Semantic layer engine
The semantic layer engine turns shared business definitions into safe, reusable SQL queries. It keeps model meaning separate from pipeline assets and warehouse connections, so the same metrics and dimensions can serve local tools and command-line query flows. This page belongs with data governance; see quality policies and linting for rule checks and data lineage for asset and query relationships.
System model
The engine is a standalone module in semantic-engine/model.go. It describes a model as a source plus named dimensions, metrics, segments, and joins. A query selects from that model, and the engine returns SQL plus the result-column mapping needed by callers.
Semantic model
A semantic model gives a business name to a source relation. Dimensions describe values used to group or filter data. Metrics describe aggregates or calculations. Segments provide named filters, while joins expose related model dimensions through a controlled relationship.
| Model part | System role |
|---|---|
| Source | Defines the table, view, or SQL relation that supplies rows. |
| Dimension | Defines a selectable and groupable business field. Time dimensions can expose named grains. |
| Metric | Defines an aggregate or a calculation over other metrics. A metric can also have a filter or window behavior. |
| Segment | Defines a reusable filter for a query. |
| Join | Defines how a model can reach a related model. |
References: semantic-engine/model.go• L3-19 semantic-engine/model.go• L21-71
Standalone engine
The engine can run with one model or with a root model and a set of related models. This keeps the semantic core usable without the full CLI dependency tree. The CLI supplies repository models and connection context around the engine, but the engine itself only needs model definitions and a query.
References: semantic-engine/engine.go• L27-83 semantic-engine/go.mod• L1-11 cmd/fetch.go• L621-642
Schema loading
Schema loading converts repository YAML files into a validated semantic catalog before query compilation. The loader checks the document shape first, then checks model rules and catalog-wide name conflicts.
Schema contract
The embedded semantic-engine/…/schema.json file is the document contract. It requires a model name and source, defines the allowed model parts, and limits values such as dimension types, join relationships, metric formats, and window types. Models that omit schema use v1; the older DAC schema identifier remains accepted for existing definitions.
References: semantic-engine/…/schema.json• L1-59 semantic-engine/…/schema.json• L105-249 semantic-engine/loader.go• L15-32 semantic-engine/engine_test.go• L181-217
Repository catalog
LoadDir reads .yml and .yaml files throughout the semantic directory tree. It skips hidden paths and unrelated files, sorts the input paths, and returns models keyed by their unique names. LoadDirPartial keeps valid models available while recording invalid models for callers that can isolate errors by model.
The CLI finds the repository root from the query input and loads the repository-level semantic directory. An asset identifies the pipeline, connection, and SQL dialect; it does not change where semantic definitions come from.
The loading sequence is shown below.
flowchart TD
A[Repository or query input] --> B[Find repository root]
B --> C[Read semantic directory]
C --> D[Validate YAML against v1 schema]
D --> E[Build model]
E --> F[Validate model rules]
F --> G[Check unique model names]
G --> H[Semantic model catalog]
H --> I[Initialize engine for a query]
References: semantic-engine/loader.go• L35-82 semantic-engine/loader.go• L85-134 semantic-engine/loader.go• L146-179 cmd/fetch.go• L700-718
Query compilation
The engine compiles a query from selected dimensions, metrics, filters, segments, sorting, and a row limit. It validates the request, resolves the needed model fields, and produces SQL that preserves the requested grouping and calculation order.
Query inputs
The query model is a small request contract. It allows callers to refer to a time dimension with a granularity and to use either structured filters or SQL filter expressions.
| Query input | Purpose |
|---|---|
| Dimensions | Select and group fields from the root or a safe related model. |
| Metrics | Select base, derived, or window calculations. |
| Filters | Restrict rows or aggregated results. |
| Segments | Apply named model filters. |
| Sort and limit | Control result order and size. |
References: semantic-engine/model.go• L73-98 semantic-engine/engine.go• L250-280
Metric calculation
A metric can be a direct SQL aggregate or a derived expression that references other metrics with {metric_name}. The engine expands the dependency chain and protects division by zero. A window metric runs over grouped results, so the engine builds an inner grouped query before applying the window calculation.
References: semantic-engine/engine.go• L135-153 semantic-engine/engine.go• L345-492 semantic-engine/engine.go• L495-565
Query validation
Validation stops a query before SQL is returned when it has no selected field, names an unknown field, uses an invalid time grain, applies an invalid filter, or names an unknown segment. Model validation also rejects missing names, missing expressions, duplicate field names, unresolved metric references, and metric cycles.
References: semantic-engine/engine.go• L86-154 semantic-engine/engine.go• L229-247 semantic-engine/engine.go• L300-343 semantic-engine/engine_test.go• L696-971
Join graph
The join graph lets a query use dimensions from related semantic models without allowing every declared relationship to affect metric results. The root model is the query anchor, and the engine adds only the paths needed by the requested fields or filters.
Safe relation graph
The graph treats one_to_one and many_to_one relationships as safe query paths because they do not add fanout to the root metric grain. one_to_many and many_to_many relationships remain valid model descriptions, but the engine does not traverse them for semantic metric queries.
The graph can follow more than one safe hop. A join uses its explicit target key when present; otherwise it uses the target model primary key. Custom SQL can replace the key-based condition when a relation needs more than one match rule.
References: semantic-engine/graph.go• L341-400 semantic-engine/graph.go• L403-463 semantic-engine/engine_test.go• L1236-1480
Dimension resolution
A qualified name such as customers.country selects a dimension through a named relation. An unqualified name is accepted only when the reachable graph contains one clear match. The plan then adds the required joins and gives joined fields safe output names so callers can map result columns back to the requested fields.
This resolution links query meaning to SQL shape. The engine qualifies root fields when joins are present, uses the selected relation alias for joined fields, and reports ambiguity instead of choosing a path silently.
References: semantic-engine/graph.go• L47-108 semantic-engine/graph.go• L127-215 semantic-engine/graph.go• L242-379 semantic-engine/engine.go• L256-297
CLI workflows
The CLI exposes the semantic engine through query, model validation, and semantic quality-check commands. It anchors semantic definitions to the repository while using an asset or an explicit pipeline and connection to run a request against a data source.
Semantic command catalog
The semantic command group loads the repository catalog once for each operation, then applies an optional model selection. It supports plain and JSON reports, environment selection, connection override, and an explicit semantic-directory path. Invalid model files remain visible in the report, while an unknown requested model stops the command.
The catalog also resolves each model's connection. A command-level connection overrides source.connection; the selected environment supplies configuration and schema-prefix context for warehouse work.
References: cmd/semantic.go• L24-65 cmd/semantic.go• L158-241 cmd/semantic.go• L259-308 cmd/semantic.go• L311-376
Query workflow
The query workflow loads the semantic catalog, builds an engine for the selected root model, compiles the request, and returns rows in the requested output format. An asset provides execution context when present; explicit pipeline and connection inputs provide that context when no asset anchors the query.
The main query paths are shown below.
sequenceDiagram
participant User
participant CLI
participant Catalog as Semantic catalog
participant Engine
participant Warehouse
User->>CLI: Query dimensions and metrics
CLI->>Catalog: Load repository definitions
Catalog-->>CLI: Validated models
CLI->>Engine: Compile query
Engine-->>CLI: SQL and column map
CLI->>Warehouse: Run SQL
Warehouse-->>CLI: Rows
CLI-->>User: JSON or CSV result
References: cmd/fetch.go• L621-642 cmd/fetch.go• L700-718 semantic-engine/engine.go• L229-280
Validation workflow
semantic validate checks each selected model and can dry-run its model queries and quality checks when a usable connection is available. Without a connection, it still checks the semantic definition and reports that warehouse validation was skipped; a connection passed by flag is required to be usable.
semantic check runs the quality checks defined on the selected models against the warehouse. It reports pass, skip, fail, and error results, returns a failure status when a check or model cannot run, and treats a run with no checks as a failure rather than a passing result.
The workflow reports definition errors at the semantic boundary. This keeps invalid models from reaching SQL compilation and lets command-line checks fail early.
References: cmd/semantic.go• L68-141 cmd/semantic.go• L445-547 cmd/semantic.go• L584-639
Integration coverage
The semantic integration suite checks the complete path from repository definitions to warehouse results. It uses small DuckDB data sets so the tests can verify both query behavior and the errors that users see at the CLI boundary.
Semantic definitions
The integration fixtures define an orders model with time grains, base and derived metrics, a filtered metric, a window metric, and reusable segments. It joins a customers model through a many-to-one customer key. These definitions test the same model relationships that users express in repository YAML.
References: integration-tests/…/orders.yml• L1-59 integration-tests/…/customers.yml• L1-19 integration-tests/…/pipeline.yml• L1-4
CLI workflows
The end-to-end cases cover the main ways a semantic query enters the system:
| Workflow | Guarantee |
|---|---|
| Asset anchor with semantic flags | The CLI loads the repository model and uses the asset for pipeline and connection context. |
| Window metric query | Grouping, filtering, sorting, and a window calculation produce the expected JSON result. |
| Pipeline plus explicit connection | A query can run without an anchor asset when the connection is supplied. |
| Joined dimension query | A related dimension can drive a result through the semantic join graph. |
| Unknown metric | An invalid semantic request returns a non-zero exit and a clear compile error. |
The suite compares JSON or CSV results rather than only checking that the command exits. This gives coverage for both the semantic contract and the returned data shape.
References: integration-tests/integration_test.go• L805-948 integration-tests/…/expected-cli-flags.json• L1-28 integration-tests/…/expected-window.json• L1-52 integration-tests/…/expected-customer-country.csv• L1-5 integration-tests/…/expected-unknown-metric.json• L1-2
Change checklist
When these files or sections are changed, remember to consider these:
- A schema field change must stay aligned across the JSON schema, the model contract, and the YAML loading path.
- A join relationship or key change must preserve safe-path rules, qualified dimension resolution, and joined-result aliases.
- A metric or window rule change must preserve dependency validation and the inner-versus-outer query boundary.
- A change to repository semantic-path discovery or model selection must cover default paths, explicit paths, and selected invalid models.
- A change to connection resolution must preserve the difference between a missing optional connection during validation and a required connection during quality checks.
- A change to environment schema-prefix handling must keep validation and quality-check SQL pointed at the same tables as semantic queries.
- A change to result-column naming must remain aligned with callers that map
QueryColumn.FieldtoQueryColumn.Nameand with JSON or CSV expectations.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A YAML file fails schema or model validation | The catalog cannot load the model, so semantic query compilation stops. | Keep the definition within the embedded v1 contract and model rules. |
| Two files use the same model name | The catalog rejects the duplicate and cannot choose a source model. | Keep model names unique across the semantic directory. |
| A query uses a fanout relation or an unsafe path | The requested joined field cannot be resolved for a semantic metric query. | Use a one_to_one or many_to_one path with a valid target key. |
| A field name is present in more than one reachable model | Compilation fails instead of selecting an arbitrary dimension. | Use a qualified name such as customers.country. |
| A metric reference is unknown or circular | The engine cannot produce a valid calculation. | Resolve metric references and keep dependency chains acyclic. |
| A window metric depends on a mixed aggregate expression | The grouped inner query cannot safely provide the window input. | Split the base aggregate and derived calculation into separate metrics. |
semantic check has no usable connection or no selected checks | The command cannot run warehouse checks and exits with failure. | Set source.connection or --connection, and select models that define checks. |
| An explicit semantic path is missing or is not a directory | The CLI stops instead of silently reporting an empty catalog. | Pass the directory that holds the semantic model files. |
| A connection override cannot run queries | Validation or checks fail before warehouse work can start. | Use a configured connection that supports queries. |
Key files
| File | Why to read it |
|---|---|
| semantic-engine/model.go | Defines the shared model and query vocabulary used by loaders, callers, and the engine. |
| semantic-engine/loader.go | Shows how repository YAML becomes a validated model catalog. |
| semantic-engine/…/schema.json | Defines the accepted semantic-definition contract. |
| semantic-engine/engine.go | Explains model validation and the boundary between a semantic query and generated SQL. |
| semantic-engine/graph.go | Explains safe join paths, dimension resolution, and joined query planning. |
| cmd/semantic.go | Shows the CLI lifecycle for model selection, validation, quality checks, connections, and environment context. |
| semantic-engine/engine_test.go | Shows the unit coverage for loading, validation, calculations, windows, filters, and joins. |
| cmd/fetch.go | Shows how the CLI finds repository models and places the standalone engine in the query flow. |
| integration-tests/…/orders.yml | Provides the main integration definition with metrics, segments, windows, and a join. |
| integration-tests/integration_test.go | Defines the end-to-end semantic query workflows and their result checks. |