Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/odcs/field-mapping.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |

Expand Down
1 change: 1 addition & 0 deletions docs/odcs/strict-odcs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
44 changes: 41 additions & 3 deletions docs/odcs/using-odcs-directly.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down
43 changes: 42 additions & 1 deletion docs/synthetic-data-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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).
53 changes: 53 additions & 0 deletions sdks/python/src/contractgate/contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down Expand Up @@ -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
# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -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]
Expand Down
30 changes: 30 additions & 0 deletions sdks/python/tests/test_odcs_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}
12 changes: 12 additions & 0 deletions sdks/typescript/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions sdks/typescript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions sdks/typescript/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion sdks/typescript/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
2 changes: 1 addition & 1 deletion sdks/typescript/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`;

// ---------------------------------------------------------------------------
Expand Down
Loading
Loading