diff --git a/docs/odcs/field-mapping.md b/docs/odcs/field-mapping.md index 1b1de13a..417885fc 100644 --- a/docs/odcs/field-mapping.md +++ b/docs/odcs/field-mapping.md @@ -33,7 +33,7 @@ | `name` | string | required | _(none at top level)_ | — | — | **Restructured** | [Fundamentals](https://bitol-io.github.io/open-data-contract-standard/v3.1.0/fundamentals/) / [Schema](https://bitol-io.github.io/open-data-contract-standard/v3.1.0/schema/) | ODCS has no single `name` field at the contract level. The equivalent contract identity is expressed via `dataProduct` (Fundamentals) plus `schema[].name` (the dataset name). On export CG `name` should populate **both** `dataProduct` and `schema[0].name`. On import, `schema[0].name` wins. **Round-trip risk.** | | `description` | string (optional) | optional | `description.purpose` | string (inside object) | O | **Restructured** | [Fundamentals](https://bitol-io.github.io/open-data-contract-standard/v3.1.0/fundamentals/) | ODCS `description` is an object with sub-keys `purpose`, `limitations`, `usage`. CG's flat string maps to `description.purpose`. On import, CG should concatenate any present sub-keys with a delimiter. | | `compliance_mode` | bool (default false) | optional | _(none)_ | — | — | **No equivalent** | — | RFC-004 per-version enforcement flag. No ODCS home. Must be exported as `x-contractgate-compliance-mode`. | -| `ontology` | Ontology object | required | `schema` (array) | array | R | **Restructured** | [Schema](https://bitol-io.github.io/open-data-contract-standard/v3.1.0/schema/) | CG flattens all field definitions under a single `ontology.entities[]` list. ODCS nests field definitions inside one or more `schema[]` dataset objects (tables, topics). On export, all CG entities are placed under a single synthesised `schema[0]`. On import, only `schema[0].properties[]` is processed unless explicitly extended. | +| `ontology` | Ontology object | required | `schema` (array) | array | R | **Restructured** | [Schema](https://bitol-io.github.io/open-data-contract-standard/v3.1.0/schema/) | CG flattens all field definitions under a single `ontology.entities[]` list. ODCS nests field definitions inside one or more `schema[]` dataset objects (tables, topics). On export, all CG entities are placed under a single synthesised `schema[0]`. On import, one schema object is processed: the first, or the one named by `schema_object` (`--schema-object` on the CLI). The others are listed in a note. | | `glossary` | GlossaryEntry[] (default []) | optional | _(none as top-level block)_ | — | — | **No equivalent** | — | ODCS has no dedicated glossary section. Per-field semantic data is distributed across `schema[].properties[].description`, `.businessName`, and `.authoritativeDefinitions`. Full glossary must be preserved as `x-contractgate-glossary`. See gap-analysis.md §CG-GAP-003. | | `metrics` | MetricDefinition[] (default []) | optional | _(none as top-level block)_ | — | — | **No equivalent** | — | ODCS has no formula-metrics section. Closest available landing zones are `schema[].quality[]` (for threshold rules) and `slaProperties[]` (for SLO-style bounds). Formula metrics have no structural home. Full block must be preserved as `x-contractgate-metrics`. See gap-analysis.md §CG-GAP-004. | diff --git a/docs/odcs/strict-odcs.md b/docs/odcs/strict-odcs.md index ab0152a1..742d03db 100644 --- a/docs/odcs/strict-odcs.md +++ b/docs/odcs/strict-odcs.md @@ -22,6 +22,7 @@ Framework bundles. | `min_length` / `max_length` | `logicalTypeOptions.minLength` / `maxLength` | `x-cg-min-length` / `x-cg-max-length` | | `min` / `max` (number/integer) | `logicalTypeOptions.minimum` / `maximum` | `x-cg-min` / `x-cg-max` | | `format` (new, string) | `logicalTypeOptions.format` | `x-cg-format` | +| `distribution` (synth-only hint) | n/a | `x-cg-distribution` (a map such as `{type: normal, mean: 50, sd: 10}`) | | `enum` | `quality: [{type: library, metric: invalidValues, mustBe: 0, arguments: {validValues: [...]}}]` (v3.1.0 has no property `enum`), tagged `x-cg-derived: enum` | `x-cg-enum` | | `required` | `required` | — | | quality `uniqueness` | `unique: true` + `library` / `duplicateValues` / `dimension: uniqueness` | `x-cg-quality` on the entry | diff --git a/docs/odcs/using-odcs-directly.md b/docs/odcs/using-odcs-directly.md index fd42e0f4..ab39117c 100644 --- a/docs/odcs/using-odcs-directly.md +++ b/docs/odcs/using-odcs-directly.md @@ -32,11 +32,49 @@ kept as native YAML; an ODCS document is converted once, on the way in. Unknown ODCS fields are ignored. +To shape synthetic values on a number or integer property, add a custom property named `x-cg-distribution`: + +```yaml +- name: amount + logicalType: number + customProperties: + - property: x-cg-distribution + value: { type: normal, mean: 120, sd: 25 } +``` + +`type` is `uniform`, `normal`, `lognormal` (`mean` and `sd` of the underlying normal) or `exponential` (`rate`). Details: [synthetic data reference](../synthetic-data-reference.md#value-distributions). A bad value is an import error that names the property. + +## Choosing a schema object + +An ODCS file can describe several tables or topics in `schema[]`. A +DataContractGate contract covers one of them. The first is used unless you pick +one by `name` (`physicalName` and `id` also match): + +```sh +contractgate validate --schema-object customers contracts/shop.odcs.yaml +contractgate synth --schema-object customers contracts/shop.odcs.yaml +``` + +`--schema-object` is on `validate`, `synth`, `test` and `enforce`. The API takes +`schema_object` on `POST /contracts/synth` (with `yaml_content`) and on +`POST /contracts/import`. An unknown name is an error that lists the names in +the file. A native contract ignores it. + +The note that lists the ignored objects (and any composite key or relationships +note) is printed by the CLI and returned as `notes` in the JSON response of +`POST /contracts/synth` and `POST /contracts/import`. `notes` is left out when +there is nothing to say. To cover several objects, import each one as its own +contract. + ## What does not map -- Only `schema[0]` is read. Other schema objects are reported as a note - (`contractgate validate` prints it) and skipped. -- `relationships` and foreign keys, composite primary key uniqueness. +- One schema object is read per contract (see below). The others are skipped + and listed in a note. +- `relationships` and foreign keys. A contract validates one object's events + and has no lookup into another, so these are not enforced. A note says so. +- Uniqueness of a composite primary key. Each key column is made required, but + uniqueness rules cover one field, so the combination is not checked. A note + says so. - Dataset-level `quality` (for example `rowCount`), `sql` and `custom` quality checks from other engines. - `servers`, `team`, `roles`, `slaProperties`, `support`, `price`, diff --git a/docs/synthetic-data-reference.md b/docs/synthetic-data-reference.md index d0164d21..c98033a4 100644 --- a/docs/synthetic-data-reference.md +++ b/docs/synthetic-data-reference.md @@ -11,6 +11,7 @@ DataContractGate can generate test rows from a contract. Rows come only from the | `required: false` | present in about 3 of 4 rows | | | `enum` | one of the listed values | a value of the right type outside the list | | `min` / `max` | inside the range | a value below `min` or above `max` | +| `distribution` (integer, number) | drawn from that shape, inside `min` / `max` (see [Value distributions](#value-distributions)) | as `min` / `max` above | | `min_length` / `max_length` | length inside the bounds | a shorter or longer string | | free-form `type: string` (no `pattern`, `format` or `enum`) | a realistic value guessed from the field name when it passes every declared rule (`email`, `first_name`, `customer_name`, `phone`, `website`, `country` / `country_code`, `city`, `address`, `zip`, `currency`, `*_id` as a UUID, and more), otherwise a random string | | | `pattern` | a string built from the regex | a string the regex does not match | @@ -48,6 +49,45 @@ Fix the contract (widen the field range, drop the duplicate rule) if one of thes The same seed, anchor time, contract and DataContractGate version give the same rows. The anchor time defaults to now, so without it freshness values (and only those) change between runs. Rows anchored far from now fail real-time freshness on ingest. +## Value distributions + +By default numbers are drawn evenly (uniform) between `min` and `max`. With no bounds, integers come from 0 to 10,000 and numbers from 0 to 1,000, and numbers are rounded to 2 decimals. To shape the values, add a `distribution` hint to an `integer` or `number` field: + +```yaml +ontology: + entities: + - name: order_total + type: number + min: 0 + distribution: { type: lognormal, mean: 3.5, sd: 0.6 } + - name: age + type: integer + min: 18 + max: 90 + distribution: { type: normal, mean: 42, sd: 12 } + - name: wait_seconds + type: number + min: 0 + distribution: { type: exponential, rate: 0.05 } +``` + +| `type` | Parameters | Values | +|---|---|---| +| `uniform` | none (`distribution: uniform`) | Evenly between `min` and `max`. The default, and the same rows as no hint. | +| `normal` | `mean`, `sd` (greater than 0) | Bell curve around `mean`. | +| `lognormal` | `mean`, `sd` (greater than 0) | `exp(N(mean, sd))`. `mean` and `sd` describe the underlying normal, the way NumPy and R do, not the resulting values. For values with a mean near 100 and a long right tail, try `mean: 4.5, sd: 0.5`. Always positive. | +| `exponential` | `rate` (greater than 0) | `min + Exp(rate)` (from 0 with no `min`). The spread above the start averages `1 / rate`. Right-skewed. | + +Rules: + +- `min` and `max` still hold. A draw outside them is redrawn, so the result is the distribution cut off at the bounds. If the bounds leave almost no mass (a mean of 1000 with `max: 10`), the call fails with `rule: distribution` and the field named. +- Integers are rounded to the nearest whole number. Numbers keep 2 decimals, or more when the values are small. +- An `enum` on the field wins: its values are picked evenly and the hint is ignored. +- A hint on a string, date or other non-numeric field fails the call (`rule: distribution`). Dates and timestamps have no distribution hint yet. +- The same seed gives the same rows. +- It is synth-only. Validation, ingest and every other feature ignore it. A bad hint (`sd: 0`, an unknown `type`, a missing parameter) is rejected when the contract is read, with a message that names the problem. +- ODCS: put it in the property's `customProperties` as `x-cg-distribution` with the same map as the value (see [odcs/using-odcs-directly.md](odcs/using-odcs-directly.md)). + ## API `POST /contracts/synth` with an `x-api-key` header. @@ -154,4 +194,5 @@ It takes the same options as the Rust CLI plus `--contract-id`, `--version`, `-- ## ODCS input `contractgate synth` and `POST /contracts/synth` accept an ODCS v3.x document -with no `ontology`. See [`odcs/using-odcs-directly.md`](odcs/using-odcs-directly.md). +with no `ontology`. Pass `--schema-object NAME` (or `schema_object` in the API) to pick one object of a multi-object file; the response lists unmapped content in `notes`. +See [`odcs/using-odcs-directly.md`](odcs/using-odcs-directly.md). diff --git a/sdks/python/src/contractgate/contract.py b/sdks/python/src/contractgate/contract.py index 685c2df6..a6577931 100644 --- a/sdks/python/src/contractgate/contract.py +++ b/sdks/python/src/contractgate/contract.py @@ -132,6 +132,9 @@ class FieldDefinition: # ODCS logicalTypeOptions.format. Enforced for email, uuid, and uri/url # on string values; any other name is metadata and passes. format: Optional[str] = None + # Synth-only hint (``uniform`` / ``normal`` / ``lognormal`` / + # ``exponential``). Read and checked here; the local validator ignores it. + distribution: Optional[Dict[str, Any]] = None @classmethod def from_yaml(cls, raw: Any) -> "FieldDefinition": @@ -166,9 +169,56 @@ def from_yaml(cls, raw: Any) -> "FieldDefinition": items=items, transform=transform, format=_opt_str(raw.get("format")), + distribution=_parse_distribution(raw.get("distribution")), ) +_DIST_PARAMS = { + "uniform": (), + "normal": ("mean", "sd"), + "lognormal": ("mean", "sd"), + "exponential": ("rate",), +} + + +def _parse_distribution(raw: Any) -> Optional[Dict[str, Any]]: + """Check a field ``distribution`` hint (same rules as the Rust engine).""" + if raw is None: + return None + if isinstance(raw, str): + raw = {"type": raw} + if not isinstance(raw, dict): + raise ContractCompileError( + "distribution must be a name or a map with a `type` " + "(uniform, normal, lognormal, exponential)" + ) + kind = raw.get("type", raw.get("kind")) + if not isinstance(kind, str): + raise ContractCompileError("distribution needs a `type`") + kind = kind.lower() + if kind not in _DIST_PARAMS: + raise ContractCompileError( + f"unknown distribution type {kind!r}; use one of: " + "uniform, normal, lognormal, exponential" + ) + out: Dict[str, Any] = {"type": kind} + for key in raw: + if key not in ("type", "kind") and key not in _DIST_PARAMS[kind]: + raise ContractCompileError(f"distribution {kind} does not take `{key}`") + for key in _DIST_PARAMS[kind]: + v = raw.get(key) + if isinstance(v, bool) or not isinstance(v, (int, float)) or v != v or abs(v) == float("inf"): + raise ContractCompileError(f"distribution {kind} needs a numeric `{key}`") + out[key] = float(v) + if kind in ("normal", "lognormal") and out["sd"] <= 0: + raise ContractCompileError(f"distribution {kind} needs sd greater than 0, got {out['sd']}") + if kind == "exponential" and out["rate"] <= 0: + raise ContractCompileError( + f"distribution exponential needs rate greater than 0, got {out['rate']}" + ) + return out + + # --------------------------------------------------------------------------- # Metric / glossary # --------------------------------------------------------------------------- @@ -324,6 +374,9 @@ def _odcs_prop(p: Dict[str, Any]) -> Dict[str, Any]: ): if opts.get(src) is not None: ent[dst] = opts[src] + for cp in p.get("customProperties") or []: + if isinstance(cp, dict) and cp.get("property") == "x-cg-distribution" and cp.get("value") is not None: + ent["distribution"] = cp["value"] for src, dst in (("minimum", "min"), ("maximum", "max")): if isinstance(opts.get(src), (int, float)) and not isinstance(opts.get(src), bool): ent[dst] = opts[src] diff --git a/sdks/python/tests/test_odcs_input.py b/sdks/python/tests/test_odcs_input.py index e2bfc57e..a9be823c 100644 --- a/sdks/python/tests/test_odcs_input.py +++ b/sdks/python/tests/test_odcs_input.py @@ -49,3 +49,33 @@ def test_unsupported_odcs_errors_are_clear(): Contract.from_yaml("apiVersion: v3.1.0\nkind: DataContract\nname: n\nversion: 1.0.0\n") with pytest.raises(ContractCompileError, match="unsupported ODCS apiVersion"): Contract.from_yaml("apiVersion: v2.2.2\nkind: DataContract\nname: n\nversion: 1\nschema: []\n") + + +def test_distribution_hint_is_read_and_checked(): + c = Contract.from_yaml( + 'version: "1.0"\nname: d\nontology:\n entities:\n' + " - name: x\n type: number\n" + " distribution: {type: normal, mean: 5, sd: 2}\n" + ) + assert c.entities[0].distribution == {"type": "normal", "mean": 5.0, "sd": 2.0} + # the validator ignores it + assert c.compile().validate({"x": 1.5}).passed + with pytest.raises(ContractCompileError, match="sd greater than 0"): + Contract.from_yaml( + 'version: "1.0"\nname: d\nontology:\n entities:\n' + " - name: x\n type: number\n distribution: {type: normal, mean: 1, sd: 0}\n" + ) + with pytest.raises(ContractCompileError, match="unknown distribution type"): + Contract.from_yaml( + 'version: "1.0"\nname: d\nontology:\n entities:\n' + " - name: x\n type: number\n distribution: {type: weibull}\n" + ) + + +def test_odcs_x_cg_distribution_custom_property(): + c = Contract.from_yaml( + "apiVersion: v3.1.0\nkind: DataContract\nversion: 1.0.0\nname: n\nschema:\n - name: t\n properties:\n" + " - name: x\n logicalType: number\n customProperties:\n" + " - property: x-cg-distribution\n value: {type: lognormal, mean: 3, sd: 0.5}\n" + ) + assert c.entities[0].distribution == {"type": "lognormal", "mean": 3.0, "sd": 0.5} diff --git a/sdks/typescript/CHANGELOG.md b/sdks/typescript/CHANGELOG.md index b81c4eab..b7889a3a 100644 --- a/sdks/typescript/CHANGELOG.md +++ b/sdks/typescript/CHANGELOG.md @@ -2,6 +2,18 @@ All notable changes to `@nightmoose/contractgate-sdk`. +## 0.4.2 — 2026-11-26 + +- `Contract.fromYaml` accepts ODCS v3.x documents (no `ontology`): fields are + read from `schema[0].properties[]` (`logicalType`, or `physicalType` when it + is absent; `required`, `primaryKey`, `enum`, `logicalTypeOptions`), a map + `description` is read as text, and unknown ODCS fields are ignored. Mirrors + the Python SDK and the gateway. +- `ontology` is optional in native contracts. +- ODCS `date` and `timestamp` read as strings, and `unique` / quality rules are + not checked locally (this SDK has no date type or quality rules). +- Version aligned with DataContractGate 0.4.2. + ## 0.4.1 — 2026-10-28 Version alignment with DataContractGate 0.4.1. No SDK API changes. diff --git a/sdks/typescript/README.md b/sdks/typescript/README.md index 6933f712..d3256e2e 100644 --- a/sdks/typescript/README.md +++ b/sdks/typescript/README.md @@ -69,6 +69,8 @@ const compiled = contract.compile(); const { passed, violations } = compiled.validate({ user_id: "alice", timestamp: 1700000000 }); ``` +`Contract.fromYaml` also reads an ODCS v3.x document directly (no `ontology` needed): fields come from `schema[0].properties[]`, a map `description` is read as text, and unknown ODCS fields are ignored. `ontology` is optional in native contracts too. + The local validator mirrors the Rust engine exactly. Conformance is enforced via a shared fixture corpus under `tests/conformance/`. ## Error hierarchy diff --git a/sdks/typescript/package-lock.json b/sdks/typescript/package-lock.json index 05d97de7..e6c79b54 100644 --- a/sdks/typescript/package-lock.json +++ b/sdks/typescript/package-lock.json @@ -1,12 +1,12 @@ { "name": "@nightmoose/contractgate-sdk", - "version": "0.4.1", + "version": "0.4.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@nightmoose/contractgate-sdk", - "version": "0.4.1", + "version": "0.4.2", "license": "MIT", "dependencies": { "js-yaml": "^4.1.0" diff --git a/sdks/typescript/package.json b/sdks/typescript/package.json index 1c8b2920..a30c2301 100644 --- a/sdks/typescript/package.json +++ b/sdks/typescript/package.json @@ -1,6 +1,6 @@ { "name": "@nightmoose/contractgate-sdk", - "version": "0.4.1", + "version": "0.4.2", "description": "Official TypeScript SDK for DataContractGate — HTTP client + local validator", "license": "MIT", "type": "module", diff --git a/sdks/typescript/src/client.ts b/sdks/typescript/src/client.ts index 31a9ea1a..59fd8ff0 100644 --- a/sdks/typescript/src/client.ts +++ b/sdks/typescript/src/client.ts @@ -20,7 +20,7 @@ import type { } from './types.js'; const DEFAULT_TIMEOUT_MS = 30_000; -const SDK_VERSION = '0.4.1'; +const SDK_VERSION = '0.4.2'; const USER_AGENT = `contractgate-typescript/${SDK_VERSION}`; // --------------------------------------------------------------------------- diff --git a/sdks/typescript/src/contract.ts b/sdks/typescript/src/contract.ts index c3843680..53a6f769 100644 --- a/sdks/typescript/src/contract.ts +++ b/sdks/typescript/src/contract.ts @@ -224,6 +224,134 @@ function parseGlossaryEntry(raw: unknown): GlossaryEntry { // Contract + CompiledContract // --------------------------------------------------------------------------- +// --------------------------------------------------------------------------- +// ODCS v3.x input +// --------------------------------------------------------------------------- + +type Json = Record; + +const isMap = (v: unknown): v is Json => + v !== null && typeof v === 'object' && !Array.isArray(v); + +// ODCS logicalType -> field type. This SDK has no date or timestamp type, so +// those read as strings (the shape is not checked locally). +const ODCS_LOGICAL: Record = { + integer: 'integer', long: 'integer', int: 'integer', + number: 'float', double: 'float', float: 'float', decimal: 'float', + boolean: 'boolean', bool: 'boolean', + object: 'object', record: 'object', struct: 'object', map: 'object', + array: 'array', list: 'array', + any: 'any', +}; + +// Used only when a property has no logicalType. +const ODCS_PHYSICAL: Record = { + int: 'integer', integer: 'integer', bigint: 'integer', smallint: 'integer', + tinyint: 'integer', long: 'integer', short: 'integer', + float: 'float', double: 'float', real: 'float', decimal: 'float', + numeric: 'float', number: 'float', + boolean: 'boolean', bool: 'boolean', + struct: 'object', record: 'object', object: 'object', map: 'object', + json: 'object', jsonb: 'object', variant: 'object', + array: 'array', list: 'array', +}; + +/** A document with no `ontology` and an `apiVersion: v3*`, `kind: DataContract` + * or a `schema` list. */ +function isOdcs(r: Json): boolean { + if ('ontology' in r) return false; + const api = r['apiVersion']; + return ( + (typeof api === 'string' && api.startsWith('v3')) || + r['kind'] === 'DataContract' || + Array.isArray(r['schema']) + ); +} + +function odcsDescription(v: unknown): string | undefined { + if (typeof v === 'string') return v; + if (isMap(v)) { + for (const k of ['purpose', 'usage', 'limitations']) { + if (typeof v[k] === 'string') return v[k] as string; + } + } + return undefined; +} + +function odcsEnum(v: unknown): unknown[] | undefined { + if (!Array.isArray(v)) return undefined; + const out = v + .map((i) => (isMap(i) ? i['value'] : i)) + .filter((i) => ['string', 'number', 'boolean'].includes(typeof i)); + return out.length ? out : undefined; +} + +function odcsProp(p: Json): Json { + const logical = p['logicalType']; + let type: string; + if (typeof logical === 'string') { + type = ODCS_LOGICAL[logical] ?? 'string'; + } else { + const base = String(p['physicalType'] ?? '').toLowerCase().split(/[(< ]/)[0] ?? ''; + type = ODCS_PHYSICAL[base] ?? 'string'; + } + const opts = isMap(p['logicalTypeOptions']) ? p['logicalTypeOptions'] : {}; + const ent: Json = { + name: String(p['name']), + type, + required: p['required'] === true || p['primaryKey'] === true, + }; + const en = odcsEnum(p['enum']) ?? odcsEnum(opts['enum']); + if (en) ent['enum'] = en; + for (const [src, dst] of [ + ['pattern', 'pattern'], + ['minLength', 'min_length'], + ['maxLength', 'max_length'], + ['minimum', 'min'], + ['maximum', 'max'], + ] as const) { + if (opts[src] !== undefined && opts[src] !== null) ent[dst] = opts[src]; + } + return ent; +} + +/** Map an ODCS v3.x document (`schema[0].properties[]`) to the native contract + * mapping. Unknown ODCS fields are ignored. */ +function odcsToNative(r: Json): Json { + const api = r['apiVersion']; + if (typeof api === 'string' && !api.startsWith('v3')) { + throw new ContractCompileError(`unsupported ODCS apiVersion ${JSON.stringify(api)}; supported: v3.x`); + } + let version = r['version']; + if (typeof version === 'number') version = String(version); + if (typeof version !== 'string' || !version) { + throw new ContractCompileError("ODCS document is missing the required 'version' field"); + } + const schema = r['schema']; + if (!Array.isArray(schema) || schema.length === 0 || !isMap(schema[0])) { + throw new ContractCompileError( + "ODCS document has no 'schema' array; fields are read from schema[].properties[]", + ); + } + const s0 = schema[0]; + const props = s0['properties']; + if (!Array.isArray(props) || props.length === 0) { + throw new ContractCompileError( + `ODCS schema[0] (${JSON.stringify(s0['name'])}) has no properties; nothing to validate`, + ); + } + // Same order as the Rust importer: dataProduct, schema[0].name, root name. + const name = + [r['dataProduct'], s0['name'], r['name']].find( + (v): v is string => typeof v === 'string' && v.trim() !== '', + ) ?? 'imported_contract'; + const entities = props.filter((p): p is Json => isMap(p) && !!p['name']).map(odcsProp); + const native: Json = { version, name, ontology: { entities } }; + const desc = odcsDescription(r['description']) ?? odcsDescription(s0['description']); + if (desc) native['description'] = desc; + return native; +} + export interface ContractData { version: string; name: string; @@ -254,7 +382,8 @@ export class Contract { if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) { throw new ContractCompileError('contract YAML must be a mapping at the top level'); } - const r = raw as Record; + let r = raw as Record; + if (isOdcs(r)) r = odcsToNative(r); const version = r['version']; const name = r['name']; @@ -265,11 +394,12 @@ export class Contract { throw new ContractCompileError('contract.name is required'); } - const ontologyRaw = r['ontology']; + // `ontology` is optional; a contract may have none. + const ontologyRaw = r['ontology'] ?? {}; if (ontologyRaw === null || typeof ontologyRaw !== 'object' || Array.isArray(ontologyRaw)) { - throw new ContractCompileError('contract.ontology is required and must be a mapping'); + throw new ContractCompileError('contract.ontology must be a mapping'); } - const entitiesRaw = (ontologyRaw as Record)['entities']; + const entitiesRaw = (ontologyRaw as Record)['entities'] ?? []; if (!Array.isArray(entitiesRaw)) { throw new ContractCompileError('contract.ontology.entities must be a list'); } @@ -285,7 +415,7 @@ export class Contract { return new Contract({ version, name, - description: typeof r['description'] === 'string' ? r['description'] : undefined, + description: odcsDescription(r['description']), complianceMode: r['compliance_mode'] === true, entities, glossary, diff --git a/sdks/typescript/tests/odcs.test.ts b/sdks/typescript/tests/odcs.test.ts new file mode 100644 index 00000000..fe073d86 --- /dev/null +++ b/sdks/typescript/tests/odcs.test.ts @@ -0,0 +1,90 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { Contract } from '../src/contract.js'; +import { ContractCompileError } from '../src/errors.js'; + +const load = (n: string) => readFileSync(fileURLToPath(new URL(`./${n}`, import.meta.url)), 'utf8'); + +describe('ODCS input', () => { + it('parses a minimal ODCS contract with no ontology and validates events', () => { + const c = Contract.fromYaml(load('odcs_minimal.yaml')).compile(); + assert.equal(c.contract.name, 'orders'); + assert.equal(c.contract.description, 'Minimal orders contract'); + assert.deepEqual( + c.contract.entities.map((e) => e.name), + ['order_id', 'amount', 'status'], + ); + assert.equal(c.contract.entities[1]!.fieldType, 'float'); + assert.ok(c.validate({ order_id: 'a', amount: 2.5, status: 'open' }).passed); + assert.ok(!c.validate({ order_id: 'a', amount: -1, status: 'open' }).passed); + assert.ok(!c.validate({ order_id: 'a', amount: 1, status: 'nope' }).passed); + }); + + it('parses the official full example (map description, v3.2 enum, primaryKey)', () => { + const c = Contract.fromYaml(load('odcs_full_example.yaml')).compile(); + assert.equal(c.contract.description, 'Views built on top of the seller tables.'); + const by = Object.fromEntries(c.contract.entities.map((e) => [e.name, e])); + assert.deepEqual(by['rcvr_cntry_code']!.allowedValues, ['US', 'CA', 'MX']); + assert.equal(by['rcvr_id']!.required, true); + assert.ok(c.validate({ rcvr_id: 'x', rcvr_cntry_code: 'US' }).passed); + assert.ok(!c.validate({ rcvr_id: 'x', rcvr_cntry_code: 'ZZ' }).passed); + }); + + it('reads physicalType when logicalType is absent and ignores unknown fields', () => { + const c = Contract.fromYaml(` +apiVersion: v3.1.0 +kind: DataContract +version: 2 +name: t +futureKey: {a: 1} +schema: + - name: t + properties: + - name: id + physicalType: BIGINT + primaryKey: true + - name: price + physicalType: DECIMAL(10,2) + - name: attrs + logicalType: map +`).compile(); + const types = c.contract.entities.map((e) => e.fieldType); + assert.deepEqual(types, ['integer', 'float', 'object']); + assert.equal(c.contract.version, '2'); + }); + + it('keeps ontology optional for native contracts', () => { + const c = Contract.fromYaml('version: "1.0"\nname: bare\n').compile(); + assert.deepEqual(c.contract.entities, []); + }); + + it('native contracts still need a mapping ontology when one is given', () => { + assert.throws( + () => Contract.fromYaml('version: "1.0"\nname: x\nontology: 5\n'), + /ontology must be a mapping/, + ); + }); + + it('gives clear errors for unsupported ODCS', () => { + assert.throws( + () => Contract.fromYaml('apiVersion: v3.1.0\nkind: DataContract\nname: n\nversion: 1.0.0\n'), + (e: unknown) => e instanceof ContractCompileError && /no 'schema' array/.test(e.message), + ); + assert.throws( + () => + Contract.fromYaml( + 'apiVersion: v2.2.2\nkind: DataContract\nname: n\nversion: 1\nschema: []\n', + ), + /unsupported ODCS apiVersion/, + ); + assert.throws( + () => + Contract.fromYaml( + 'apiVersion: v3.1.0\nname: n\nversion: 1\nschema:\n - name: t\n', + ), + /no properties/, + ); + }); +}); diff --git a/sdks/typescript/tests/odcs_full_example.yaml b/sdks/typescript/tests/odcs_full_example.yaml new file mode 100644 index 00000000..f1c072bd --- /dev/null +++ b/sdks/typescript/tests/odcs_full_example.yaml @@ -0,0 +1,362 @@ +# Copyright 2026 The Bitol Contributors +# SPDX-License-Identifier: Apache-2.0 + +# What's this data contract about? +domain: seller # Domain +dataProduct: my quantum # Data product name +version: 1.1.0 # Version (follows semantic versioning) +status: active +id: 53581432-6c55-4ba2-a65f-72344a91553a + +authoritativeDefinitions: +- type: canonical + url: https://github.com/bitol-io/open-data-contract-standard/blob/main/docs/examples/all/full-example.odcs.yaml + description: Canonical URL to the latest version of the contract. + +# Lots of information +description: + purpose: Views built on top of the seller tables. + limitations: Data based on seller perspective, no buyer information + usage: Predict sales over time + authoritativeDefinitions: + - type: privacy-statement + url: https://example.com/gdpr.pdf +tenant: ClimateQuantumInc + +kind: DataContract +apiVersion: v3.2.0 # Standard version (follows semantic versioning) + +# Infrastructure & servers +servers: + - server: my-postgres + type: postgres + host: localhost + port: 5432 + database: pypl-edw + schema: pp_access_views + +# Dataset, schema, and quality +schema: + - id: tbl_obj + name: tbl + physicalName: tbl_1 + physicalType: table + businessName: Core Payment Metrics + description: Provides core payment metrics + authoritativeDefinitions: + - url: https://catalog.data.gov/dataset/air-quality + type: businessDefinition + - url: https://youtu.be/jbY1BKFj9ec + type: videoTutorial + tags: [ 'finance', 'payments'] + dataGranularityDescription: Aggregation on columns txn_ref_dt, pmt_txn_id + # Schema-level relationships (for composite keys) + relationships: + - type: foreignKey + from: + - tbl.rcvr_id + - tbl.rcvr_cntry_code + to: + - receivers.id + - receivers.country_code + customProperties: + - property: description + value: "Composite key linking to receivers table" + - property: cardinality + value: "many-to-one" + properties: + - id: txn_ref_dt_prop + name: transaction_reference_date + physicalName: txn_ref_dt + primaryKey: false + primaryKeyPosition: -1 + businessName: transaction reference date + logicalType: date + physicalType: date + required: false + description: Reference date for transaction + partitioned: true + partitionKeyPosition: 1 + criticalDataElement: false + tags: [ ] + classification: public + transformSourceObjects: + - table_name_1 + - table_name_2 + - table_name_3 + transformLogic: sel t1.txn_dt as txn_ref_dt from table_name_1 as t1, table_name_2 as t2, table_name_3 as t3 where t1.txn_dt=date-3 + transformDescription: defines the logic in business terms; logic for dummies + examples: + - "2022-10-03" + - "2020-01-28" + customProperties: + - property: anonymizationStrategy + value: none + - id: rcvr_id_prop + name: rcvr_id + primaryKey: true + primaryKeyPosition: 1 + businessName: receiver id + logicalType: string + physicalType: varchar(18) + required: false + description: A description for column rcvr_id. + partitioned: false + partitionKeyPosition: -1 + criticalDataElement: false + tags: [ 'uid' ] + classification: restricted + # Property-level relationship (from is implicit) + relationships: + - to: receivers.id + type: foreignKey + customProperties: + - property: description + value: "Links to receiver master data" + - id: rcvr_cntry_code_prop + name: rcvr_cntry_code + primaryKey: false + primaryKeyPosition: -1 + businessName: receiver country code + logicalType: string + physicalType: varchar(2) + required: false + description: Country code + partitioned: false + partitionKeyPosition: -1 + criticalDataElement: false + tags: [ ] + classification: public + # Enumeration of allowed values (RFC 0033, ODCS v3.2.0+) + enum: + - value: US + label: United States + description: ISO 3166-1 alpha-2 code for the United States. + - value: CA + label: Canada + - value: MX + label: Mexico + customProperties: + - property: languageEs + value: México + authoritativeDefinitions: + - url: https://collibra.com/asset/742b358f-71a5-4ab1-bda4-dcdba9418c25 + type: businessDefinition + - url: https://github.com/myorg/myrepo + type: transformationImplementation + - url: jdbc:postgresql://localhost:5432/adventureworks/tbl_1/rcvr_cntry_code + type: implementation + encryptedName: rcvr_cntry_code_encrypted + quality: + - metric: nullValues + mustBe: 0 + description: column should not contain null values + dimension: completeness + type: library + severity: error + businessImpact: operational + schedule: 0 20 * * * + scheduler: cron + customProperties: + - property: FIELD_NAME + value: + - property: COMPARE_TO + value: + - property: COMPARISON_TYPE + value: Greater than + quality: + - metric: rowCount + mustBeGreaterThan: 1000000 + type: library + description: Ensure row count is within expected volume range + dimension: completeness + method: reconciliation + severity: error + businessImpact: operational + schedule: 0 20 * * * + scheduler: cron + customProperties: + - property: business-key + value: + - txn_ref_dt + - rcvr_id + + # Receivers master table + - id: receivers_obj + name: receivers + physicalName: receivers_master + physicalType: table + businessName: Receivers Master Data + description: Master data for all receivers + tags: [ 'master-data', 'receivers' ] + properties: + - id: receiver_id_prop + name: id + primaryKey: true + primaryKeyPosition: 1 + businessName: receiver identifier + logicalType: string + physicalType: varchar(18) + required: true + description: Unique identifier for receiver + unique: true + classification: restricted + - id: country_code_prop + name: country_code + primaryKey: true + primaryKeyPosition: 2 + businessName: receiver country + logicalType: string + physicalType: varchar(2) + required: true + description: Country code of the receiver + classification: public + - id: receiver_name_prop + name: receiver_name + businessName: receiver name + logicalType: string + physicalType: varchar(255) + required: true + description: Name of the receiver + classification: restricted + - id: receiver_type_prop + name: receiver_type + businessName: receiver type + logicalType: string + physicalType: varchar(20) + required: false + description: Type of receiver (individual, business, etc.) + classification: public + # Example of nested reference + relationships: + - to: receiver_types.type_code + customProperties: + - property: description + value: "Links to receiver type definitions" + # Map-typed property (RFC 0030, ODCS v3.2.0+) + - id: receiver_attributes_prop + name: receiver_attributes + businessName: receiver attributes + logicalType: map + physicalType: "MAP" + required: false + description: Free-form attributes attached to a receiver, keyed by attribute name. + classification: restricted + map: + key: + logicalType: string + description: Attribute name. + value: + logicalType: string + description: Attribute value. + + +# Pricing +price: + priceAmount: 9.95 + priceCurrency: USD + priceUnit: megabyte + + +# Team +team: + name: my-team + description: The team owning the data contract + members: + - username: ceastwood + role: Data Scientist + dateIn: "2022-08-02" + dateOut: "2022-10-01" + replacedByUsername: mhopper + - username: mhopper + role: Data Scientist + dateIn: "2022-10-01" + - username: daustin + role: Owner + description: Keeper of the grail + dateIn: "2022-10-01" + + +# Roles +roles: + - role: microstrategy_user_opr + access: read + firstLevelApprovers: Reporting Manager + secondLevelApprovers: 'mandolorian' + - role: bq_queryman_user_opr + access: read + firstLevelApprovers: Reporting Manager + secondLevelApprovers: na + - role: risk_data_access_opr + access: read + firstLevelApprovers: Reporting Manager + secondLevelApprovers: 'dathvador' + - role: bq_unica_user_opr + access: write + firstLevelApprovers: Reporting Manager + secondLevelApprovers: 'mickey' + +# SLA +slaProperties: + - property: latency # Property, see list of values in DP QoS + value: 4 + unit: d # d, day, days for days; y, yr, years for years + element: tab1.txn_ref_dt # This would not be needed as it is the same table.column as the default one + - property: generalAvailability + value: "2022-05-12T09:30:10-08:00" + - property: endOfSupport + value: "2032-05-12T09:30:10-08:00" + - property: endOfLife + value: "2042-05-12T09:30:10-08:00" + - property: retention + value: 3 + unit: y + element: tab1.txn_ref_dt + - property: frequency + value: 1 + valueExt: 1 + unit: d + element: tab1.txn_ref_dt + - property: timeOfAvailability + value: 09:00-08:00 + element: tab1.txn_ref_dt + driver: regulatory # Describes the importance of the SLA: [regulatory|analytics|operational|...] + - property: timeOfAvailability + value: 08:00-08:00 + element: tab1.txn_ref_dt + driver: analytics + + +# Support +support: + - channel: '#product-help' # Simple Slack communication channel + tool: slack + - channel: datacontract-ann # Simple distribution list + tool: email + url: mailto:datacontract-ann@bitol.io + - channel: Feedback # Product Feedback + description: General Product Feedback (Public) + url: https://product-feedback.com + - channel: 'product-issues' + tool: teams + scope: issues + customProperties: + - property: servicehours + value: 9-5 CET + + +# Tags +tags: + - transactions + + +# Custom properties +customProperties: + - property: refRulesetName + value: gcsc.ruleset.name + - property: somePropertyName + value: property.value + - property: dataprocClusterName # Used for specific applications like Elevate + value: [ cluster name ] + +contractCreatedTs: "2022-11-15T02:59:43+00:00" diff --git a/sdks/typescript/tests/odcs_minimal.yaml b/sdks/typescript/tests/odcs_minimal.yaml new file mode 100644 index 00000000..87ce5996 --- /dev/null +++ b/sdks/typescript/tests/odcs_minimal.yaml @@ -0,0 +1,24 @@ +apiVersion: v3.2.0 +kind: DataContract +id: 11111111-2222-3333-4444-555555555555 +name: orders +version: 1.0.0 +status: active +description: + purpose: Minimal orders contract +schema: + - name: orders + physicalType: table + properties: + - name: order_id + logicalType: string + required: true + unique: true + - name: amount + logicalType: number + required: true + logicalTypeOptions: + minimum: 0 + - name: status + logicalType: string + enum: [open, closed] diff --git a/src/batch_rules.rs b/src/batch_rules.rs index 1c72c56b..e67ce6fb 100644 --- a/src/batch_rules.rs +++ b/src/batch_rules.rs @@ -406,6 +406,7 @@ ontology: fn field(name: &str, field_type: FieldType) -> FieldDefinition { FieldDefinition { + distribution: None, name: name.to_string(), field_type, required: false, diff --git a/src/cli/commands/enforce.rs b/src/cli/commands/enforce.rs index 86f80758..ed9042d1 100644 --- a/src/cli/commands/enforce.rs +++ b/src/cli/commands/enforce.rs @@ -38,6 +38,11 @@ pub struct EnforceArgs { #[arg(long, env = "CG_KAFKA_BROKER", value_name = "HOST:PORT")] pub broker: Option, + /// For an ODCS file with several `schema` objects: the one to use, by + /// name (default: the first). + #[arg(long, value_name = "NAME")] + pub schema_object: Option, + /// Kafka topic to consume. #[arg(long, value_name = "TOPIC")] pub topic: Option, @@ -74,7 +79,7 @@ pub struct EnforceArgs { pub fn run(args: &EnforceArgs) -> anyhow::Result { // Load and compile the contract. - let (contract_name, compiled) = load_contract(&args.contract)?; + let (contract_name, compiled) = load_contract(&args.contract, args.schema_object.as_deref())?; // Collect events to validate. let events = collect_events(args)?; @@ -130,7 +135,10 @@ pub fn run(args: &EnforceArgs) -> anyhow::Result { // Helpers // --------------------------------------------------------------------------- -fn load_contract(spec: &str) -> anyhow::Result<(String, CompiledContract)> { +fn load_contract( + spec: &str, + schema_object: Option<&str>, +) -> anyhow::Result<(String, CompiledContract)> { if spec.starts_with("id:") { anyhow::bail!( "contract ID lookup (id:uuid) is a Phase 2 feature; \ @@ -139,8 +147,9 @@ fn load_contract(spec: &str) -> anyhow::Result<(String, CompiledContract)> { } let yaml = std::fs::read_to_string(spec).map_err(|e| anyhow::anyhow!("cannot read {spec}: {e}"))?; - let contract: Contract = crate::odcs::parse_contract_yaml(&yaml) - .map_err(|e| anyhow::anyhow!("invalid contract YAML: {e}"))?; + let (contract, _notes): (Contract, Vec) = + crate::odcs::parse_contract_yaml_with(&yaml, schema_object) + .map_err(|e| anyhow::anyhow!("invalid contract YAML: {e}"))?; let name = contract.name.clone(); let compiled = CompiledContract::compile(contract) .map_err(|e| anyhow::anyhow!("contract compile failed: {e}"))?; diff --git a/src/cli/commands/synth.rs b/src/cli/commands/synth.rs index eba0e022..f6dc990a 100644 --- a/src/cli/commands/synth.rs +++ b/src/cli/commands/synth.rs @@ -50,6 +50,11 @@ pub struct SynthArgs { /// Write to this file instead of stdout. #[arg(long, short = 'o', value_name = "FILE")] pub out: Option, + + /// For an ODCS file with several `schema` objects: the one to use, by + /// name (default: the first). + #[arg(long, value_name = "NAME")] + pub schema_object: Option, } #[derive(Debug, Clone, Copy, clap::ValueEnum)] @@ -66,13 +71,13 @@ pub fn run(args: &SynthArgs) -> Result { return Ok(2); } }; - if let Ok((_, notes)) = crate::odcs::normalize_contract_yaml(&yaml) { - for n in notes { - eprintln!("note: {n}"); + let compiled = match synth::compile_yaml_with(&yaml, args.schema_object.as_deref()) { + Ok((c, notes)) => { + for n in notes { + eprintln!("note: {n}"); + } + c } - } - let compiled = match synth::compile_yaml(&yaml) { - Ok(c) => c, Err(e) => { eprintln!("error: {}", e.message); return Ok(2); diff --git a/src/cli/commands/test.rs b/src/cli/commands/test.rs index a6a67354..2347931b 100644 --- a/src/cli/commands/test.rs +++ b/src/cli/commands/test.rs @@ -46,6 +46,11 @@ pub struct TestArgs { /// Summary line only; suppress per-violation detail. #[arg(long)] pub quiet: bool, + + /// For an ODCS file with several `schema` objects: the one to use, by + /// name (default: the first). + #[arg(long, value_name = "NAME")] + pub schema_object: Option, } #[derive(Debug, Clone, clap::ValueEnum)] @@ -90,11 +95,12 @@ struct Summary { pub fn run(args: &TestArgs) -> anyhow::Result { // --- Load + compile contract (exit 2 on failure) ---------------------- - let (contract_name, compiled) = load_contract(&args.contract).map_err(|e| { - eprintln!("error: {e:#}"); - // We can't return i32 from map_err; we propagate and handle at call site. - e - })?; + let (contract_name, compiled) = load_contract(&args.contract, args.schema_object.as_deref()) + .map_err(|e| { + eprintln!("error: {e:#}"); + // We can't return i32 from map_err; we propagate and handle at call site. + e + })?; // --- Read records (exit 2 on top-level parse failure) ----------------- let records = read_records(&args.data).map_err(|e| { @@ -216,11 +222,15 @@ impl Format { } } -fn load_contract(path: &PathBuf) -> anyhow::Result<(String, CompiledContract)> { +fn load_contract( + path: &PathBuf, + schema_object: Option<&str>, +) -> anyhow::Result<(String, CompiledContract)> { let yaml = std::fs::read_to_string(path) .map_err(|e| anyhow::anyhow!("cannot read {}: {e}", path.display()))?; - let contract: Contract = crate::odcs::parse_contract_yaml(&yaml) - .map_err(|e| anyhow::anyhow!("invalid contract YAML: {e}"))?; + let (contract, _notes): (Contract, Vec) = + crate::odcs::parse_contract_yaml_with(&yaml, schema_object) + .map_err(|e| anyhow::anyhow!("invalid contract YAML: {e}"))?; let name = contract.name.clone(); let compiled = CompiledContract::compile(contract) .map_err(|e| anyhow::anyhow!("contract compile failed: {e}"))?; diff --git a/src/cli/commands/validate.rs b/src/cli/commands/validate.rs index fba95467..12fd6300 100644 --- a/src/cli/commands/validate.rs +++ b/src/cli/commands/validate.rs @@ -16,6 +16,11 @@ pub struct ValidateArgs { /// Emit machine-readable JSON output. #[arg(long)] pub json: bool, + + /// For an ODCS file with several `schema` objects: the one to use, by + /// name (default: the first). + #[arg(long, value_name = "NAME")] + pub schema_object: Option, } #[derive(Serialize)] @@ -57,7 +62,7 @@ pub fn run(args: &ValidateArgs, cfg: &CliConfig) -> Result { let mut any_failure = false; for path in &files { - let result = validate_file(path); + let result = validate_file(path, args.schema_object.as_deref()); match result { Ok(notes) => { let name = path.display().to_string(); @@ -99,11 +104,11 @@ pub fn run(args: &ValidateArgs, cfg: &CliConfig) -> Result { /// Native or ODCS v3.x YAML. Returns notes for anything in an ODCS document /// that did not map. -fn validate_file(path: &Path) -> Result> { +fn validate_file(path: &Path, schema_object: Option<&str>) -> Result> { let src = std::fs::read_to_string(path).map_err(|e| anyhow::anyhow!("cannot read file: {e}"))?; let (contract, notes): (Contract, Vec) = - crate::odcs::parse_contract_yaml_with_notes(&src) + crate::odcs::parse_contract_yaml_with(&src, schema_object) .map_err(|e| anyhow::anyhow!("YAML parse error: {e}"))?; CompiledContract::compile(contract).map_err(|e| anyhow::anyhow!("compile error: {e}"))?; Ok(notes) diff --git a/src/conformance.rs b/src/conformance.rs index b0db3a30..475fd2cf 100644 --- a/src/conformance.rs +++ b/src/conformance.rs @@ -379,6 +379,7 @@ mod tests { ontology: Ontology { entities: vec![ FieldDefinition { + distribution: None, name: "user_id".into(), field_type: FieldType::String, required: true, @@ -394,6 +395,7 @@ mod tests { format: None, }, FieldDefinition { + distribution: None, name: "amount".into(), field_type: FieldType::Float, required: false, diff --git a/src/contract.rs b/src/contract.rs index 3941cd8d..fd1b0823 100644 --- a/src/contract.rs +++ b/src/contract.rs @@ -344,6 +344,128 @@ pub struct FieldDefinition { /// are carried as metadata only. Omitted from YAML when unset. #[serde(default, skip_serializing_if = "Option::is_none")] pub format: Option, + /// Synthetic-data hint for integer / number fields (RFC-117). Only + /// `synth` reads it: validation ignores it. Omitted from YAML when unset. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub distribution: Option, +} + +/// How `synth` draws values for a numeric field. Values are always kept +/// inside the field's `min` / `max` (draws outside are redrawn), and an +/// `enum` on the field wins over the hint. +/// +/// YAML forms: `distribution: uniform`, or a map such as +/// `{type: normal, mean: 50, sd: 10}`, `{type: lognormal, mean: 3, sd: 0.5}` +/// or `{type: exponential, rate: 0.1}`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(tag = "type", rename_all = "lowercase")] +pub enum Distribution { + /// Evenly between `min` and `max` (the default when no hint is given). + Uniform, + /// Bell curve with the given mean and standard deviation. + Normal { mean: f64, sd: f64 }, + /// `exp(N(mean, sd))`: `mean` and `sd` describe the underlying normal, + /// not the resulting values (the NumPy / R convention). Right-skewed. + Lognormal { mean: f64, sd: f64 }, + /// `min + Exp(rate)` (from 0 when there is no `min`); the mean spread + /// above the start is `1 / rate`. Right-skewed. + Exponential { rate: f64 }, +} + +impl Distribution { + /// The `type` name, for messages. + pub fn name(&self) -> &'static str { + match self { + Distribution::Uniform => "uniform", + Distribution::Normal { .. } => "normal", + Distribution::Lognormal { .. } => "lognormal", + Distribution::Exponential { .. } => "exponential", + } + } + + /// Names accepted for `type`. + const KINDS: &'static str = "uniform, normal, lognormal, exponential"; + + /// Build from a parsed YAML/JSON value, with a message naming the problem. + pub fn from_value(v: &serde_yaml::Value) -> Result { + use serde_yaml::Value; + let (kind, map) = match v { + Value::String(s) => (s.clone(), None), + Value::Mapping(m) => { + let kind = m + .get("type") + .or_else(|| m.get("kind")) + .and_then(|k| k.as_str()) + .ok_or_else(|| format!("distribution needs a `type` ({})", Self::KINDS))? + .to_string(); + (kind, Some(m)) + } + _ => { + return Err(format!( + "distribution must be a name or a map with a `type` ({})", + Self::KINDS + )) + } + }; + let kind = kind.to_ascii_lowercase(); + let num = |key: &str| -> Result { + map.and_then(|m| m.get(key)) + .and_then(|v| v.as_f64()) + .filter(|n| n.is_finite()) + .ok_or_else(|| format!("distribution {kind} needs a numeric `{key}`")) + }; + let allowed: &[&str] = match kind.as_str() { + "uniform" => &[], + "normal" | "lognormal" => &["mean", "sd"], + "exponential" => &["rate"], + other => { + return Err(format!( + "unknown distribution type {other:?}; use one of: {}", + Self::KINDS + )) + } + }; + if let Some(m) = map { + for key in m.keys().filter_map(|k| k.as_str()) { + if key != "type" && key != "kind" && !allowed.contains(&key) { + return Err(format!("distribution {kind} does not take `{key}`")); + } + } + } + let d = match kind.as_str() { + "uniform" => Distribution::Uniform, + "normal" => Distribution::Normal { + mean: num("mean")?, + sd: num("sd")?, + }, + "lognormal" => Distribution::Lognormal { + mean: num("mean")?, + sd: num("sd")?, + }, + _ => Distribution::Exponential { rate: num("rate")? }, + }; + match &d { + Distribution::Normal { sd, .. } | Distribution::Lognormal { sd, .. } if *sd <= 0.0 => { + Err(format!( + "distribution {kind} needs sd greater than 0, got {sd}" + )) + } + Distribution::Exponential { rate } if *rate <= 0.0 => Err(format!( + "distribution exponential needs rate greater than 0, got {rate}" + )), + _ => Ok(d), + } + } +} + +impl<'de> Deserialize<'de> for Distribution { + fn deserialize(d: D) -> Result + where + D: serde::Deserializer<'de>, + { + let v = serde_yaml::Value::deserialize(d)?; + Distribution::from_value(&v).map_err(serde::de::Error::custom) + } } /// Supported field types inside a contract ontology. @@ -1209,6 +1331,11 @@ pub struct VersionResponse { pub import_source: ImportSource, /// When `true`, human review is required before promotion to stable. pub requires_review: bool, + /// Import notes: ODCS content that did not map (ignored schema objects, + /// composite key, relationships). Only set by `POST /contracts/import`, + /// and omitted from the JSON when empty. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub notes: Vec, } impl From<&ContractVersion> for VersionResponse { @@ -1226,6 +1353,7 @@ impl From<&ContractVersion> for VersionResponse { egress_leakage_mode: v.egress_leakage_mode, import_source: v.import_source, requires_review: v.requires_review, + notes: Vec::new(), } } } diff --git a/src/dbt_yaml.rs b/src/dbt_yaml.rs index 635a9db8..6b11e143 100644 --- a/src/dbt_yaml.rs +++ b/src/dbt_yaml.rs @@ -637,6 +637,7 @@ fn import_column( } Ok(FieldDefinition { + distribution: None, name, field_type, required, diff --git a/src/egress.rs b/src/egress.rs index 72036eae..c15a3f05 100644 --- a/src/egress.rs +++ b/src/egress.rs @@ -789,6 +789,7 @@ mod tests { fn bare_field(name: &str) -> FieldDefinition { FieldDefinition { + distribution: None, name: name.into(), field_type: FieldType::String, required: true, diff --git a/src/infer.rs b/src/infer.rs index 08c8a738..8bda1729 100644 --- a/src/infer.rs +++ b/src/infer.rs @@ -169,6 +169,7 @@ fn infer_field(name: &str, values: &[&Value], total_samples: usize) -> FieldDefi let field_type = infer_type(&non_null); let mut def = FieldDefinition { + distribution: None, name: name.to_string(), field_type: field_type.clone(), required, diff --git a/src/infer_avro.rs b/src/infer_avro.rs index fc59c343..bad2bb4b 100644 --- a/src/infer_avro.rs +++ b/src/infer_avro.rs @@ -181,6 +181,7 @@ fn avro_field_to_definition(field: &Value) -> Result { let (field_type, required, allowed_values, properties, items) = resolve_avro_type(type_val)?; Ok(FieldDefinition { + distribution: None, name, field_type, required, @@ -229,6 +230,7 @@ fn resolve_avro_type(type_val: &Value) -> AvroTypeResolution { let (item_ft, item_req, item_av, item_props, item_items) = resolve_avro_type(items_val)?; let items_def = FieldDefinition { + distribution: None, name: "item".to_string(), field_type: item_ft, required: item_req, diff --git a/src/infer_diff.rs b/src/infer_diff.rs index f3a669a8..06f7d3fe 100644 --- a/src/infer_diff.rs +++ b/src/infer_diff.rs @@ -389,6 +389,7 @@ mod tests { fn simple_field(name: &str, ft: FieldType, required: bool) -> FieldDefinition { FieldDefinition { + distribution: None, name: name.to_string(), field_type: ft, required, diff --git a/src/infer_openapi.rs b/src/infer_openapi.rs index e825b6d2..8d5aa3ee 100644 --- a/src/infer_openapi.rs +++ b/src/infer_openapi.rs @@ -199,6 +199,7 @@ fn json_schema_to_definition( let (item_ft, item_props, item_items) = resolve_schema_type(items_s); let item_av = items_s.get("enum").and_then(|e| e.as_array()).cloned(); FieldDefinition { + distribution: None, name: "item".to_string(), field_type: item_ft, required: true, @@ -215,6 +216,7 @@ fn json_schema_to_definition( } } else { FieldDefinition { + distribution: None, name: "item".to_string(), field_type: FieldType::Any, required: true, @@ -262,6 +264,7 @@ fn json_schema_to_definition( .map(|v| v as usize); Ok(FieldDefinition { + distribution: None, name: name.to_string(), field_type, required, diff --git a/src/infer_proto.rs b/src/infer_proto.rs index 34e5c820..6f74d772 100644 --- a/src/infer_proto.rs +++ b/src/infer_proto.rs @@ -489,6 +489,7 @@ fn proto_field_to_definition( let (field_type, allowed_values, properties, items) = resolve_proto_type(f, proto); Ok(FieldDefinition { + distribution: None, name: f.name.clone(), field_type, required: !f.optional, @@ -516,6 +517,7 @@ fn resolve_proto_type(f: &ProtoField, proto: &ParsedProto) -> ProtoTypeResolutio }; let (item_ft, item_av, item_props, item_items) = resolve_proto_type(&inner, proto); let items_def = FieldDefinition { + distribution: None, name: "item".to_string(), field_type: item_ft, required: true, diff --git a/src/main.rs b/src/main.rs index 87862ea8..fd946ba3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -970,7 +970,8 @@ async fn import_odcs_handler( .await .map_err(|e| AppError::BadRequest(e.to_string()))?; - let result = odcs::import_odcs(&body.odcs_yaml).map_err(AppError::BadRequest)?; + let result = odcs::import_odcs_with(&body.odcs_yaml, body.schema_object.as_deref()) + .map_err(AppError::BadRequest)?; // Name override from request body wins over the ODCS-parsed name. let name_in_yaml: Contract = serde_yaml::from_str(&result.yaml_content) @@ -1011,7 +1012,9 @@ async fn import_odcs_handler( state.self_hosted, ) .await?; - return Ok((StatusCode::CREATED, Json(VersionResponse::from(&cv)))); + let mut resp = VersionResponse::from(&cv); + resp.notes = result.warnings; + return Ok((StatusCode::CREATED, Json(resp))); } // No target: a new identity needs an org (NOT NULL column). @@ -1059,7 +1062,9 @@ async fn import_odcs_handler( ) .await?; - Ok((StatusCode::CREATED, Json(VersionResponse::from(&cv)))) + let mut resp = VersionResponse::from(&cv); + resp.notes = result.warnings; + Ok((StatusCode::CREATED, Json(resp))) } /// `GET /contracts/:id/versions/:version/export` — return the contract version diff --git a/src/odcs.rs b/src/odcs.rs index 08518e13..1ae3db02 100644 --- a/src/odcs.rs +++ b/src/odcs.rs @@ -24,8 +24,8 @@ //! `name`; callers must NOT pass the salt to any outbound serializer. use crate::contract::{ - Contract, ContractIdentity, ContractVersion, EgressLeakageMode, FieldDefinition, FieldType, - ImportSource, Ontology, QualityRule, QualityRuleType, UniqueScope, VersionState, + Contract, ContractIdentity, ContractVersion, Distribution, EgressLeakageMode, FieldDefinition, + FieldType, ImportSource, Ontology, QualityRule, QualityRuleType, UniqueScope, VersionState, }; use serde_yaml::{Mapping, Value}; @@ -267,6 +267,11 @@ fn build_odcs_property(name: &str, f: &FieldDefinition, prop_quality: &[&Quality if let Some(v) = f.max { custom.push(custom_prop("x-cg-max", num(v))); } + if let Some(d) = &f.distribution { + if let Ok(v) = serde_yaml::to_value(d) { + custom.push(custom_prop("x-cg-distribution", v)); + } + } if let Some(v) = f.min_length { custom.push(custom_prop( "x-cg-min-length", @@ -699,6 +704,14 @@ fn description_text(v: Option<&Value>) -> Option { /// transforms, glossary, metrics, and dataset-level rules (`rowCount`) are /// not recoverable — the caller sets `requires_review = true` (D-002). pub fn import_odcs(yaml: &str) -> Result { + import_odcs_with(yaml, None) +} + +/// [`import_odcs`] for a document whose `schema` has several objects: +/// `schema_object` picks one by `name` (or `physicalName`, or `id`); the +/// first object is used when it is `None`. A DataContractGate export (lossless +/// import) is a single contract, so the choice does not apply to it. +pub fn import_odcs_with(yaml: &str, schema_object: Option<&str>) -> Result { let doc: Value = serde_yaml::from_str(yaml).map_err(|e| format!("invalid ODCS YAML: {e}"))?; let mapping = doc @@ -731,9 +744,17 @@ pub fn import_odcs(yaml: &str) -> Result { }; if root_extension(mapping, "x-contractgate-version").is_some() { - import_mode_a(mapping, version) + let mut r = import_mode_a(mapping, version)?; + if schema_object.is_some() { + r.warnings.push( + "schema_object ignored: this document is a DataContractGate export, \ + which carries one contract" + .to_string(), + ); + } + Ok(r) } else { - import_mode_b(mapping, version) + import_mode_b(mapping, version, schema_object) } } @@ -792,10 +813,20 @@ fn looks_like_odcs(yaml: &str) -> bool { pub fn normalize_contract_yaml( yaml: &str, ) -> Result<(std::borrow::Cow<'_, str>, Vec), String> { + normalize_contract_yaml_with(yaml, None) +} + +/// [`normalize_contract_yaml`] with a `schema_object` choice for ODCS +/// documents that have several schema objects (see [`import_odcs_with`]). +/// Ignored for native YAML. +pub fn normalize_contract_yaml_with<'a>( + yaml: &'a str, + schema_object: Option<&str>, +) -> Result<(std::borrow::Cow<'a, str>, Vec), String> { if !looks_like_odcs(yaml) { return Ok((std::borrow::Cow::Borrowed(yaml), Vec::new())); } - let r = import_odcs(yaml).map_err(|e| format!("ODCS import: {e}"))?; + let r = import_odcs_with(yaml, schema_object).map_err(|e| format!("ODCS import: {e}"))?; Ok((std::borrow::Cow::Owned(r.yaml_content), r.warnings)) } @@ -806,7 +837,15 @@ pub fn parse_contract_yaml(yaml: &str) -> Result { /// Like [`parse_contract_yaml`], also returning ODCS import notes. pub fn parse_contract_yaml_with_notes(yaml: &str) -> Result<(Contract, Vec), String> { - let (native, notes) = normalize_contract_yaml(yaml)?; + parse_contract_yaml_with(yaml, None) +} + +/// [`parse_contract_yaml_with_notes`] with a `schema_object` choice. +pub fn parse_contract_yaml_with( + yaml: &str, + schema_object: Option<&str>, +) -> Result<(Contract, Vec), String> { + let (native, notes) = normalize_contract_yaml_with(yaml, schema_object)?; let contract: Contract = serde_yaml::from_str(&native).map_err(|e| e.to_string())?; Ok((contract, notes)) } @@ -872,7 +911,11 @@ fn import_mode_a(doc: &Mapping, version: String) -> Result // ── Mode B (stripped / foreign ODCS) ───────────────────────────────────────── -fn import_mode_b(doc: &Mapping, version: String) -> Result { +fn import_mode_b( + doc: &Mapping, + version: String, + schema_object: Option<&str>, +) -> Result { let schema_seq = doc .get("schema") .and_then(|v| v.as_sequence()) @@ -882,14 +925,41 @@ fn import_mode_b(doc: &Mapping, version: String) -> Result .to_string() })?; + let object_name = |v: &Value| -> String { + v.as_mapping() + .and_then(|m| m.get("name")) + .and_then(|n| n.as_str()) + .unwrap_or("?") + .to_string() + }; + // Which schema object: by name, physicalName or id when asked, else the first. + let idx = match schema_object { + None => 0, + Some(want) => schema_seq + .iter() + .position(|o| { + o.as_mapping().is_some_and(|m| { + ["name", "physicalName", "id"] + .iter() + .any(|k| m.get(*k).and_then(|v| v.as_str()) == Some(want)) + }) + }) + .ok_or_else(|| { + let names: Vec = schema_seq.iter().map(object_name).collect(); + format!( + "schema object '{want}' not found; this document has: {}", + names.join(", ") + ) + })?, + }; let schema0 = schema_seq - .first() + .get(idx) .and_then(|v| v.as_mapping()) .ok_or_else(|| { "ODCS 'schema' array is empty or its first entry is not a mapping".to_string() })?; - // Contract name: dataProduct › schema[0].name › root name (the order + // Contract name: dataProduct › schema object name › root name (the order // existing imports already use). let name = doc .get("dataProduct") @@ -909,8 +979,8 @@ fn import_mode_b(doc: &Mapping, version: String) -> Result .filter(|p| !p.is_empty()) .ok_or_else(|| { format!( - "ODCS schema[0] ('{}') has no properties; nothing to validate. \ - Add schema[0].properties[] with a name and logicalType per field", + "ODCS schema[{idx}] ('{}') has no properties; nothing to validate. \ + Add schema[{idx}].properties[] with a name and logicalType per field", schema0.get("name").and_then(|v| v.as_str()).unwrap_or("?") ) })?; @@ -923,23 +993,46 @@ fn import_mode_b(doc: &Mapping, version: String) -> Result .get("name") .and_then(|v| v.as_str()) .unwrap_or("schema[0]"); - let skipped: Vec<&str> = schema_seq + let skipped: Vec = schema_seq .iter() - .skip(1) - .map(|s| { - s.as_mapping() - .and_then(|m| m.get("name")) - .and_then(|v| v.as_str()) - .unwrap_or("?") - }) + .enumerate() + .filter(|(i, _)| *i != idx) + .map(|(_, o)| object_name(o)) .collect(); warnings.push(format!( - "ODCS schema has {} objects; imported '{}' (schema[0]) and ignored: {}", + "ODCS schema has {} objects; imported '{}' (schema[{}]) and ignored: {}. \ + Pick another with schema_object (--schema-object on the CLI)", schema_seq.len(), used, + idx, skipped.join(", ") )); } + let key_cols: Vec<&str> = props + .iter() + .filter_map(|p| p.as_mapping()) + .filter(|m| m.get("primaryKey").and_then(|v| v.as_bool()) == Some(true)) + .filter_map(|m| m.get("name").and_then(|v| v.as_str())) + .collect(); + if key_cols.len() > 1 { + warnings.push(format!( + "composite primary key ({}): each column is required, but uniqueness of the \ + combination is not enforced (uniqueness rules cover one field)", + key_cols.join(", ") + )); + } + let has_relationships = schema0.contains_key("relationships") + || props + .iter() + .filter_map(|p| p.as_mapping()) + .any(|m| m.contains_key("relationships")); + if has_relationships { + warnings.push( + "relationships (foreign keys) are not enforced: a contract validates one object's \ + events and has no lookup into another" + .to_string(), + ); + } let compliance_mode = root_extension(doc, "x-contractgate-compliance-mode") .and_then(|v| v.as_bool()) @@ -1068,6 +1161,7 @@ fn build_field_tree(pairs: Vec<(String, FieldDefinition)>) -> Result Result = None; if field_type == FieldType::Date && format.as_deref() == Some(CG_DATE_FORMAT) { format = None; // CG's built-in date format } @@ -1254,6 +1349,14 @@ fn odcs_prop_to_field(m: &Mapping, full_name: &str) -> Result format = val.and_then(|v| v.as_str()).map(String::from), + // Synth-only hint; a bad value is an error, not silently dropped. + "x-cg-distribution" => { + if let Some(v) = val.filter(|v| !v.is_null()) { + distribution = Some(Distribution::from_value(v).map_err(|e| { + format!("property '{full_name}': x-cg-distribution: {e}") + })?); + } + } // Transform kind/style not reconstructed in Mode B — // transform secrets (salt) are absent; review required (D-002). _ => {} @@ -1276,6 +1379,7 @@ fn odcs_prop_to_field(m: &Mapping, full_name: &str) -> Result Result, /// Optional contract identity name override. When absent, the importer /// reads `dataProduct` (or `schema[0].name`) from the ODCS document. #[serde(default)] diff --git a/src/scaffold/merge.rs b/src/scaffold/merge.rs index 4947f26b..6c981f3e 100644 --- a/src/scaffold/merge.rs +++ b/src/scaffold/merge.rs @@ -209,6 +209,7 @@ mod tests { fn make_field(name: &str, ft: FieldType) -> FieldDefinition { FieldDefinition { + distribution: None, name: name.to_string(), field_type: ft, required: true, diff --git a/src/synth.rs b/src/synth.rs index 15102912..049f824d 100644 --- a/src/synth.rs +++ b/src/synth.rs @@ -24,7 +24,7 @@ //! `freshness` rules, which are defined relative to the current time. use crate::contract::{ - CompareOp, Contract, CrossFieldRule, FieldDefinition, FieldType, QualityRuleType, + CompareOp, Contract, CrossFieldRule, Distribution, FieldDefinition, FieldType, QualityRuleType, }; use crate::validation::{ compare_holds, concrete_rule, expand_cross_rule, pattern_for, string_format_ok, validate_at, @@ -49,6 +49,8 @@ const NAMED_ATTEMPTS: usize = 6; const ROW_ATTEMPTS: usize = 64; /// Attempts to break one rule in isolation before skipping it. const BREAK_ATTEMPTS: usize = 16; +/// Redraws of a distribution value before giving up on the bounds. +const DIST_ATTEMPTS: usize = 1000; /// Which kind of rows to generate. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -199,10 +201,23 @@ pub fn generate( /// Parse and compile contract YAML, mapping failures to a `contract` rule error. pub fn compile_yaml(yaml: &str) -> Result { - let contract: Contract = crate::odcs::parse_contract_yaml(yaml) - .map_err(|e| SynthError::new("contract", None, format!("invalid contract YAML: {e}")))?; - CompiledContract::compile(contract) - .map_err(|e| SynthError::new("contract", None, format!("contract does not compile: {e}"))) + compile_yaml_with(yaml, None).map(|(c, _)| c) +} + +/// [`compile_yaml`] for ODCS documents with several `schema` objects: +/// `schema_object` picks one by name. Also returns the ODCS import notes. +pub fn compile_yaml_with( + yaml: &str, + schema_object: Option<&str>, +) -> Result<(CompiledContract, Vec), SynthError> { + let (contract, notes): (Contract, Vec) = + crate::odcs::parse_contract_yaml_with(yaml, schema_object).map_err(|e| { + SynthError::new("contract", None, format!("invalid contract YAML: {e}")) + })?; + let compiled = CompiledContract::compile(contract).map_err(|e| { + SynthError::new("contract", None, format!("contract does not compile: {e}")) + })?; + Ok((compiled, notes)) } // --------------------------------------------------------------------------- @@ -1413,6 +1428,30 @@ impl<'a> Generator<'a> { return Ok(json!(rfc3339(secs))); } } + // A distribution hint (RFC-117 follow-up) reshapes numeric draws. + // `uniform` is the default and keeps the original code path. + if let Some(d) = f + .distribution + .as_ref() + .filter(|d| **d != Distribution::Uniform) + { + match f.field_type { + FieldType::Integer | FieldType::Float => { + return self.draw_distribution(f, path, d); + } + _ => { + return Err(SynthError::new( + "distribution", + Some(path), + format!( + "field '{path}' has a {} distribution, which only applies to \ + integer and number fields", + d.name() + ), + )); + } + } + } Ok(match f.field_type { FieldType::Integer => { let (lo, hi) = int_bounds(f, path)?; @@ -1442,6 +1481,93 @@ impl<'a> Generator<'a> { }) } + /// Standard normal draw (Box-Muller), deterministic for the seed. + fn std_normal(&mut self) -> f64 { + let u1 = 1.0 - self.rng.gen::(); + let u2 = self.rng.gen::(); + (-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos() + } + + /// One integer or number from a `normal`, `lognormal` or `exponential` + /// hint. Draws outside the field's `min` / `max` are redrawn, so the + /// result is the distribution truncated to the bounds. + fn draw_distribution( + &mut self, + f: &FieldDefinition, + path: &str, + d: &Distribution, + ) -> Result { + let integer = f.field_type == FieldType::Integer; + let lo = f.min.map(|m| if integer { m.ceil() } else { m }); + let hi = f.max.map(|m| if integer { m.floor() } else { m }); + if let (Some(a), Some(b)) = (lo, hi) { + if a > b { + return Err(SynthError::new( + "min", + Some(path), + format!( + "field '{path}' has no {} between min {:?} and max {:?}", + if integer { "integer" } else { "number" }, + f.min, + f.max + ), + )); + } + } + // Digits kept for non-integers: 2 normally, more when values are small. + let scale = match d { + Distribution::Normal { sd, .. } => *sd, + Distribution::Lognormal { mean, .. } => mean.exp(), + Distribution::Exponential { rate } => 1.0 / rate, + Distribution::Uniform => 1.0, + }; + let decimals = if scale >= 1.0 || !scale.is_finite() || scale <= 0.0 { + 2 + } else { + (2.0 + (-scale.log10()).ceil()).min(8.0) as i32 + }; + let factor = 10f64.powi(decimals); + for _ in 0..DIST_ATTEMPTS { + let x = match d { + Distribution::Normal { mean, sd } => mean + sd * self.std_normal(), + Distribution::Lognormal { mean, sd } => (mean + sd * self.std_normal()).exp(), + Distribution::Exponential { rate } => { + f.min.unwrap_or(0.0) - (1.0 - self.rng.gen::()).ln() / rate + } + Distribution::Uniform => unreachable!("uniform keeps the default path"), + }; + if !x.is_finite() { + continue; + } + let v = if integer { + x.round() + } else { + let r = (x * factor).round() / factor; + // Rounding may step over a bound; use the raw draw then. + if lo.is_some_and(|a| r < a) || hi.is_some_and(|b| r > b) { + x + } else { + r + } + }; + if v.abs() > SAFE_INT || lo.is_some_and(|a| v < a) || hi.is_some_and(|b| v > b) { + continue; + } + return Ok(if integer { json!(v as i64) } else { json!(v) }); + } + Err(SynthError::new( + "distribution", + Some(path), + format!( + "field '{path}': the {} distribution puts almost no values between min {:?} \ + and max {:?}; move the mean or widen the bounds", + d.name(), + f.min, + f.max + ), + )) + } + fn string_value( &mut self, f: &FieldDefinition, @@ -2010,6 +2136,7 @@ fn numeric_template(path: &str, min: Option, max: Option) -> FieldDefi fn string_template(path: &str) -> FieldDefinition { FieldDefinition { + distribution: None, name: path.to_string(), field_type: FieldType::String, required: true, diff --git a/src/synth_handler.rs b/src/synth_handler.rs index e9580eab..3154a622 100644 --- a/src/synth_handler.rs +++ b/src/synth_handler.rs @@ -49,6 +49,10 @@ pub struct SynthRequest { /// `envelope_payload` (RFC-118). 400 when the contract has none. #[serde(default)] pub envelope: bool, + /// For `yaml_content` in ODCS with several `schema` objects: which one to + /// use, by name. The first when omitted. + #[serde(default)] + pub schema_object: Option, } fn default_rows() -> usize { @@ -104,6 +108,7 @@ pub async fn synth_handler( None => chrono::Utc::now(), }; let want_envelope = req.envelope; + let schema_object = req.schema_object.clone(); let seed = req.seed.unwrap_or_else(rand::random); let opts = SynthOptions { rows: req.rows, @@ -115,7 +120,7 @@ pub async fn synth_handler( let started = std::time::Instant::now(); // CPU-bound; keep it off the async reactor. let result = tokio::task::spawn_blocking(move || { - let compiled = synth::compile_yaml(&yaml)?; + let (compiled, notes) = synth::compile_yaml_with(&yaml, schema_object.as_deref())?; let name = compiled.contract.name.clone(); let version = compiled.contract.version.clone(); let out = synth::generate(&compiled, &opts)?; @@ -128,13 +133,13 @@ pub async fn synth_handler( } else { None }; - Ok::<_, synth::SynthError>((name, version, out, payload)) + Ok::<_, synth::SynthError>((name, version, out, payload, notes)) }) .await .map_err(|e| AppError::Internal(format!("synth task failed: {e}")))?; match result { - Ok((name, version, out, payload)) => { + Ok((name, version, out, payload, notes)) => { let count = out.rows.len() + out.invalid_rows.len(); let rows: Value = match out.mode { SynthMode::Valid => Value::Array(out.rows), @@ -155,6 +160,9 @@ pub async fn synth_handler( if let Some(p) = payload { body["envelope_payload"] = p; } + if !notes.is_empty() { + body["notes"] = json!(notes); + } Ok(Json(body).into_response()) } Err(e) => { @@ -205,6 +213,7 @@ pub fn merge_openapi(paths: &mut serde_json::Map) { "mode": {"type": "string", "enum": ["valid", "invalid"], "default": "valid"}, "seed": {"type": "integer", "minimum": 0}, "anchor_time": {"type": "string", "format": "date-time", "description": "Time freshness rules are measured from. Now when omitted. Set it with seed for rows that repeat exactly."}, + "schema_object": {"type": "string", "description": "For ODCS yaml_content with several schema objects: the one to use, by name. The first when omitted."}, "envelope": {"type": "boolean", "default": false, "description": "Also return the rows wrapped in the contract's envelope as envelope_payload. 400 no_envelope when the contract has none."} }}}}}, "responses": { @@ -215,6 +224,7 @@ pub fn merge_openapi(paths: &mut serde_json::Map) { "seed": {"type": "integer"}, "anchor_time": {"type": "string", "format": "date-time"}, "envelope_payload": {"type": "object", "description": "Present when envelope=true: the records wrapped in the contract's envelope."}, + "notes": {"type": "array", "items": {"type": "string"}, "description": "ODCS content that did not map (ignored schema objects, composite key, relationships). Omitted when empty."}, "row_count": {"type": "integer"}, "rows": {"type": "array", "description": "valid: records. invalid: {record, broken_rule: {field, rule, metric?, violation_kind, message, constraint?}}.", "items": {"type": "object"}}, "skipped_rules": {"type": "array", "items": {"type": "object", "properties": {"field": {"type": "string"}, "rule": {"type": "string"}, "reason": {"type": "string"}}}}, @@ -265,6 +275,36 @@ mod tests { assert!(row["id"].as_str().unwrap().starts_with('A')); } + const ODCS_MULTI: &str = "apiVersion: v3.1.0\nkind: DataContract\nversion: 1.0.0\nschema:\n - name: a\n properties:\n - name: x\n logicalType: integer\n required: true\n - name: b\n properties:\n - name: y\n logicalType: string\n required: true\n"; + + #[tokio::test] + async fn odcs_schema_object_selects_and_notes_are_returned() { + let r = server() + .post("/contracts/synth") + .json(&json!({"yaml_content": ODCS_MULTI, "rows": 3, "seed": 1})) + .await; + assert_eq!(r.status_code(), StatusCode::OK); + let b = r.json::(); + assert!(b["rows"][0]["x"].is_number()); + assert!(b["notes"][0].as_str().unwrap().contains("ignored: b")); + let r = server() + .post("/contracts/synth") + .json(&json!({"yaml_content": ODCS_MULTI, "rows": 3, "seed": 1, "schema_object": "b"})) + .await; + let b = r.json::(); + assert!(b["rows"][0]["y"].is_string()); + assert!(b["notes"][0].as_str().unwrap().contains("ignored: a")); + let r = server() + .post("/contracts/synth") + .json(&json!({"yaml_content": ODCS_MULTI, "schema_object": "zzz"})) + .await; + assert_eq!(r.status_code(), StatusCode::UNPROCESSABLE_ENTITY); + assert!(r.json::()["message"] + .as_str() + .unwrap() + .contains("'zzz' not found")); + } + #[tokio::test] async fn inline_invalid_rows_are_labeled() { let r = server() diff --git a/src/tests.rs b/src/tests.rs index e055f1e4..61318341 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -36,6 +36,7 @@ mod fixtures { #[allow(dead_code)] pub fn entity(name: &str, field_type: FieldType) -> FieldDefinition { FieldDefinition { + distribution: None, name: name.to_string(), field_type, required: false, @@ -2070,6 +2071,7 @@ mod rfc028_tests { ontology: Ontology { entities: vec![ FieldDefinition { + distribution: None, name: "monthly_rent".into(), field_type: FieldType::Float, required: true, @@ -2085,6 +2087,7 @@ mod rfc028_tests { format: None, }, FieldDefinition { + distribution: None, name: "tenant_id".into(), field_type: FieldType::String, required: true, diff --git a/src/transform.rs b/src/transform.rs index 9a8e32a3..b943ec9c 100644 --- a/src/transform.rs +++ b/src/transform.rs @@ -232,6 +232,7 @@ mod tests { fn entity(name: &str, transform: Option) -> FieldDefinition { FieldDefinition { + distribution: None, name: name.to_string(), field_type: FieldType::String, required: false, diff --git a/src/v1_ingest.rs b/src/v1_ingest.rs index 2d258b0d..893b580d 100644 --- a/src/v1_ingest.rs +++ b/src/v1_ingest.rs @@ -625,7 +625,7 @@ fn extra_openapi_paths(paths: &mut serde_json::Map) { paths.insert("/contracts/import/dbt".into(), json!({"post": {"operationId": "import_dbt", "summary": "Import a dbt model contract as a DataContractGate draft", "description": "RFC-120. Body is dbt schema.yml (`dbt_yaml`) plus optional `model`, `name_override`, and `target_contract_id`. Creates a native draft, or a new version on a contract the caller owns. Mirrors POST /contracts/import (ODCS).", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["dbt_yaml"], "properties": {"dbt_yaml": {"type": "string"}, "model": {"type": "string"}, "name_override": {"type": "string"}, "target_contract_id": {"type": "string", "format": "uuid"}, "contract_id": {"type": "string", "format": "uuid"}}}}}}, "responses": {"201": {"description": "Created version"}, "400": {"description": "Invalid dbt YAML or missing model"}, "401": {"description": "Missing or invalid credentials"}, "402": {"description": "Free plan cap"}, "404": {"description": "Target contract not found"}, "409": {"description": "A contract with this name already exists"}}, "security": [{"ApiKeyAuth": []}]}})); paths.insert("/contracts/{id}/versions/{version}/export/dbt".into(), json!({"get": {"operationId": "export_dbt", "summary": "Export a version as a dbt model contract", "description": "RFC-120. Writes schema.yml with config.contract.enforced, portable data_type values, not_null/unique/check constraints, and accepted_values tests. Rules dbt model contracts cannot express are stored in meta.contractgate for a lossless round-trip.", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string", "format": "uuid"}}, {"name": "version", "in": "path", "required": true, "schema": {"type": "string"}}, {"name": "model", "in": "query", "required": false, "schema": {"type": "string"}, "description": "dbt model name; defaults to the contract's name"}], "responses": {"200": {"description": "dbt schema.yml", "content": {"application/yaml": {"schema": {"type": "string"}}}}, "401": {"description": "Missing or invalid credentials"}, "404": {"description": "Contract or version not found"}}, "security": [{"ApiKeyAuth": []}]}})); paths.insert("/contracts/{id}/export".into(), json!({"post": {"operationId": "export_fork_data", "summary": "Export a forked public-catalog contract's data", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string", "format": "uuid"}}, {"name": "format", "in": "query", "required": false, "schema": {"type": "string", "enum": ["csv", "parquet"], "default": "csv"}}], "responses": {"200": {"description": "Exported data (CSV)"}, "400": {"description": "Unsupported format (parquet is not implemented yet)"}, "401": {"description": "Missing or invalid credentials"}, "404": {"description": "Contract not found"}}, "security": [{"ApiKeyAuth": []}]}})); - paths.insert("/contracts/import".into(), json!({"post": {"operationId": "import_odcs", "summary": "Import an ODCS v3.1 document as a draft version", "description": "With target_contract_id (or its alias contract_id) the document is imported as a new draft version on that contract, which must be owned by the caller. Without a target, a new contract is created, unless the caller already owns a live contract with that name (409; pass target_contract_id).", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["odcs_yaml"], "properties": {"odcs_yaml": {"type": "string"}, "name_override": {"type": ["string", "null"]}, "target_contract_id": {"type": ["string", "null"], "format": "uuid"}, "contract_id": {"type": ["string", "null"], "format": "uuid", "description": "Alias of target_contract_id"}}}}}}, "responses": {"201": {"description": "Draft version created"}, "400": {"description": "Invalid ODCS document, or target_contract_id and contract_id disagree"}, "401": {"description": "Missing or invalid credentials"}, "403": {"description": "Collaborator grant on the target (owner required)"}, "404": {"description": "Target contract not found or not owned by the caller's org"}, "409": {"description": "Version (or an equivalent, e.g. 1.0 vs 1.0.0) already exists on the target, or a live contract with this name exists and no target was given"}}, "security": [{"ApiKeyAuth": []}]}})); + paths.insert("/contracts/import".into(), json!({"post": {"operationId": "import_odcs", "summary": "Import an ODCS v3.1 document as a draft version", "description": "With target_contract_id (or its alias contract_id) the document is imported as a new draft version on that contract, which must be owned by the caller. Without a target, a new contract is created, unless the caller already owns a live contract with that name (409; pass target_contract_id).", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["odcs_yaml"], "properties": {"odcs_yaml": {"type": "string"}, "schema_object": {"type": ["string", "null"], "description": "For an ODCS document with several schema objects: the one to import, by name. The first when omitted. Unmapped content is listed in the response's notes array."}, "name_override": {"type": ["string", "null"]}, "target_contract_id": {"type": ["string", "null"], "format": "uuid"}, "contract_id": {"type": ["string", "null"], "format": "uuid", "description": "Alias of target_contract_id"}}}}}}, "responses": {"201": {"description": "Draft version created. A notes array lists ODCS content that did not map (ignored schema objects, composite key uniqueness, relationships)."}, "400": {"description": "Invalid ODCS document, schema_object not found, or target_contract_id and contract_id disagree"}, "401": {"description": "Missing or invalid credentials"}, "403": {"description": "Collaborator grant on the target (owner required)"}, "404": {"description": "Target contract not found or not owned by the caller's org"}, "409": {"description": "Version (or an equivalent, e.g. 1.0 vs 1.0.0) already exists on the target, or a live contract with this name exists and no target was given"}}, "security": [{"ApiKeyAuth": []}]}})); paths.insert("/contracts/{id}/kafka-ingress".into(), json!({"get": {"operationId": "get_kafka_ingress", "summary": "Kafka ingress config (owner)", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string", "format": "uuid"}}], "responses": {"200": {"description": "Config (no secret)"}, "401": {"description": "Missing or invalid credentials"}, "404": {"description": "Contract not found or not owned by the caller's org"}}, "security": [{"ApiKeyAuth": []}]}})); paths.insert("/contracts/{id}/kafka-ingress/enable".into(), json!({"post": {"operationId": "enable_kafka_ingress", "summary": "Enable Kafka ingress (owner, Enterprise; available on request)", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string", "format": "uuid"}}], "responses": {"200": {"description": "Already enabled"}, "201": {"description": "Enabled; secret shown once"}, "400": {"description": "Kafka ingress unavailable on this deployment (KAFKA_ENABLED=false)"}, "401": {"description": "Missing or invalid credentials"}, "404": {"description": "Contract not found or not owned by the caller's org"}, "403": {"description": "Collaborator grant (owner required), or org below Enterprise: \"Kafka/Kinesis streaming ingress requires the Enterprise plan (available on request)\""}}, "security": [{"ApiKeyAuth": []}]}})); paths.insert("/contracts/{id}/kafka-ingress/disable".into(), json!({"delete": {"operationId": "disable_kafka_ingress", "summary": "Disable Kafka ingress (owner, any plan)", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string", "format": "uuid"}}], "responses": {"204": {"description": "Disabled; credentials revoked"}, "401": {"description": "Missing or invalid credentials"}, "404": {"description": "Contract not found or not owned by the caller's org"}}, "security": [{"ApiKeyAuth": []}]}})); diff --git a/src/validation.rs b/src/validation.rs index 3f300929..c60529e9 100644 --- a/src/validation.rs +++ b/src/validation.rs @@ -1633,6 +1633,7 @@ mod tests { ontology: Ontology { entities: vec![ FieldDefinition { + distribution: None, name: "user_id".into(), field_type: FieldType::String, required: true, @@ -1648,6 +1649,7 @@ mod tests { format: None, }, FieldDefinition { + distribution: None, name: "event_type".into(), field_type: FieldType::String, required: true, @@ -1667,6 +1669,7 @@ mod tests { format: None, }, FieldDefinition { + distribution: None, name: "timestamp".into(), field_type: FieldType::Integer, required: true, @@ -1733,6 +1736,7 @@ mod tests { let mut c = make_simple_contract(); c.null_as_absent = null_as_absent; c.ontology.entities.push(FieldDefinition { + distribution: None, name: "note".into(), field_type: FieldType::String, required: false, diff --git a/tests/cli_test_dryrun.rs b/tests/cli_test_dryrun.rs index e707dc2c..1eb4a00d 100644 --- a/tests/cli_test_dryrun.rs +++ b/tests/cli_test_dryrun.rs @@ -24,6 +24,7 @@ fn args(data: &str) -> TestArgs { format: Format::Human, fail_fast: false, quiet: false, + schema_object: None, } } @@ -34,6 +35,7 @@ fn args_json(data: &str) -> TestArgs { format: Format::Json, fail_fast: false, quiet: false, + schema_object: None, } } @@ -114,6 +116,7 @@ fn bad_contract_yaml_returns_err() { format: Format::Human, fail_fast: false, quiet: false, + schema_object: None, }; // run() returns Err for load/compile failures (caller maps to exit 2). assert!(run(&bad_args).is_err(), "bad contract YAML → Err"); @@ -127,6 +130,7 @@ fn missing_data_file_returns_err() { format: Format::Human, fail_fast: false, quiet: false, + schema_object: None, }; assert!(run(&bad_args).is_err(), "missing data file → Err"); } @@ -149,6 +153,7 @@ fn fail_fast_exits_1_on_first_failing_record() { format: Format::Human, fail_fast: true, quiet: true, + schema_object: None, }; let code = run(&ff_args).expect("run"); assert_eq!(code, 1); @@ -165,6 +170,7 @@ fn quiet_mode_does_not_panic() { format: Format::Human, fail_fast: false, quiet: true, + schema_object: None, }; let code = run(&quiet_args).expect("run"); assert_eq!(code, 1); diff --git a/tests/cli_validate.rs b/tests/cli_validate.rs index 1d7e4a5d..154959e1 100644 --- a/tests/cli_validate.rs +++ b/tests/cli_validate.rs @@ -24,6 +24,7 @@ fn args_for_dir(dir: PathBuf) -> ValidateArgs { ValidateArgs { dir: Some(dir), json: false, + schema_object: None, } } @@ -31,6 +32,7 @@ fn args_for_dir_json(dir: PathBuf) -> ValidateArgs { ValidateArgs { dir: Some(dir), json: true, + schema_object: None, } } diff --git a/tests/odcs_compat.rs b/tests/odcs_compat.rs index 3da98925..e40c9912 100644 --- a/tests/odcs_compat.rs +++ b/tests/odcs_compat.rs @@ -79,8 +79,10 @@ fn official_full_example_parses_and_synths() { Some("Views built on top of the seller tables.") ); // schema[0] only; the second object is reported, not silently dropped. - assert_eq!(notes.len(), 1, "{notes:?}"); + // It also notes the relationships it does not enforce. + assert_eq!(notes.len(), 2, "{notes:?}"); assert!(notes[0].contains("receivers"), "{notes:?}"); + assert!(notes[1].contains("relationships"), "{notes:?}"); let cc = c .ontology .entities @@ -219,6 +221,7 @@ fn validate_command_accepts_odcs_directory() { let args = ValidateArgs { dir: Some(tmp.path().to_path_buf()), json: false, + schema_object: None, }; assert_eq!(run(&args, &CliConfig::default()).unwrap(), 0); } @@ -240,3 +243,16 @@ fn json_style_odcs_is_detected() { let c = parse_contract_yaml(y).expect("parses"); assert_eq!(c.ontology.entities.len(), 1); } + +#[test] +fn official_full_example_second_object_by_name() { + let (c, notes) = + contractgate::odcs::parse_contract_yaml_with(FULL, Some("receivers")).expect("parses"); + assert!(notes[0].contains("imported 'receivers'"), "{notes:?}"); + assert!(!c.ontology.entities.is_empty()); + assert!(c + .ontology + .entities + .iter() + .all(|f| f.name != "rcvr_cntry_code")); +} diff --git a/tests/odcs_schema_object.rs b/tests/odcs_schema_object.rs new file mode 100644 index 00000000..85efc030 --- /dev/null +++ b/tests/odcs_schema_object.rs @@ -0,0 +1,147 @@ +//! ODCS documents with several `schema` objects: pick one by name, and +//! surface what did not map (ignored objects, composite key, relationships). + +use contractgate::odcs::{import_odcs_with, parse_contract_yaml_with}; +use contractgate::synth::{self, SynthMode, SynthOptions}; +use contractgate::validation::validate; + +const MULTI: &str = r#" +apiVersion: v3.1.0 +kind: DataContract +version: 1.0.0 +dataProduct: shop +schema: + - name: orders + properties: + - name: order_id + logicalType: string + primaryKey: true + required: true + - name: line_no + logicalType: integer + primaryKey: true + required: true + - name: customer_id + logicalType: string + relationships: + - to: customers.customer_id + - name: customers + physicalName: tbl_customers + properties: + - name: customer_id + logicalType: string + required: true + - name: age + logicalType: integer + logicalTypeOptions: + minimum: 18 + maximum: 99 +"#; + +fn field_names(yaml: &str, obj: Option<&str>) -> Vec { + let (c, _) = parse_contract_yaml_with(yaml, obj).expect("parses"); + c.ontology.entities.into_iter().map(|f| f.name).collect() +} + +#[test] +fn default_is_first_object_and_note_names_the_rest_and_the_flag() { + assert_eq!( + field_names(MULTI, None), + ["order_id", "line_no", "customer_id"] + ); + let r = import_odcs_with(MULTI, None).unwrap(); + let n = r + .warnings + .iter() + .find(|w| w.contains("objects")) + .expect("multi-object note"); + assert!(n.contains("imported 'orders'"), "{n}"); + assert!(n.contains("customers"), "{n}"); + assert!(n.contains("schema_object"), "{n}"); +} + +#[test] +fn schema_object_selects_by_name_physical_name_and_id() { + assert_eq!( + field_names(MULTI, Some("customers")), + ["customer_id", "age"] + ); + assert_eq!( + field_names(MULTI, Some("tbl_customers")), + ["customer_id", "age"] + ); + let r = import_odcs_with(MULTI, Some("customers")).unwrap(); + let n = r.warnings.iter().find(|w| w.contains("objects")).unwrap(); + assert!(n.contains("imported 'customers' (schema[1])"), "{n}"); + assert!(n.contains("ignored: orders"), "{n}"); +} + +#[test] +fn unknown_schema_object_lists_the_available_names() { + let Err(e) = import_odcs_with(MULTI, Some("nope")) else { + panic!("expected error") + }; + assert!(e.contains("'nope' not found"), "{e}"); + assert!(e.contains("orders, customers"), "{e}"); +} + +#[test] +fn composite_key_and_relationships_are_noted_not_enforced() { + let r = import_odcs_with(MULTI, None).unwrap(); + assert!( + r.warnings + .iter() + .any(|w| w.contains("composite primary key (order_id, line_no)")), + "{:?}", + r.warnings + ); + assert!( + r.warnings.iter().any(|w| w.contains("relationships")), + "{:?}", + r.warnings + ); + // The second object has neither. + let r2 = import_odcs_with(MULTI, Some("customers")).unwrap(); + assert!(!r2.warnings.iter().any(|w| w.contains("composite"))); + assert!(!r2.warnings.iter().any(|w| w.contains("relationships"))); +} + +#[test] +fn single_column_key_gets_no_composite_note() { + let y = "apiVersion: v3.1.0\nkind: DataContract\nversion: 1.0.0\nschema:\n - name: t\n properties:\n - name: id\n logicalType: string\n primaryKey: true\n"; + let r = import_odcs_with(y, None).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); +} + +#[test] +fn selected_object_synths_valid_rows() { + let (c, _) = parse_contract_yaml_with(MULTI, Some("customers")).unwrap(); + let compiled = contractgate::validation::CompiledContract::compile(c).unwrap(); + let out = synth::generate( + &compiled, + &SynthOptions { + rows: 50, + mode: SynthMode::Valid, + seed: 1, + now_unix: 1_780_000_000, + }, + ) + .unwrap(); + let mut seen = 0; + for row in &out.rows { + assert!(validate(&compiled, row).passed, "{row}"); + if let Some(age) = row.get("age").and_then(|v| v.as_i64()) { + assert!((18..=99).contains(&age)); + seen += 1; + } + } + assert!(seen > 0, "optional field never generated"); +} + +#[test] +fn schema_object_is_ignored_for_native_yaml() { + let y = "version: \"1\"\nname: t\nontology:\n entities:\n - name: id\n type: string\n"; + let (c, notes) = parse_contract_yaml_with(y, Some("whatever")).unwrap(); + assert_eq!(c.name, "t"); + assert!(notes.is_empty()); +} diff --git a/tests/scaffold_property.rs b/tests/scaffold_property.rs index 43f60eef..ad0f3149 100644 --- a/tests/scaffold_property.rs +++ b/tests/scaffold_property.rs @@ -236,6 +236,7 @@ fn make_contract(fields: &[(&str, FieldType, bool)]) -> Contract { entities: fields .iter() .map(|(name, ft, required)| FieldDefinition { + distribution: None, name: name.to_string(), field_type: ft.clone(), required: *required, @@ -280,6 +281,7 @@ proptest! { let mut theirs = base.clone(); // theirs adds an extra field theirs.ontology.entities.push(FieldDefinition { + distribution: None, name: extra_field.clone(), field_type: FieldType::String, required: false, @@ -313,6 +315,7 @@ proptest! { let base = make_contract(&[("id", FieldType::String, true)]); let mut ours = base.clone(); ours.ontology.entities.push(FieldDefinition { + distribution: None, name: extra_field.clone(), field_type: FieldType::Integer, required: true, @@ -347,6 +350,7 @@ proptest! { let ours = make_contract(&[("a", FieldType::String, true)]); let mut theirs = make_contract(&[("a", FieldType::String, true)]); theirs.ontology.entities.push(FieldDefinition { + distribution: None, name: extra.clone(), field_type: FieldType::String, required: false, diff --git a/tests/synth_distribution.rs b/tests/synth_distribution.rs new file mode 100644 index 00000000..c9fab1f6 --- /dev/null +++ b/tests/synth_distribution.rs @@ -0,0 +1,254 @@ +//! Per-field `distribution` hint for `synth` (integer and number fields). + +use contractgate::contract::{Contract, Distribution}; +use contractgate::odcs::{normalize_contract_yaml, parse_contract_yaml}; +use contractgate::synth::{self, SynthMode, SynthOptions}; +use contractgate::validation::validate; +use serde_json::Value; + +const ROWS: usize = 5000; + +fn contract(field_yaml: &str) -> String { + format!("version: '1.0'\nname: dist\nontology:\n entities:\n - name: x\n type: number\n{field_yaml}") +} + +fn opts(rows: usize, seed: u64) -> SynthOptions { + SynthOptions { + rows, + mode: SynthMode::Valid, + seed, + now_unix: 1_780_000_000, + } +} + +fn draw(yaml: &str, rows: usize, seed: u64) -> Vec { + let compiled = synth::compile_yaml(yaml).expect("compiles"); + let out = synth::generate(&compiled, &opts(rows, seed)).expect("generates"); + out.rows + .iter() + .map(|r| r["x"].as_f64().expect("numeric x")) + .collect() +} + +fn mean_sd(v: &[f64]) -> (f64, f64) { + let n = v.len() as f64; + let m = v.iter().sum::() / n; + let var = v.iter().map(|x| (x - m).powi(2)).sum::() / (n - 1.0); + (m, var.sqrt()) +} + +#[test] +fn normal_matches_mean_and_sd() { + let y = contract( + " min: 0\n max: 200\n distribution: {type: normal, mean: 100, sd: 15}\n", + ); + let v = draw(&y, ROWS, 11); + let (m, sd) = mean_sd(&v); + assert!((m - 100.0).abs() < 0.8, "mean {m}"); + assert!((sd - 15.0).abs() < 0.8, "sd {sd}"); + assert!(v.iter().all(|x| (0.0..=200.0).contains(x))); +} + +#[test] +fn normal_on_integers_stays_integer() { + let y = "version: '1.0'\nname: d\nontology:\n entities:\n - name: x\n type: integer\n distribution: {type: normal, mean: 1000, sd: 50}\n"; + let compiled = synth::compile_yaml(y).unwrap(); + let out = synth::generate(&compiled, &opts(ROWS, 3)).unwrap(); + let v: Vec = out + .rows + .iter() + .map(|r| { + assert!(r["x"].is_i64(), "{}", r["x"]); + r["x"].as_f64().unwrap() + }) + .collect(); + let (m, sd) = mean_sd(&v); + assert!((m - 1000.0).abs() < 3.0, "mean {m}"); + assert!((sd - 50.0).abs() < 3.0, "sd {sd}"); +} + +#[test] +fn lognormal_parameters_describe_the_underlying_normal() { + let y = contract(" distribution: {type: lognormal, mean: 3, sd: 0.5}\n"); + let v = draw(&y, ROWS, 5); + assert!(v.iter().all(|x| *x > 0.0)); + let logs: Vec = v.iter().map(|x| x.ln()).collect(); + let (m, sd) = mean_sd(&logs); + assert!((m - 3.0).abs() < 0.05, "log mean {m}"); + assert!((sd - 0.5).abs() < 0.05, "log sd {sd}"); + // Right-skewed: the mean sits above the median. + let mut sorted = v.clone(); + sorted.sort_by(|a, b| a.partial_cmp(b).unwrap()); + assert!(mean_sd(&v).0 > sorted[ROWS / 2]); +} + +#[test] +fn exponential_has_mean_one_over_rate_above_min() { + let y = contract(" min: 5\n distribution: {type: exponential, rate: 0.1}\n"); + let v = draw(&y, ROWS, 9); + assert!(v.iter().all(|x| *x >= 5.0)); + let (m, _) = mean_sd(&v); + assert!((m - 15.0).abs() < 0.7, "mean {m}"); +} + +#[test] +fn bounds_truncate_by_redrawing() { + let y = contract( + " min: 45\n max: 55\n distribution: {type: normal, mean: 50, sd: 5}\n", + ); + let v = draw(&y, ROWS, 2); + assert!(v.iter().all(|x| (45.0..=55.0).contains(x))); + // Truncated bell, not flat: the middle 4 units hold far more than the outer 2. + let mid = v.iter().filter(|x| **x >= 48.0 && **x <= 52.0).count(); + let edge = v.iter().filter(|x| **x < 46.0 || **x > 54.0).count(); + assert!(mid > 2 * edge, "mid {mid} edge {edge}"); +} + +#[test] +fn deterministic_per_seed() { + let y = contract(" distribution: {type: normal, mean: 0, sd: 1}\n"); + assert_eq!(draw(&y, 200, 42), draw(&y, 200, 42)); + assert_ne!(draw(&y, 200, 42), draw(&y, 200, 43)); +} + +#[test] +fn uniform_hint_leaves_output_unchanged() { + let base = contract(" min: 1\n max: 9\n"); + let hinted = contract(" min: 1\n max: 9\n distribution: uniform\n"); + assert_eq!(draw(&base, 300, 8), draw(&hinted, 300, 8)); +} + +#[test] +fn rows_pass_the_validator_and_the_hint_is_ignored_by_it() { + let y = contract( + " min: 0\n max: 10\n distribution: {type: normal, mean: 5, sd: 2}\n", + ); + let compiled = synth::compile_yaml(&y).unwrap(); + let out = synth::generate(&compiled, &opts(500, 1)).unwrap(); + for r in &out.rows { + assert!(validate(&compiled, r).passed); + } + // The validator takes the same events with or without the hint. + let plain = synth::compile_yaml(&contract(" min: 0\n max: 10\n")).unwrap(); + for ev in [ + serde_json::json!({"x": 5.0}), + serde_json::json!({"x": 11}), + serde_json::json!({"x": -1}), + ] { + assert_eq!( + validate(&compiled, &ev).passed, + validate(&plain, &ev).passed + ); + } +} + +#[test] +fn contracts_without_a_hint_serialize_without_one() { + let c: Contract = serde_yaml::from_str(&contract(" min: 0\n")).unwrap(); + assert!(c.ontology.entities[0].distribution.is_none()); + assert!(!serde_yaml::to_string(&c).unwrap().contains("distribution")); +} + +#[test] +fn invalid_hints_get_clear_errors() { + let err = |field: &str| { + serde_yaml::from_str::(&contract(field)) + .unwrap_err() + .to_string() + }; + assert!( + err(" distribution: {type: normal, mean: 1, sd: 0}\n").contains("sd greater than 0") + ); + assert!(err(" distribution: {type: normal, mean: 1}\n").contains("needs a numeric `sd`")); + assert!( + err(" distribution: {type: exponential, rate: -1}\n").contains("rate greater than 0") + ); + assert!(err(" distribution: {type: weibull}\n").contains("unknown distribution type")); + assert!( + err(" distribution: {type: normal, mean: 1, sd: 1, rate: 2}\n") + .contains("does not take `rate`") + ); + assert!(err(" distribution: 7\n").contains("distribution must be")); +} + +#[test] +fn synth_errors_name_the_field() { + let on_string = "version: '1.0'\nname: d\nontology:\n entities:\n - name: s\n type: string\n distribution: {type: normal, mean: 1, sd: 1}\n"; + let c = synth::compile_yaml(on_string).unwrap(); + let e = synth::generate(&c, &opts(2, 1)).unwrap_err(); + assert_eq!(e.rule, "distribution"); + assert!( + e.message.contains("field 's'") && e.message.contains("integer and number"), + "{}", + e.message + ); + + let y = contract(" max: 10\n distribution: {type: normal, mean: 1000, sd: 1}\n"); + let c = synth::compile_yaml(&y).unwrap(); + let e = synth::generate(&c, &opts(2, 1)).unwrap_err(); + assert_eq!(e.rule, "distribution"); + assert!(e.message.contains("almost no values"), "{}", e.message); +} + +#[test] +fn enum_wins_over_the_hint() { + let y = + contract(" enum: [1, 2, 3]\n distribution: {type: normal, mean: 100, sd: 1}\n"); + assert!(draw(&y, 100, 1).iter().all(|x| [1.0, 2.0, 3.0].contains(x))); +} + +const ODCS: &str = r#" +apiVersion: v3.1.0 +kind: DataContract +version: 1.0.0 +name: odcs_dist +schema: + - name: t + properties: + - name: x + logicalType: number + required: true + customProperties: + - property: x-cg-distribution + value: {type: normal, mean: 50, sd: 5} +"#; + +#[test] +fn odcs_custom_property_sets_the_hint_and_round_trips() { + let c = parse_contract_yaml(ODCS).unwrap(); + assert_eq!( + c.ontology.entities[0].distribution, + Some(Distribution::Normal { + mean: 50.0, + sd: 5.0 + }) + ); + let v = draw(ODCS, ROWS, 4); + let (m, sd) = mean_sd(&v); + assert!((m - 50.0).abs() < 0.5 && (sd - 5.0).abs() < 0.4, "{m} {sd}"); + // Serialized native YAML keeps it. + let (native, _) = normalize_contract_yaml(ODCS).unwrap(); + assert!(native.contains("distribution")); + let again: Contract = serde_yaml::from_str(&native).unwrap(); + assert_eq!( + again.ontology.entities[0].distribution, + c.ontology.entities[0].distribution + ); +} + +#[test] +fn odcs_bad_hint_is_an_error() { + let bad = ODCS.replace("sd: 5", "sd: -5"); + let e = parse_contract_yaml(&bad).unwrap_err(); + assert!( + e.contains("property 'x'") && e.contains("sd greater than 0"), + "{e}" + ); +} + +#[test] +fn json_value_form_parses() { + let v: Value = serde_json::json!({"type": "lognormal", "mean": 1.0, "sd": 0.2}); + let d: Distribution = serde_json::from_value(v).unwrap(); + assert_eq!(d, Distribution::Lognormal { mean: 1.0, sd: 0.2 }); +}