From 3642224a0c7cc7e6a5ef85a964c03e0e01a463e8 Mon Sep 17 00:00:00 2001 From: ContractGate Lead Date: Thu, 26 Nov 2026 10:54:02 -0500 Subject: [PATCH] feat: synth distribution hints for numeric fields (normal, lognormal, exponential) Optional per-field distribution on integer and number fields. Uniform stays the default and the rows are unchanged without a hint. Draws outside min/max are redrawn. Validation ignores the hint. ODCS: x-cg-distribution customProperty (import and export). Python SDK reads and checks the hint. Docs and tests. --- docs/odcs/strict-odcs.md | 1 + docs/odcs/using-odcs-directly.md | 12 ++ docs/synthetic-data-reference.md | 40 ++++ sdks/python/src/contractgate/contract.py | 53 +++++ sdks/python/tests/test_odcs_input.py | 30 +++ src/batch_rules.rs | 1 + src/conformance.rs | 2 + src/contract.rs | 122 +++++++++++ src/dbt_yaml.rs | 1 + src/egress.rs | 1 + src/infer.rs | 1 + src/infer_avro.rs | 2 + src/infer_diff.rs | 1 + src/infer_openapi.rs | 3 + src/infer_proto.rs | 2 + src/odcs.rs | 20 +- src/scaffold/merge.rs | 1 + src/synth.rs | 116 ++++++++++- src/tests.rs | 3 + src/transform.rs | 1 + src/validation.rs | 4 + tests/scaffold_property.rs | 4 + tests/synth_distribution.rs | 254 +++++++++++++++++++++++ 23 files changed, 672 insertions(+), 3 deletions(-) create mode 100644 tests/synth_distribution.rs 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..5157ebe1 100644 --- a/docs/odcs/using-odcs-directly.md +++ b/docs/odcs/using-odcs-directly.md @@ -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 diff --git a/docs/synthetic-data-reference.md b/docs/synthetic-data-reference.md index d0164d21..02accf4f 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. 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/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/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..66173ceb 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. 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/odcs.rs b/src/odcs.rs index 08518e13..d1447a6a 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", @@ -1068,6 +1073,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 +1261,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 +1291,7 @@ fn odcs_prop_to_field(m: &Mapping, full_name: &str) -> Result 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..a20b4596 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)] @@ -1413,6 +1415,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 +1468,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 +2123,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/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/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/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 }); +}