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
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
12 changes: 12 additions & 0 deletions docs/odcs/using-odcs-directly.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,18 @@ 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.

## What does not map

- Only `schema[0]` is read. Other schema objects are reported as a note
Expand Down
40 changes: 40 additions & 0 deletions 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
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}
1 change: 1 addition & 0 deletions src/batch_rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,7 @@ ontology:

fn field(name: &str, field_type: FieldType) -> FieldDefinition {
FieldDefinition {
distribution: None,
name: name.to_string(),
field_type,
required: false,
Expand Down
2 changes: 2 additions & 0 deletions src/conformance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,7 @@ mod tests {
ontology: Ontology {
entities: vec![
FieldDefinition {
distribution: None,
name: "user_id".into(),
field_type: FieldType::String,
required: true,
Expand All @@ -394,6 +395,7 @@ mod tests {
format: None,
},
FieldDefinition {
distribution: None,
name: "amount".into(),
field_type: FieldType::Float,
required: false,
Expand Down
122 changes: 122 additions & 0 deletions src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
/// 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<Distribution>,
}

/// 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<Self, String> {
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<f64, String> {
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: D) -> Result<Self, D::Error>
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.
Expand Down
1 change: 1 addition & 0 deletions src/dbt_yaml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -637,6 +637,7 @@ fn import_column(
}

Ok(FieldDefinition {
distribution: None,
name,
field_type,
required,
Expand Down
1 change: 1 addition & 0 deletions src/egress.rs
Original file line number Diff line number Diff line change
Expand Up @@ -789,6 +789,7 @@ mod tests {

fn bare_field(name: &str) -> FieldDefinition {
FieldDefinition {
distribution: None,
name: name.into(),
field_type: FieldType::String,
required: true,
Expand Down
1 change: 1 addition & 0 deletions src/infer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions src/infer_avro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ fn avro_field_to_definition(field: &Value) -> Result<FieldDefinition, String> {
let (field_type, required, allowed_values, properties, items) = resolve_avro_type(type_val)?;

Ok(FieldDefinition {
distribution: None,
name,
field_type,
required,
Expand Down Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions src/infer_diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading