Skip to content

Commit 40a360e

Browse files
authored
feat: nested checks warnings, sodacl export, jsonschema union handling (#1278) (#1654)
Nested checks (required, unique, pattern, enum, logicalTypeOptions, quality) run on servers read through DuckDB and on Spark; on other servers they are reported as warnings. Type checks on parquet files are reported as warnings, as the file is read as the contract's types. export sodacl warns about the nested properties it leaves out. import jsonschema keeps the type of nullable anyOf/oneOf properties and warns about union types, which are imported as string. Closes #1278
1 parent 20b5024 commit 40a360e

32 files changed

Lines changed: 601 additions & 164 deletions

‎CHANGELOG.md‎

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

1010
### Added
1111
- `datacontract api`: `--contract-variables` and `--allow-local-files` options, as alternatives to their environment variables
12+
- `datacontract test` checks constraints and quality rules of nested properties on servers read through DuckDB (#1278)
1213

1314
### Changed
1415
- `datacontract lint` and `datacontract test`: a quality rule the CLI cannot run is reported as a warning instead of being silently dropped
1516
- `${VAR}` references are accepted in fields with a fixed set of values (`quality.type`, `quality.metric`, `quality.dimension`, `logicalType`, `servers[].type`); `datacontract test` fails when one resolves into anything else
17+
- `datacontract test` reports nested checks it cannot run and unsupported type checks on parquet files as warnings (#1278)
1618

1719
### Security
1820
- `datacontract api`:
@@ -24,6 +26,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
2426
- `datacontract test --dry-run`: a check that could not be planned no longer reports the run as `skipped`
2527
- Non-ASCII characters in data contract and import source files are now decoded as UTF-8, fixing garbling on Windows (#1650 @ymurong)
2628
- `datacontract import spark` preserves `varchar(...)` and `char(...)` types nested inside `struct`, `array` and `map` columns instead of widening them to `string` (#1634)
29+
- `datacontract import jsonschema` keeps the type of nullable `anyOf`/`oneOf` properties and warns about union types (#1278)
30+
- `datacontract export sodacl` warns about the nested properties it leaves out (#1278)
2731

2832
## [1.2.1] - 2026-09-22
2933

‎datacontract/engines/checks/check_spec.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ class MetricType(str, Enum):
4040

4141
# Metrics answered from schema introspection alone, without reading row values.
4242
# A positive allowlist: any future metric defaults conservatively to data-reading.
43-
_METADATA_METRICS = {
43+
METADATA_METRICS = {
4444
MetricType.FIELD_PRESENT,
4545
MetricType.FIELD_TYPE,
4646
MetricType.FIELD_PHYSICAL_TYPE,
@@ -175,7 +175,7 @@ class CheckSpec:
175175
def requires_data_read(self) -> bool:
176176
if self.metric == MetricType.UNSUPPORTED:
177177
return False
178-
return self.metric not in _METADATA_METRICS
178+
return self.metric not in METADATA_METRICS
179179

180180
def has_validity_constraints(self) -> bool:
181181
return any(

‎datacontract/engines/checks/create_checks.py‎

Lines changed: 26 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
)
2424

2525
from datacontract.config.variables import VariableError, contains_variables, resolve_variables
26-
from datacontract.engines.checks.check_spec import CheckSpec, MetricType, Op, Threshold
26+
from datacontract.engines.checks.check_spec import METADATA_METRICS, CheckSpec, MetricType, Op, Threshold
2727
from datacontract.engines.checks.dimensions import default_dimension
2828
from datacontract.engines.checks.sql_guard import dialect_for_server_type, is_read_only_query
2929
from datacontract.engines.checks.type_normalize import normalize_type_name
@@ -34,7 +34,8 @@
3434
logger = logging.getLogger(__name__)
3535

3636
_FILE_SERVER_TYPES = {"local", "s3", "gcs", "azure"}
37-
_NESTED_CHECK_SERVER_TYPES = {"dataframe", "databricks"}
37+
# Spark and every server read through DuckDB
38+
_NESTED_CHECK_SERVER_TYPES = {"dataframe", "databricks", "duckdb", "iceberg", "kafka"} | _FILE_SERVER_TYPES
3839

3940

4041
# ---------------------------------------------------------------------------
@@ -138,7 +139,8 @@ def _iter_property_paths(
138139
yield from _iter_property_paths(prop.items.properties, f"{field_path}[]")
139140

140141

141-
NESTED_NOT_RUN_REASON = "Quality rules on nested properties are only run on dataframe and databricks servers."
142+
def nested_not_run_reason(server_type: Optional[str]) -> str:
143+
return f"Checks on nested properties are not supported on {server_type} servers."
142144

143145

144146
_PERCENT_UNITS = {"percent", "percentage", "%"}
@@ -267,10 +269,7 @@ def _to_schema_checks(
267269
primary_key_is_composite = len(primary_key_props) > 1
268270

269271
for field, prop, nested in _iter_property_paths(properties):
270-
if nested and server_type not in _NESTED_CHECK_SERVER_TYPES:
271-
if prop.quality:
272-
checks.extend(_quality_checks(model, field, prop.quality, server, not_run_reason=NESTED_NOT_RUN_REASON))
273-
continue
272+
first_check = len(checks)
274273
# ODCS physicalName is the real column; mirror to_schema_name at field level.
275274

276275
checks.append(
@@ -545,6 +544,25 @@ def _to_schema_checks(
545544
if prop.quality:
546545
checks.extend(_quality_checks(model, field, prop.quality, server, variables))
547546

547+
# A check the server cannot run is reported, not dropped.
548+
unenforced = []
549+
if nested and server_type not in _NESTED_CHECK_SERVER_TYPES:
550+
# The parent's nested type check already covers presence and types.
551+
if check_types:
552+
checks[first_check:] = [c for c in checks[first_check:] if c.metric not in METADATA_METRICS]
553+
unenforced = checks[first_check:]
554+
reason = nested_not_run_reason(server_type)
555+
elif uses_raw_view:
556+
# The file is cast into the contract's types, so a type check would compare the contract with itself.
557+
unenforced = [c for c in checks[first_check:] if c.metric in METADATA_METRICS - {MetricType.FIELD_PRESENT}]
558+
reason = f"Checking types in {server.format} files is not supported yet."
559+
for check in unenforced:
560+
# An unrunnable rule keeps its own, more specific reason.
561+
if check.preset_result != "warning":
562+
check.metric = MetricType.UNSUPPORTED
563+
check.preset_result = "warning"
564+
check.preset_reason = reason
565+
548566
if primary_key_is_composite:
549567
primary_key_fields = [prop.physicalName or prop.name for prop in primary_key_props]
550568
checks.append(
@@ -668,24 +686,10 @@ def _quality_checks(
668686
quality_list: List[DataQuality],
669687
server: Optional[Server],
670688
variables: Optional[Mapping[str, str]] = None,
671-
not_run_reason: Optional[str] = None,
672689
) -> List[CheckSpec]:
673690
checks: List[CheckSpec] = []
674691
for count, quality in enumerate(quality_list):
675-
if not_run_reason is None:
676-
rule_checks = _quality_rule_checks(model, field, quality, count, server, variables)
677-
elif quality.type == "sql" or quality.metric is not None:
678-
kind = "sql" if quality.type == "sql" else "library"
679-
rule_checks = _unexecuted_check(
680-
f"{model}__{field}__quality_{kind}_{count}",
681-
f"field_quality_{kind}",
682-
model,
683-
field,
684-
quality,
685-
not_run_reason,
686-
)
687-
else:
688-
rule_checks = []
692+
rule_checks = _quality_rule_checks(model, field, quality, count, server, variables)
689693
# Every check keeps a link back to the rule that declared it, so that
690694
# `test --quality-id` / `test --tag` can select it.
691695
for check in rule_checks:

‎datacontract/engines/hana/hana_quality_check.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@
66
from open_data_contract_standard.model import DataQuality, OpenDataContractStandard, SchemaObject
77

88
from datacontract.engines.checks.create_checks import (
9-
NESTED_NOT_RUN_REASON,
109
_iter_property_paths,
1110
_retention_value_to_seconds,
1211
is_percent_unit,
12+
nested_not_run_reason,
1313
quality_definition_yaml,
1414
unexecuted_check_name,
1515
unrunnable_reason,
@@ -57,7 +57,7 @@ def run_quality_checks(
5757
name=quality.description or unexecuted_check_name(table_name, field_name),
5858
model=table_name,
5959
field=field_name,
60-
reason=NESTED_NOT_RUN_REASON,
60+
reason=nested_not_run_reason("hana"),
6161
quality=quality,
6262
)
6363
)

‎datacontract/engines/ibis/ibis_check_execute.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -338,7 +338,7 @@ def _invalid(c, _t=t, _dtype=dtype, _spec=spec, _flag=unconstrained):
338338
_record_sql(run, spec, t.aggregate([named]))
339339
agg_exprs.append((spec, named))
340340
except _ColumnNotFound as e:
341-
set_result(run, spec.key, ResultEnum.failed, str(e))
341+
set_result(run, spec.key, ResultEnum.failed, str(e) or f"Column '{spec.field}' not found")
342342
except Exception as e:
343343
logger.warning("Check '%s' errored: %s", spec.key, e)
344344
set_result(run, spec.key, ResultEnum.failed, f"Error evaluating check: {e}")
@@ -1319,7 +1319,11 @@ def _struct_field_name(value, name: str) -> str:
13191319
return name
13201320
if name in names:
13211321
return name
1322-
return next((n for n in names if n.lower() == name.lower()), name)
1322+
match = next((n for n in names if n.lower() == name.lower()), None)
1323+
if match is None:
1324+
# the handler names the full path
1325+
raise _ColumnNotFound()
1326+
return match
13231327

13241328

13251329
def _resolve_dtype(schema, field: str):

‎datacontract/export/sodacl_exporter.py‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,42 @@
1+
import logging
2+
13
import yaml
2-
from open_data_contract_standard.model import OpenDataContractStandard, Server
4+
from open_data_contract_standard.model import OpenDataContractStandard, SchemaProperty, Server
35

46
from datacontract.export.exporter import Exporter
57
from datacontract.export.sodacl_check_builder import create_checks
68
from datacontract.model.run import Run
79

10+
logger = logging.getLogger(__name__)
11+
812

913
class SodaExporter(Exporter):
1014
def export(self, data_contract, schema_name, server, sql_server_type, export_args) -> str:
1115
run = Run.create_run()
1216
found_server = get_server(data_contract, server)
1317
run.checks.extend(create_checks(data_contract, found_server))
18+
nested = [
19+
path
20+
for schema_obj in data_contract.schema_ or []
21+
for prop in schema_obj.properties or []
22+
for path in _nested_paths(prop, f"{schema_obj.name}.{prop.name}")
23+
]
24+
if nested:
25+
listed = ", ".join(nested) if len(nested) <= 6 else ", ".join(nested[:5]) + f" and {len(nested) - 5} others"
26+
logger.warning(f"SodaCL only checks top-level columns; nested properties not exported: {listed}")
1427
return to_sodacl_yaml(run)
1528

1629

30+
def _nested_paths(prop: SchemaProperty, path: str):
31+
children = prop.properties or []
32+
if prop.items is not None:
33+
children, path = prop.items.properties or [], f"{path}[]"
34+
for child in children:
35+
child_path = f"{path}.{child.name}"
36+
yield child_path
37+
yield from _nested_paths(child, child_path)
38+
39+
1740
def to_sodacl_yaml(run: Run) -> str:
1841
sodacl_dict = {}
1942
for run_check in run.checks:

‎datacontract/imports/jsonschema_importer.py‎

Lines changed: 60 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import json
2+
import logging
23
from typing import Any, Dict, List
34

45
import fastjsonschema
@@ -12,6 +13,8 @@
1213
)
1314
from datacontract.model.exceptions import DataContractException
1415

16+
logger = logging.getLogger(__name__)
17+
1518

1619
class JsonSchemaImporter(Importer):
1720
def import_source(self, source: str, import_args: dict) -> OpenDataContractStandard:
@@ -41,10 +44,23 @@ def import_jsonschema(source: str) -> OpenDataContractStandard:
4144
)
4245

4346
odcs.schema_ = [schema_obj]
47+
unions = [path for prop in properties for path in _union_paths(prop, prop.name)]
48+
if unions:
49+
listed = ", ".join(unions) if len(unions) <= 6 else ", ".join(unions[:5]) + f" and {len(unions) - 5} others"
50+
logger.warning(f"ODCS has no union type, so these properties are imported as string: {listed}")
4451

4552
return odcs
4653

4754

55+
def _union_paths(prop: SchemaProperty, path: str):
56+
if "|" in (prop.physicalType or ""):
57+
yield f"{path} ({prop.physicalType})"
58+
for child in prop.properties or []:
59+
yield from _union_paths(child, f"{path}.{child.name}")
60+
if prop.items:
61+
yield from _union_paths(prop.items, f"{path}[]")
62+
63+
4864
def load_and_validate_json_schema(source: str) -> dict:
4965
"""Load and validate a JSON Schema file."""
5066
try:
@@ -87,9 +103,21 @@ def jsonschema_to_properties(json_properties: Dict[str, Any], required_propertie
87103

88104
def schema_to_property(name: str, prop_schema: Dict[str, Any], is_required: bool = None) -> SchemaProperty:
89105
"""Convert a JSON Schema property to an ODCS SchemaProperty."""
106+
key = "anyOf" if "anyOf" in prop_schema else "oneOf"
107+
if key in prop_schema:
108+
# A true branch admits every value, a false one none
109+
prop_schema = {**prop_schema, key: [{} if b is True else b for b in prop_schema[key] if b is not False]}
110+
branches = prop_schema.get(key) or []
111+
non_null_branches = [branch for branch in branches if branch.get("type") != "null"]
112+
if len(non_null_branches) == 1:
113+
# One type or null is a nullable property, not a union
114+
outer = {key: value for key, value in prop_schema.items() if key not in ("anyOf", "oneOf")}
115+
prop_schema = {**non_null_branches[0], **outer}
116+
90117
# Determine the type
91118
property_type = determine_type(prop_schema)
92-
logical_type = map_jsonschema_type_to_odcs(property_type)
119+
# ODCS has no union type
120+
logical_type = "string" if "|" in property_type else map_jsonschema_type_to_odcs(property_type)
93121

94122
# Extract common attributes
95123
title = prop_schema.get("title")
@@ -190,18 +218,37 @@ def schema_to_property(name: str, prop_schema: Dict[str, Any], is_required: bool
190218

191219

192220
def determine_type(prop_schema: Dict[str, Any]) -> str:
193-
"""Determine the type from a JSON Schema property."""
194-
property_type = prop_schema.get("type")
195-
196-
if isinstance(property_type, list):
197-
# Handle union types like ["string", "null"]
198-
non_null_types = [t for t in property_type if t != "null"]
199-
if non_null_types:
200-
property_type = non_null_types[0]
201-
else:
202-
property_type = "string"
203-
204-
return property_type or "string"
221+
"""Determine the type from a JSON Schema property; a union is rendered as ``string|integer``."""
222+
branches = prop_schema.get("anyOf") or prop_schema.get("oneOf")
223+
if not branches:
224+
types = [prop_schema.get("type") or "string"]
225+
elif any("type" not in b and "$ref" not in b and "const" not in b and "enum" not in b for b in branches):
226+
# a branch without any type constraint admits every value
227+
return "string"
228+
else:
229+
types = [
230+
b.get("type")
231+
or b.get("$ref", "").rsplit("/", 1)[-1]
232+
or [_JSON_VALUE_TYPES[type(v)] for v in ([b["const"]] if "const" in b else b["enum"])]
233+
for b in branches
234+
]
235+
flat = [t for listed in types for t in (listed if isinstance(listed, list) else [listed])]
236+
names = [t for t in flat if t != "null"]
237+
# two object or array shapes are a union even though their type names match
238+
if len(dict.fromkeys(names)) == 1 and names[0] in ("object", "array") and len(names) > 1:
239+
return "|".join(names)
240+
return "|".join(dict.fromkeys(names)) or "string"
241+
242+
243+
_JSON_VALUE_TYPES = {
244+
str: "string",
245+
bool: "boolean",
246+
int: "integer",
247+
float: "number",
248+
dict: "object",
249+
list: "array",
250+
type(None): "null",
251+
}
205252

206253

207254
def map_jsonschema_type_to_odcs(json_type: str) -> str:

‎datacontract/output/test_results_writer.py‎

Lines changed: 24 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -80,31 +80,35 @@ def write_test_result(
8080
)
8181
elif run.result == "warning":
8282
console.print("🟠 data contract has warnings. Found the following warnings:")
83-
i = 1
84-
for check in run.checks:
85-
if check.result not in ("passed", "skipped"):
86-
field = to_field(run, check)
87-
if field:
88-
field = field + " "
89-
else:
90-
field = ""
91-
console.print(f"{i}) {field}{check.name}: {escape(str(check.reason))}")
92-
i += 1
83+
print_findings(run, console)
9384
else:
9485
console.print("🔴 data contract is invalid, found the following errors:")
95-
i = 1
96-
for check in run.checks:
97-
if check.result not in ("passed", "skipped"):
98-
field = to_field(run, check)
99-
if field:
100-
field = field + " "
101-
else:
102-
field = ""
103-
console.print(f"{i}) {field}{check.name}: {escape(str(check.reason))}")
104-
i += 1
86+
print_findings(run, console)
10587
raise typer.Exit(code=1)
10688

10789

90+
def print_findings(run, console):
91+
"""List every check that did not pass, folding checks that share a reason into one line."""
92+
findings = [check for check in run.checks if check.result not in ("passed", "skipped")]
93+
by_reason = {}
94+
for check in findings:
95+
by_reason.setdefault(check.reason, []).append(check)
96+
i = 1
97+
for check in findings:
98+
group = by_reason[check.reason] if check.reason else [check]
99+
if len(group) > 1:
100+
if group[0] is not check:
101+
continue
102+
fields = ", ".join(dict.fromkeys(f for f in (to_field(run, c) for c in group) if f))
103+
fields_info = f" on {escape(fields)}" if fields else ""
104+
console.print(f"{i}) {len(group)} checks{fields_info}: {escape(str(check.reason))}")
105+
else:
106+
field = to_field(run, check)
107+
field = field + " " if field else ""
108+
console.print(f"{i}) {escape(field)}{escape(str(check.name))}: {escape(str(check.reason))}")
109+
i += 1
110+
111+
108112
def print_test_results_table(run, console):
109113
table = Table(box=box.ROUNDED)
110114
table.add_column("Result", no_wrap=True)

‎docs/docs/imports/jsonschema.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,4 +76,6 @@ schema:
7676

7777
{/* END AUTOGENERATED EXAMPLE */}
7878

79+
ODCS has no union type. A property that allows more than one type (`"type": ["string", "integer"]`, or several `anyOf`/`oneOf` branches) is imported as `logicalType: string` with the union in `physicalType` (`string|integer`), and the import prints a warning naming it. A single type plus `null` is not a union and imports as that type.
80+
7981
All options: **[`datacontract import jsonschema`](../commands/import/jsonschema.md)**.

0 commit comments

Comments
 (0)