Skip to content

Commit 5f35d6d

Browse files
authored
Check nested properties on Dremio servers (#1838)
Struct fields compile to aliased field access, which Dremio reads. Dremio has no lambda to filter an array with, so a rule on array items flattens each array on the path with FLATTEN in a subquery of its own, numbering the rows first, and counts the rows with an item that breaks it. A {property} placeholder on a struct field becomes customer['email'], which Dremio reads without an alias.
1 parent fc6452e commit 5f35d6d

8 files changed

Lines changed: 240 additions & 31 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## [Unreleased]
99

10+
### Fixed
11+
- `datacontract test` checks the constraints and quality rules of nested properties (struct fields and array items) on Dremio servers
12+
1013
## [1.2.11] - 2026-11-17
1114

1215
### Added

‎datacontract/engines/checks/create_checks.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959
_NESTED_CHECK_SERVER_TYPES = {
6060
"dataframe",
6161
"databricks",
62+
"dremio",
6263
"duckdb",
6364
"iceberg",
6465
"kafka",
@@ -237,6 +238,10 @@ def identifier(name: str | tuple[str | Hop, ...], forced: bool) -> str:
237238
if dialect == "snowflake" and isinstance(name, tuple):
238239
# Snowflake reaches into a column's value with `:`; a dot would name a table's column
239240
return parts[0] + "".join(f":{part}" for part in parts[1:])
241+
if dialect == "dremio" and isinstance(name, tuple):
242+
# Without a table alias, Dremio reads `customer.email` as the column email of a table customer
243+
fields = [part for part in steps[1:] if isinstance(part, str)]
244+
return parts[0] + "".join(f"[{exp.Literal.string(field).sql(dialect=dialect)}]" for field in fields)
240245
return ".".join(parts)
241246

242247
if instance is not None:

‎datacontract/engines/ibis/connections/dremio.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,9 @@ class DremioCompiler(TrinoCompiler):
326326
dialect = Dremio
327327
type_mapper = DremioType
328328

329+
def visit_Unnest(self, op, *, arg):
330+
return self.f.flatten(arg)
331+
329332
class Backend(SQLBackend, NoExampleLoader):
330333
name = "dremio"
331334
compiler = DremioCompiler()

‎datacontract/engines/ibis/ibis_check_execute.py‎

Lines changed: 112 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -309,10 +309,15 @@ def model_row_count() -> int:
309309
if spec.metric == MetricType.ROW_COUNT:
310310
named = t.count().name(spec.key)
311311
elif spec.metric == MetricType.MISSING_COUNT:
312-
predicate = _row_predicate(
313-
t, columns, spec.path, lambda c: _missing_expr(c, spec.missing_values), spec.value_type
314-
)
315-
named = _count_true(predicate).name(spec.key)
312+
313+
def _missing(c, _spec=spec):
314+
return _missing_expr(c, _spec.missing_values)
315+
316+
if _flattens_items(t, spec.path):
317+
_run_item_count(run, spec, _matching_items(t, columns, spec.path, _missing), model_row_count())
318+
else:
319+
predicate = _row_predicate(t, columns, spec.path, _missing, spec.value_type)
320+
named = _count_true(predicate).name(spec.key)
316321
elif spec.metric == MetricType.INVALID_COUNT:
317322
dtype = _resolve_dtype(schema, spec.path)
318323
# ibis reports no type inside a nested Snowflake column, where a value has the type it is cast to
@@ -339,11 +344,17 @@ def _invalid(c, _t=t, _dtype=dtype, _spec=spec, _flag=unconstrained, _cast=cast)
339344
return ibis.literal(False)
340345
return built
341346

342-
expr = _row_predicate(t, columns, spec.path, _invalid, spec.value_type)
347+
flattened = _flattens_items(t, spec.path)
348+
if flattened:
349+
expr = _matching_items(t, columns, spec.path, _invalid)
350+
else:
351+
expr = _row_predicate(t, columns, spec.path, _invalid, spec.value_type)
343352
if unconstrained:
344353
# No validity constraints => nothing can be invalid.
345354
_set_impl(run, spec.key, "invalid_count = 0 (no validity constraints configured)", None)
346355
_evaluate(run, spec, 0, row_count=model_row_count())
356+
elif flattened:
357+
_run_item_count(run, spec, expr, model_row_count())
347358
else:
348359
named = _count_true(expr).name(spec.key)
349360
elif spec.metric == MetricType.DUPLICATE_COUNT:
@@ -518,37 +529,50 @@ def _select_columns(columns, sensitive, wanted):
518529

519530

520531
def _samples_for(t, columns, schema, spec: CheckSpec, identifiers, sensitive):
532+
# A nested path is not a column; show the one it starts from.
533+
root = _root(spec.path) if spec.path else None
534+
select_cols = _select_columns(columns, sensitive, [*identifiers, root])
535+
flattened = _flattens_items(t, spec.path)
521536
if spec.metric == MetricType.DUPLICATE_COUNT:
522537
if not _is_item_duplicate(spec):
523538
return _duplicate_samples(t, columns, sensitive, spec)
524-
predicate = _item_duplicate_predicate(t, columns, spec.path, spec.value_type)
525-
elif spec.metric == MetricType.MISSING_COUNT:
526-
predicate = _row_predicate(
527-
t, columns, spec.path, lambda c: _missing_expr(c, spec.missing_values), spec.value_type
528-
)
529-
else: # INVALID_COUNT
530-
dtype = _resolve_dtype(schema, spec.path)
531-
cast = _is_nested_path(spec.path) and _backend_name(t) == "snowflake"
532-
unconstrained = []
539+
if flattened:
540+
# the repeats are counted per array, in groups that keep no column of the row
541+
return None
542+
rows = t.filter(_item_duplicate_predicate(t, columns, spec.path, spec.value_type))
543+
else:
544+
if spec.metric == MetricType.MISSING_COUNT:
533545

534-
def _invalid(c, _flag=unconstrained):
535-
import ibis
546+
def build(c):
547+
return _missing_expr(c, spec.missing_values)
548+
549+
else: # INVALID_COUNT
550+
dtype = _resolve_dtype(schema, spec.path)
551+
cast = _is_nested_path(spec.path) and _backend_name(t) == "snowflake"
552+
unconstrained = []
536553

537-
built = _invalid_expr(t, c, c.type() if cast else dtype, spec)
538-
if built is None:
539-
_flag.append(True)
540-
return ibis.literal(False)
541-
return built
554+
def build(c, _flag=unconstrained):
555+
import ibis
542556

543-
predicate = _row_predicate(t, columns, spec.path, _invalid, spec.value_type)
544-
if unconstrained:
557+
built = _invalid_expr(t, c, c.type() if cast else dtype, spec)
558+
if built is None:
559+
_flag.append(True)
560+
return ibis.literal(False)
561+
return built
562+
563+
if flattened:
564+
import ibis
565+
566+
items = _matching_items(t, columns, spec.path, build, select_cols or t.columns)
567+
# one sample for each row, however many of its items break the rule
568+
items = items.mutate(__dc_first__=ibis.row_number().over(group_by=_ROW_NUMBER.format(0)))
569+
rows = items.filter(items["__dc_first__"] == 0)
570+
else:
571+
rows = t.filter(_row_predicate(t, columns, spec.path, build, spec.value_type))
572+
if spec.metric == MetricType.INVALID_COUNT and unconstrained:
545573
return None
546574

547-
# A nested path is not a column; show the one it starts from.
548-
root = _root(spec.path) if spec.path else None
549-
select_cols = _select_columns(columns, sensitive, [*identifiers, root])
550-
rows = t.filter(predicate)
551-
rows = rows.select(select_cols) if select_cols else rows
575+
rows = rows.select(select_cols or t.columns)
552576
return _df_to_records(rows.limit(_FAILED_SAMPLE_LIMIT).execute())
553577

554578

@@ -916,9 +940,19 @@ def _run_item_duplicate(run: Run, t, columns, spec: CheckSpec, row_count: int):
916940
917941
Counted in parent rows.
918942
"""
919-
bad = t.filter(_item_duplicate_predicate(t, columns, spec.path, spec.value_type))
943+
if _flattens_items(t, spec.path):
944+
rows, item, steps = _flattened_items(t, columns, spec.path)
945+
value = _struct_path(item, steps)
946+
# each array on its own: the items of other arrays in the same row are no repeats
947+
numbers = dict.fromkeys(_ROW_NUMBER.format(level) for level in (0, spec.path.count(Hop.ITEMS) - 1))
948+
arrays = rows.group_by(list(numbers)).aggregate(__dc_values__=value.count(), __dc_distinct__=value.nunique())
949+
bad = arrays.filter(arrays["__dc_values__"] > arrays["__dc_distinct__"])
950+
repeating = bad[_ROW_NUMBER.format(0)].nunique()
951+
else:
952+
bad = t.filter(_item_duplicate_predicate(t, columns, spec.path, spec.value_type))
953+
repeating = bad.count()
920954
_record_sql(run, spec, bad)
921-
repeats = int(bad.count().execute())
955+
repeats = int(repeating.execute())
922956
_evaluate(run, spec, repeats, row_count=row_count)
923957
_update_diagnostics(run, spec.key, {"failed_rows": repeats})
924958

@@ -1403,6 +1437,54 @@ def _row_predicate(t, columns: dict, path: tuple[str | Hop, ...], build, value_t
14031437
return items.filter(lambda i: _element_predicate(i, path[array + 1 :], build)).length() > 0
14041438

14051439

1440+
def _flattens_items(t, path: tuple[str | Hop, ...]) -> bool:
1441+
"""Whether a rule at ``path`` reads array items flattened into rows of their own, as on Dremio.
1442+
1443+
Dremio has no lambda to filter an array with (``FILTER(array, x -> ...)``), and flattens an
1444+
array only in a select list (``FLATTEN(array)``, not ``UNNEST``), so such a rule runs a query of its own.
1445+
"""
1446+
return Hop.ITEMS in path and _backend_name(t) == "dremio"
1447+
1448+
1449+
# The number of a row of the table, and of a row each array but the last is flattened into
1450+
_ROW_NUMBER = "__dc_row_{}__"
1451+
1452+
1453+
def _flattened_items(t, columns, path: tuple[str | Hop, ...], keep=()):
1454+
"""One row per item of the arrays on ``path``, as ``(rows, item, steps)``: the last array's item
1455+
and the struct fields ``steps`` below it.
1456+
1457+
Each array is flattened in a subquery of its own, after its rows are numbered, so the rows keep
1458+
the number of the row of ``t`` they come from (``__dc_row_0__``) and of each array's row.
1459+
``keep`` names columns of ``t`` the rows carry along.
1460+
"""
1461+
import ibis
1462+
1463+
rows, item, steps, numbers = t, _resolve_col(columns, path[0]), path[1:], []
1464+
while Hop.ITEMS in steps:
1465+
array = steps.index(Hop.ITEMS)
1466+
numbers.append(_ROW_NUMBER.format(len(numbers)))
1467+
rows = rows.mutate(**{numbers[-1]: ibis.row_number()})
1468+
items = _struct_path(rows[item], steps[:array]).unnest()
1469+
item = f"__dc_item_{len(numbers)}__"
1470+
rows = rows.select(*numbers, *keep, **{item: items})
1471+
steps = steps[array + 1 :]
1472+
return rows, rows[item], steps
1473+
1474+
1475+
def _matching_items(t, columns, path: tuple[str | Hop, ...], build, keep=()):
1476+
"""The flattened items at ``path`` that satisfy ``build``; see ``_flattened_items``."""
1477+
rows, item, steps = _flattened_items(t, columns, path, keep)
1478+
return rows.filter(_element_predicate(item, steps, build))
1479+
1480+
1481+
def _run_item_count(run: Run, spec: CheckSpec, items, row_count: int):
1482+
"""A missing or invalid count over flattened ``items``: the rows with an item that breaks the rule."""
1483+
counted = items[_ROW_NUMBER.format(0)].nunique()
1484+
_record_sql(run, spec, counted)
1485+
_evaluate(run, spec, int(counted.execute()), row_count=row_count)
1486+
1487+
14061488
def _element_predicate(element, steps, build):
14071489
if Hop.ITEMS not in steps:
14081490
value = _struct_path(element, steps[:1])

‎docs/docs/schema.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,7 @@ These are common sources of confusion. They are valid ODCS and appear in exports
236236
- **`logicalTypeOptions.format`** — never enforced, on any property. On a `string` property (`email`, `uuid`, `uri`, …) use `pattern` for an enforceable equivalent. On a `date`, `timestamp` or `time` property `format` holds a date pattern such as `yyyy-MM-dd`, and `pattern` is *not* an equivalent there: by the time a check runs, the column has already been parsed as a date, so there is no string left to match. Such a column is validated as a date, in whatever format the server stores it.
237237
- **Descriptive attributes** — `description`, `businessName`, `examples`, `tags`, `classification`, `criticalDataElement`, `transformSourceObjects`, and `customProperties` of a property. `authoritativeDefinitions` generates no check either, but it *is* resolved and inlined before the checks are built — see [Link your Semantics](./semantics.md).
238238
- **Schema-level attributes** other than `name`, `physicalName`, `properties`, `quality`, and the custom property `additionalProperties`.
239-
- **Constraints and quality rules on nested properties, on some servers** — `required`, `unique`, `pattern`, `enum`, the other `logicalTypeOptions` and `quality` rules below the top level are checked on the `dataframe`, `databricks`, `trino`, `athena` and `snowflake` servers and on every server read through DuckDB (`local`, `s3`, `gcs`, `azure`, `duckdb`, `iceberg`, `kafka`). On every other server, nested properties are only type-checked, and each of their constraints and quality rules is reported as a warning. On SAP HANA, only their quality rules are reported as warnings; their constraints are not checked.
239+
- **Constraints and quality rules on nested properties, on some servers** — `required`, `unique`, `pattern`, `enum`, the other `logicalTypeOptions` and `quality` rules below the top level are checked on the `dataframe`, `databricks`, `dremio`, `trino`, `athena` and `snowflake` servers and on every server read through DuckDB (`local`, `s3`, `gcs`, `azure`, `duckdb`, `iceberg`, `kafka`). On every other server, nested properties are only type-checked, and each of their constraints and quality rules is reported as a warning. On SAP HANA, only their quality rules are reported as warnings; their constraints are not checked.
240240

241241
Anything beyond this list that you want verified belongs in a [quality rule](./quality-rules/index.md) — a `type: library` metric for the common cases, or `type: sql` for arbitrary expressions.
242242

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
-- __TABLE__ is replaced by the path of the table, a folder below $scratch
2+
-- order 2 has an item without a sku and an email without @; order 3 repeats a sku, repeats a discount
3+
-- code within one item, has a negative discount, two disallowed tags and no email; orders 4 and 5 have no items.
4+
-- Order 1 has the discount code X in two items, which is no repeat.
5+
CREATE TABLE __TABLE__ AS
6+
SELECT o.r.order_id AS order_id, o.r.items AS items, o.r.tags AS tags, o.r.customer AS customer
7+
FROM (SELECT FLATTEN(CONVERT_FROM('[
8+
{"order_id": 1, "items": [{"sku": "A", "discounts": [{"code": "X", "amount": 1.5}]}, {"sku": "B", "discounts": [{"code": "X", "amount": 2.5}]}],
9+
"tags": ["new"], "customer": {"id": 1, "email": "a@example.com"}},
10+
{"order_id": 2, "items": [{"sku": null, "discounts": []}], "tags": ["vip"], "customer": {"id": 2, "email": "b.example.com"}},
11+
{"order_id": 3, "items": [{"sku": "C", "discounts": [{"code": "Y", "amount": -1.0}, {"code": "Y", "amount": 1.0}]}, {"sku": "C", "discounts": []}],
12+
"tags": ["bogus", "wrong"], "customer": {"id": 3, "email": null}},
13+
{"order_id": 4, "items": [], "tags": ["new"], "customer": {"id": 4, "email": "d@example.com"}},
14+
{"order_id": 5, "items": null, "tags": null, "customer": {"id": 5, "email": "e@example.com"}}
15+
]', 'JSON')) AS r) o

‎tests/test_create_checks_sql_placeholders.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,16 @@ def test_a_nested_property_is_a_path_into_its_column_on_snowflake():
9797
)
9898

9999

100+
def test_a_nested_property_is_a_path_into_its_column_on_dremio():
101+
quality = DataQuality(type="sql", query="SELECT COUNT(*) FROM {model} WHERE {property} IS NULL")
102+
server = Server(type="dremio")
103+
104+
assert (
105+
prepare_query(quality.query, "orders", ("customer", "home address", "city"), server)
106+
== "SELECT COUNT(*) FROM orders WHERE customer['home address']['city'] IS NULL"
107+
)
108+
109+
100110
def test_a_property_name_with_a_dot_is_one_quoted_name_on_every_dialect():
101111
quality = DataQuality(type="sql", query="SELECT COUNT(*) FROM orders WHERE {property} < 0")
102112

‎tests/test_test_dremio.py‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,3 +158,94 @@ def test_an_unknown_table_fails_its_checks_with_dremios_message(valid_orders):
158158

159159
assert run.result in (ResultEnum.failed, ResultEnum.error)
160160
assert any("not found" in (check.reason or "") for check in run.checks)
161+
162+
163+
NESTED_CONTRACT = """apiVersion: v3.1.0
164+
kind: DataContract
165+
id: dremio-nested
166+
version: 1.0.0
167+
status: active
168+
servers:
169+
- server: dremio
170+
type: dremio
171+
host: localhost
172+
port: __PORT__
173+
schema: __SCHEMA__
174+
schema:
175+
- name: orders
176+
physicalName: orders
177+
properties:
178+
- name: order_id
179+
logicalType: integer
180+
primaryKey: true
181+
- name: items
182+
logicalType: array
183+
items:
184+
logicalType: object
185+
properties:
186+
- name: sku
187+
logicalType: string
188+
required: true
189+
unique: true
190+
- name: discounts
191+
logicalType: array
192+
items:
193+
logicalType: object
194+
properties:
195+
- name: code
196+
logicalType: string
197+
unique: true
198+
- name: amount
199+
logicalType: number
200+
logicalTypeOptions:
201+
minimum: 0
202+
- name: tags
203+
logicalType: array
204+
items:
205+
logicalType: string
206+
quality:
207+
- metric: invalidValues
208+
arguments:
209+
validValues: [new, vip]
210+
mustBe: 0
211+
- name: customer
212+
logicalType: object
213+
properties:
214+
- name: email
215+
logicalType: string
216+
required: true
217+
quality:
218+
- type: sql
219+
query: SELECT COUNT(*) FROM {model} WHERE {property} NOT LIKE '%@%'
220+
mustBe: 0
221+
"""
222+
223+
224+
@pytest.fixture(scope="module")
225+
def nested_orders():
226+
return load('"$scratch".lake.nested', "nested_orders.sql")
227+
228+
229+
def nested_contract(schema: str) -> str:
230+
return NESTED_CONTRACT.replace("__PORT__", str(dremio.port())).replace("__SCHEMA__", f"'{schema}'")
231+
232+
233+
def test_nested_rules_fail_on_the_parent_rows_that_violate_them(nested_orders):
234+
run = DataContract(data_contract_str=nested_contract(nested_orders), include_failed_samples=True).test()
235+
236+
print(run.pretty())
237+
failed = [c for c in run.checks if c.result != ResultEnum.passed]
238+
assert {(c.field, c.type) for c in failed} == {
239+
("items[].sku", "field_required"),
240+
("items[].sku", "field_unique"),
241+
("items[].discounts[].code", "field_unique"),
242+
("items[].discounts[].amount", "field_minimum"),
243+
("tags[]", "field_invalid_values"),
244+
("customer.email", "field_required"),
245+
("customer.email", "field_quality_sql"),
246+
}
247+
assert all(c.result == ResultEnum.failed and c.diagnostics["value"] == 1 for c in failed)
248+
samples = {(c.field, c.type): [sample["order_id"] for sample in c.failedSamples or []] for c in failed}
249+
assert samples[("items[].sku", "field_required")] == [2]
250+
# one sample for each order, however many of its tags break the rule
251+
assert samples[("tags[]", "field_invalid_values")] == [3]

0 commit comments

Comments
 (0)