Skip to content

Latest commit

 

History

History
909 lines (735 loc) · 29.9 KB

native-format.md

File metadata and controls

909 lines (735 loc) · 29.9 KB

Native sqlctx Format

This document defines the native sqlctx project format consumed by the Rust native runtime and the Python native adapter.

The native format has two source forms:

  • YAML semantic project files.
  • SQL semantic definition files.

The native format is the runtime contract. External formats such as LookML, MetricFlow, Hex, Rill, Malloy, Omni, Superset, GoodData, Snowflake Cortex, ThoughtSpot, Holistics, Tableau, AtScale SML, BSL, Yardstick, and Graphene GSQL should be converted into this format by Python importers before they are expected to run through the Rust native runtime.

Rust Loader Scope

The Rust runtime and Rust CLI directory loader intentionally have a smaller direct input surface than Python:

  • .yml / .yaml: native sqlctx YAML or Cube YAML.
  • .sql: native sqlctx SQL definition files.

They do not auto-detect LookML, MetricFlow/dbt manifests, Hex, Rill, Malloy, Omni, Superset, GoodData, Snowflake Cortex, ThoughtSpot, Holistics, Tableau, AtScale SML, BSL, Yardstick, or other external source formats. Convert those formats through the Python CLI/API first, then load the exported native YAML/SQL with the Rust runtime.

Versioning

Current native format version: 1.

New native YAML exports must include:

version: 1

Existing files without version are treated as version 1 for compatibility.

Unsupported versions fail early. A file with version: 2 must not be silently interpreted as version 1.

Top-Level YAML Shape

version: 1

parameters:
  - name: status
    type: string
    default_value: paid

models:
  - name: orders
    table: public.orders
    primary_key: order_id
    dimensions:
      - name: status
        type: categorical
    metrics:
      - name: total_revenue
        agg: sum
        sql: amount
      - name: order_count
        agg: count

metrics:
  - name: revenue_per_order
    type: ratio
    numerator: orders.total_revenue
    denominator: orders.order_count

Top-level sections:

Field Required Notes
version No Missing means 1. New exports should include it.
models No List of model definitions. Most useful projects define at least one model.
metrics No Graph-level metrics. Rust assigns these to exactly one owning model when possible.
parameters No Graph-level parameters for templates and query-time substitution.
explores No Named Explore contracts with a base model, defaults, allowed fields, and mandatory filters.
saved_queries No Named structured queries, optionally governed by an explore.
table_calculations No Named calculations over query results, such as formulas and running totals.

Consumption catalogs use lists of named objects and may live in separate catalog-only files alongside model files. The Python CLI resolves these definitions before sending queries to the versioned Rust runtime. This does not add support for these root catalogs to the legacy Rust native-file loader.

Top-level metrics are graph-scoped in the Python runtime. The Rust runtime does not store a separate graph-metric namespace at execution time; it assigns each top-level metric to one owning model by resolving explicit model references, metric dependencies, entity dimensions, or a single-model project fallback. If Rust cannot infer exactly one owner, loading fails. Portable native files should therefore make top-level metric dependencies explicit, for example orders.total_revenue rather than total_revenue when multiple models define the same local metric name. Dotted top-level metric names are allowed and are resolved by exact metric name before model.metric parsing.

Top-level parameters remain graph-scoped in both runtimes. Query APIs interpolate parameter values before SQL compilation.

Models

Models describe physical or logical query sources.

models:
  - name: orders
    table: public.orders
    primary_key: order_id
    default_time_dimension: created_at
    default_grain: day
    freshness:
      watermark: updated_at
      ttl_seconds: 3600
    dimensions:
      - name: created_at
        type: time
        granularity: day

At least one of table, sql, or source_uri should be present unless the model extends another model that provides one.

Field Required Notes
name Yes Unique model name.
table Conditional Physical table name.
sql Conditional SQL subquery used as the model source.
source_uri Conditional Source URI for external data discovery or file-backed sources. Native loaders preserve it; execution is adapter/runtime-specific until a concrete backend maps URI sources.
extends No Parent model name. Child fields override or extend parent fields.
primary_key No Single primary key string or list of columns. Omitted, null, or empty means no known primary key; no id is inferred.
primary_key_columns No Explicit list form for primary keys.
unique_keys No List of unique key column lists.
description No Human-readable description.
dimensions No List of dimensions.
metrics No List of model-local metrics.
relationships No List of relationships from this model to other models.
segments No List of model-local named filters.
required_filters No Fields that every query using the model must filter. Enforced by Python-hosted clients before Python or Rust compilation.
required_filters_or_groups No Fields that every query using the model must filter or group by, independently for each listed field.
pre_aggregations No List of pre-aggregation definitions.
default_time_dimension No Time dimension a structured query is grouped by when it selects metrics and no dimensions, and the time axis of cumulative, time-comparison and offset-ratio metrics that select none. Ordinary aggregates in a query with its own dimensions, or in a SQL SELECT, are never grouped by it.
default_grain No Default time grain for the default time dimension.
freshness No Source freshness policy for live chart/dashboard runtimes.
security No Row/access SecurityPolicy (access gate + row_filters) enforced per query when user_attributes are supplied. See Security.
auto_dimensions No Python auto-discovery flag. Rust accepts false for compatibility and rejects true because it does not perform schema discovery.

Canonical CLI-authored files should use metrics and sql. The native loaders also accept compatibility input aliases: model-level measures for metrics, dimension/metric expr for sql, and metric measure for sql. Exports use canonical field names.

Required filters

Use model-level caller obligations to reject queries that omit a date range or combine rows across a required grouping dimension:

models:
  - name: daily_activity
    table: warehouse.daily_activity
    required_filters: [event_date]
    required_filters_or_groups: [test_name]
    dimensions:
      - name: event_date
        type: time
        granularity: day
      - name: test_name
        type: categorical
    metrics:
      - name: activity_count
        agg: count
sqlctx query --models ./models --metric daily_activity.activity_count \
  --dimension daily_activity.test_name \
  --filter "daily_activity.event_date >= '2026-01-01'"

Each listed field is mandatory, including on models reached through metric dependencies, filters, and intermediate joins. Declarations accept local names or names qualified with the declaring model. Inheritance accumulates parent and child requirements, rebinding inherited fields to the child. Empty lists are the default and impose no obligations.

Matching uses SQL column references, not text or string literals. A time-grained reference such as daily_activity.event_date__month matches event_date. required_filters cannot be satisfied by grouping; required_filters_or_groups accepts either a filter or grouping for each field. Structured dimensions count as grouping unless ungrouped is set. SQL clients must use an explicit GROUP BY (field or selected alias). Filters on an outer query do not satisfy obligations inside a CTE or subquery. The check requires a field reference; it does not prove selectivity or impose a maximum date range.

Selected segments and resolved Explore filters can satisfy the obligation. Explore default_filters still apply only when filters are omitted; replacing them with an unrelated filter fails the model requirement. Explore mandatory filters still always apply. Model invariant_filters, security policies, and metric-internal filters do not substitute for the caller obligation.

The Python CLI, HTTP /query, MCP structured queries, and standard semantic SQL (including PostgreSQL wire queries) enforce these rules before engine dispatch. Missing requirements raise ValueError and HTTP 400. Raw SQL bypass endpoints are disabled while requirements are declared. Yardstick SQL is rejected for these graphs; use structured queries or standard semantic SQL. Standalone Rust and DuckDB extension runtimes do not yet support these model options; exported definitions retain them and unsupported native loaders reject them.

Single-column primary key:

primary_key: order_id

Composite primary key:

primary_key: [order_id, line_item_id]

Equivalent explicit list form:

primary_key_columns:
  - order_id
  - line_item_id

Model Freshness

Model-level freshness describes how live chart and dashboard runtimes should decide whether source-backed results are fresh, stale, or unknown.

freshness:
  watermark: updated_at
  ttl_seconds: 3600

Fields:

Field Required Notes
watermark Conditional Dimension or source column whose MAX value represents source freshness. Prefer this for normal semantic-model usage.
sql Conditional Advanced SQL query that returns one scalar freshness marker. Use only when a source freshness marker cannot be expressed as a model dimension or physical column.
ttl_seconds No Positive integer maximum age before data is stale. Native input also accepts compatibility alias ttlSeconds; exports use ttl_seconds.

watermark and sql are mutually exclusive. A TTL without a real source watermark is accepted as configuration, but live runtimes report freshness as unknown when there is no real data_as_of timestamp to compare.

Dimensions

Dimensions are groupable attributes or reusable SQL expressions.

dimensions:
  - name: created_at
    type: time
    sql: created_at
    granularity: day
    supported_granularities: [day, week, month, quarter, year]
Field Required Notes
name Yes Unique within model.
type No categorical, time, boolean, or numeric. Defaults to categorical.
sql No SQL expression. If omitted, the dimension name is used.
granularity No Default grain for time dimensions. On DuckDB, PostgreSQL and Redshift, day and coarser grains return DATE values; hour, minute and second return timestamps.
supported_granularities No Allowed grains for time dimensions.
description No Human-readable description.
label No Display label.
format No Display format string.
value_format_name No Named display format.
parent No Parent dimension for hierarchy navigation.
window No Window expression.
public No Visibility flag (default true). When a layer is built with enforce_visibility=True, a public: false dimension cannot be projected, filtered, or ordered on.
uri No Rendering hint (default false): UIs may render this dimension's values as links. Metadata only — no effect on generated SQL.

The {model} placeholder can be used in SQL expressions that need the generated table alias:

sql: "{model}.status"

Metrics

Metrics describe aggregations or derived semantic measures.

Simple Metrics

metrics:
  - name: total_revenue
    agg: sum
    sql: amount

Simple metrics omit type; agg makes them simple. The Rust loader also accepts type: simple, but the Python loader rejects it, so portable files should leave it out.

Supported aggregations in the native contract:

  • count
  • count_distinct
  • approx_count_distinct
  • sum
  • avg
  • min
  • max
  • median
  • stddev
  • stddev_pop
  • variance
  • variance_pop

Additional aggregation names must be added deliberately to the Rust enum and tested before they are considered part of the native contract.

Derived Metrics

metrics:
  - name: net_revenue
    type: derived
    sql: total_revenue - refunds

Derived metrics can reference other metrics by name or by qualified reference.

Ratio Metrics

metrics:
  - name: revenue_per_order
    type: ratio
    numerator: total_revenue
    denominator: order_count

The runtime is responsible for safe divide behavior.

Cumulative Metrics

metrics:
  - name: cumulative_revenue
    type: cumulative
    sql: total_revenue
  - name: rolling_7d_revenue
    type: cumulative
    sql: total_revenue
    window: "7 days"
  - name: mtd_revenue
    type: cumulative
    sql: total_revenue
    grain_to_date: month

sql names the base metric to accumulate and is required (or window_expression for a raw window function). The Rust loader also accepts base_metric in place of sql, but the Python loader rejects a cumulative metric without sql, so portable files should use sql. Omit window and grain_to_date for a running total; set window to a "<number> <unit>" interval for a rolling window, or grain_to_date (day, week, month, quarter, year) for a period-to-date total.

Supported cumulative behavior must be validated before SQL generation. Queries missing a usable time dimension should fail before producing SQL.

Time Comparison Metrics

metrics:
  - name: revenue_yoy
    type: time_comparison
    base_metric: total_revenue
    comparison_type: yoy
    calculation: percent_change
    time_offset: "1 year"

Supported comparison types:

  • yoy
  • mom
  • wow
  • dod
  • qoq
  • prior_period

Supported calculations:

  • difference
  • percent_change
  • ratio

Conversion Metrics

metrics:
  - name: signup_to_purchase
    type: conversion
    entity: user_id
    base_event: "event_type = 'signup'"
    conversion_event: "event_type = 'purchase'"
    conversion_window: "7 days"

Initial native-runtime rule:

  • One conversion metric per query.
  • Conversion metrics do not mix with regular metrics.

Retention Metrics

metrics:
  - name: signup_retention
    type: retention
    entity: user_id
    cohort_event: "event_type = 'signup'"
    activity_event: "event_type = 'active'"
    periods: 7
    retention_granularity: day

Initial native-runtime rule:

  • One retention metric per query.
  • Retention metrics do not mix with regular metrics.

Cohort Metrics

metrics:
  - name: multi_platform_users
    type: cohort
    entity: user_id
    inner_metrics:
      - name: platform_count
        agg: count_distinct
        sql: platform
    having: platform_count >= 2
    agg: count

Initial native-runtime rule:

  • One cohort metric per query.
  • Cohort metrics do not mix with regular metrics.

Common Metric Fields

Field Notes
name Required. Unique within owner scope.
type derived, ratio, cumulative, time_comparison, conversion, retention, or cohort. Omit for simple metrics.
agg Aggregation for simple metrics and some cohort inner metrics.
sql SQL expression or derived expression.
filters List of SQL predicates applied to the metric.
fill_nulls_with Value used to fill null metric results.
description Human-readable description.
label Display label.
format Display format string.
value_format_name Named display format.
drill_fields Suggested drill fields.
non_additive_dimension Semi-additive time dimension. The measure is aggregated over only the last (or first) snapshot per group — implemented with a QUALIFY on QUALIFY-capable engines (DuckDB, Snowflake, BigQuery, Databricks, Spark, ClickHouse). Raises UnsupportedMetricError on other dialects or when combined with a fan-out (symmetric-aggregate) join, unless SemanticLayer(allow_non_additive_unsafe=True).
non_additive_window "max" (default, last value) or "min" (first value) for non_additive_dimension.
non_additive_window_groupings Dimensions the semi-additive snapshot is taken per (MetricFlow window_groupings, e.g. balance-per-user). When set, the last/first snapshot partitions by these regardless of the query's grouping; when unset, it partitions by the query's own non-time grouping dimensions.

Relationships

Relationships define how models join.

relationships:
  - name: customers
    type: many_to_one
    foreign_key: customer_id
    primary_key: customer_id
Field Required Notes
name Yes Target model name.
type No Defaults to many_to_one.
foreign_key Conditional Single column or list of source columns.
foreign_key_columns Conditional Explicit source-column list.
primary_key Conditional Single column or list of target columns.
primary_key_columns Conditional Explicit target-column list.
through For many-to-many Junction model.
through_foreign_key For many-to-many Source-to-through key.
through_foreign_key_columns For many-to-many Explicit source-to-through key columns.
related_foreign_key For many-to-many Through-to-target key.
related_foreign_key_columns For many-to-many Explicit through-to-target key columns.
sql No Custom join SQL using {from} and {to} runtime placeholders.

Set foreign_key on every keyed relationship. The Python runtime does not infer it: a many_to_one, one_to_many, or one_to_one relationship without foreign_key adds no join, so queries across it fail with No join path found, and the Python CLI's Rust engine path rejects it. The standalone Rust loader still applies compatibility defaults (many_to_one uses {name}_id; one_to_many and one_to_one use id on the related side), so files that rely on them behave differently across runtimes. An omitted primary_key resolves to the target model's declared primary key in both runtimes.

When sql is present, Python and Rust use it instead of the FK/PK-generated predicate. {from} is replaced with the source model's runtime alias and {to} with the target model's runtime alias. Reverse graph traversal swaps the placeholders automatically.

Relationship types:

  • many_to_one
  • one_to_one
  • one_to_many
  • many_to_many

Which rows a joined query keeps

The model that owns the selected metrics is the preserved side of the join. Models that only supply dimensions are LEFT JOINed onto it, across every hop:

  • A metric row whose key is NULL or matches no dimension row is counted in a NULL dimension group, so a breakdown adds up to the ungrouped total.
  • A dimension row that no metric row references is not a group. orders.revenue by customers.region lists no region without orders.
  • A filter or segment on a dimension model's column keeps only metric rows that have a matching dimension row, so it removes the NULL group. That includes IS NULL predicates; filter on the metric model's own key column to inspect unmatched rows.
  • The same holds when the metric sits on the "one" side: customers.customer_count by orders.status keeps every customer once, with customers without orders in a NULL status group.

Metrics from several models keep each model's own rows, so their groups are the union of those populations. A query with dimensions and no metric starts from its first dimension's model.

To list every dimension member, including those without metric rows, either query through an Explore whose base model is the dimension model, or also select a metric owned by that model:

models:
  - name: customers
    table: customers
    primary_key: id
    dimensions:
      - name: region
        type: categorical
    metrics:
      - name: customer_count
        agg: count
  - name: orders
    table: orders
    primary_key: id
    relationships:
      - name: customers
        type: many_to_one
        foreign_key: customer_id
    metrics:
      - name: revenue
        agg: sum
        sql: amount
      - name: order_count
        agg: count

explores:
  - name: by_customer
    model: customers
# Every customer region; regions without orders have NULL revenue and a zero count.
sqlctx query --explore by_customer --metric orders.revenue --metric orders.order_count --dimension region
# Both populations: regions without orders and orders without a region.
sqlctx query --metric orders.revenue --metric customers.customer_count --dimension customers.region

Releases through 0.13.1 anchored a single-model metric query on its first dimension's model instead: it listed dimension members without metric rows and dropped metric rows without a matching dimension row.

Composite relationship:

relationships:
  - name: order_items
    type: many_to_one
    foreign_key: [order_id, line_item_id]
    primary_key: [order_id, line_item_id]

Many-to-many relationship:

relationships:
  - name: products
    type: many_to_many
    through: order_items
    through_foreign_key: order_id
    related_foreign_key: product_id
    primary_key: product_id

Segments

Segments are named model-local filters.

segments:
  - name: completed
    sql: "{model}.status = 'completed'"
    description: Completed orders
Field Required Notes
name Yes Unique within model.
sql Yes SQL predicate.
description No Human-readable description.
public No Visibility flag. Defaults to true.

Parameters

Parameters are graph-level values that can be used in templates and filters.

parameters:
  - name: status
    type: string
    default_value: paid
    allowed_values: [paid, refunded, pending]

Supported types:

  • string
  • number
  • date
  • unquoted
  • yesno
Field Required Notes
name Yes Unique parameter name.
type Yes Parameter type.
description No Human-readable description.
label No Display label.
default_value No Default value.
allowed_values No Allowed values.
default_to_today No Date helper flag.

Pre-Aggregations

Pre-aggregations describe materialized rollups.

pre_aggregations:
  - name: daily_revenue
    type: rollup
    measures: [total_revenue]
    dimensions: [status]
    time_dimension: created_at
    granularity: day
    refresh_key:
      every: 1 hour
Field Required Notes
name Yes Unique within model.
type No Defaults to rollup.
measures No Metric names.
dimensions No Dimension names.
time_dimension No Time dimension name.
granularity No Time grain.
partition_granularity No Partition grain.
build_range_start No Build range SQL or expression.
build_range_end No Build range SQL or expression.
scheduled_refresh No Defaults to true.
refresh_key No Refresh settings.
indexes No Index definitions.

Supported pre-aggregation types:

  • rollup
  • original_sql
  • rollup_join
  • lambda

Refresh key:

refresh_key:
  every: 1 hour
  sql: "select max(updated_at) from orders"
  incremental: true
  update_window: 7 days

Index:

indexes:
  - name: by_status
    columns: [status]
    type: regular

SQL Definition Files

SQL definition files are the second native source form. They can define models and graph objects without YAML.

Example:

MODEL (
  name orders,
  table public.orders,
  primary_key order_id
);

DIMENSION (
  name status,
  type categorical,
  sql status
);

METRIC (
  name total_revenue,
  agg sum,
  sql amount
);

Definitions that follow a MODEL statement belong to that model. The Rust loader also accepts an explicit model orders property inside DIMENSION and METRIC, but the Python parser fails on it, so portable files should leave it out.

SQL files may also use YAML frontmatter for the model and SQL definitions for metrics, segments, parameters, and pre-aggregations.

---
version: 1
name: orders
table: public.orders
primary_key: order_id
---

METRIC (
  name total_revenue,
  agg sum,
  sql amount
);

Versioning for SQL frontmatter follows the same YAML contract when a version field is present. Missing frontmatter version means version 1; unsupported frontmatter versions fail early; version is removed before model metadata parsing.

Environment Variables

Native YAML supports environment substitution:

table: ${ORDERS_TABLE:-public.orders}

Supported forms:

  • ${ENV_VAR}
  • ${ENV_VAR:-default}
  • $ENV_VAR

Missing variables without defaults are preserved for later handling.

Unknown Fields

Native format version 1 is a strict runtime contract for native YAML and native SQL frontmatter. Rust rejects unknown fields in documented native objects instead of silently dropping them.

  • New native fields must be documented here before being treated as supported.
  • Known enum-like fields, including dimension type, dimension granularity, dimension supported_granularities, model default_grain, metric type, metric agg, metric retention_granularity, relationship type, pre-aggregation type, pre-aggregation granularity, and pre-aggregation partition_granularity, reject unsupported values.
  • Source-adapter-specific fields belong under metadata or meta rather than new top-level native fields.
  • Python importers should not leak external adapter concepts into native YAML unless they are part of this document.

Compatibility Rules

  1. Missing version means version 1.
  2. New exports include version: 1.
  3. Unsupported versions fail early.
  4. Native YAML and native SQL are the only direct Rust runtime input contracts.
  5. External formats should be normalized to native YAML/SQL before Rust runtime use.
  6. Rust and Python may generate different SQL text, but shared fixtures should prove equivalent validation and result behavior.

Minimal Valid Project

version: 1
models:
  - name: orders
    table: orders

Recommended Project Shape

version: 1

parameters:
  - name: start_date
    type: date

models:
  - name: orders
    table: public.orders
    primary_key: order_id
    default_time_dimension: created_at
    default_grain: day
    dimensions:
      - name: order_id
        type: categorical
      - name: customer_id
        type: categorical
      - name: status
        type: categorical
      - name: created_at
        type: time
        sql: created_at
        granularity: day
        supported_granularities: [day, week, month, quarter, year]
    metrics:
      - name: order_count
        agg: count
      - name: total_revenue
        agg: sum
        sql: amount
      - name: customer_count
        agg: count_distinct
        sql: customer_id
      - name: average_order_value
        type: ratio
        numerator: total_revenue
        denominator: order_count
    segments:
      - name: paid
        sql: "{model}.status = 'paid'"
    relationships:
      - name: customers
        type: many_to_one
        foreign_key: customer_id
        primary_key: customer_id

  - name: customers
    table: public.customers
    primary_key: customer_id
    dimensions:
      - name: customer_id
        type: categorical
      - name: country
        type: categorical

metrics:
  - name: revenue_per_customer
    type: ratio
    numerator: orders.total_revenue
    denominator: orders.customer_count

The top-level metric depends on one model, so both runtimes can load it. A top-level metric that combines metrics from two models (for example orders.total_revenue / customers.customer_count) works in the Python runtime, but the Rust loader rejects it because it cannot pick a single owning model.

Authoring contracts

Use the default full sqlctx contract for native semantics such as non-additive metrics, policies, and other runtime features:

sqlctx validate ./models --authoring-mode sqlctx

To author a model intended for Ossie core interchange, check representability while editing, before exporting:

sqlctx validate ./models --authoring-mode ossie-portable --ossie-expression-dialect ANSI_SQL

This uses the same portable-only synthesis checks as convert --ossie-portable-only. It reports stable ossie.synthesis.* diagnostics and object paths for semantics that require sqlctx or cannot be represented. Dropped or approximated source semantics are errors in this mode. The declared expression dialect must describe the actual SQL; validation does not translate SQL or rewrite source files. The default profile is ossie-core at the pinned 0.2.0.dev0 schema; select --ossie-consumer-profile dbt-1.12 to validate against its supported 0.1.1 schema instead. These versions come from the canonical pinned profile definitions; the 0.1.0 dbt compatibility alias is not used for synthesized validation.

Portable validation certifies a core representation, not execution by every consumer. Preserved external expressions still have to lower through the normal strict source importer; schema validity alone is insufficient. Extension-dependent native models remain valid under the full sqlctx contract, but fail the portable contract. Invalid source fails both. --engine controls separate runtime compatibility checks, and --live checks database schema; neither selects the authoring contract. The default authoring contract remains sqlctx.

Validation never exports, migrates, or replaces the authoritative source. When ready to export, continue to supply an explicit scope, expression dialect, and --ossie-portable-only to convert.