"""Seeded case sampler: workflow spec -> concrete decision states. Every field is sampled in spec order so parents (``depends`` / ``when`` / ``bank_by`` / ``{@path}`` references) are always available. Fields with dotted paths become nested objects. Cases are deduplicated by ``schema.content_hash`` of the state. Deterministic for a given (spec, seed): the RNG is seeded from sha256(global_seed, workflow_id). """ from __future__ import annotations import datetime as dt import hashlib import math import random import re from typing import Any from ..schema import content_hash SAMPLER_VERSION = "typed-synth-sampler-v2" DEFAULT_REFERENCE_DATE = "2026-09-01" _MISSING = object() class SamplingError(ValueError): pass def workflow_seed(workflow_id: str, global_seed: int = 13) -> int: return int(hashlib.sha256(f"{global_seed}:{workflow_id}".encode()).hexdigest()[:12], 16) def _key(value: Any) -> str: if isinstance(value, bool): return "true" if value else "false" return str(value) def _set_path(obj: dict, path: str, value: Any) -> None: parts = path.split(".") for p in parts[:-1]: obj = obj.setdefault(p, {}) obj[parts[-1]] = value def _weighted(rng: random.Random, values: list, weights: list | None) -> Any: if not weights: return rng.choice(values) return rng.choices(values, weights=weights, k=1)[0] def _fill(text: str, rng: random.Random, slots: dict, ctx: dict) -> str: def at(m: re.Match) -> str: v = ctx.get(m.group(1), "") return "" if v is None or v is _MISSING else _key(v) text = re.sub(r"\{@([^{}\s]+)\}", at, text) def slot(m: re.Match) -> str: vals = slots.get(m.group(1)) return _key(rng.choice(vals)) if vals else m.group(0) return re.sub(r"\{([A-Za-z_][A-Za-z0-9_]*)\}", slot, text) def _numeric(f: dict, rng: random.Random, ctx: dict) -> float | int: dist = f.get("dist", "uniform") if dist == "uniform": x = rng.uniform(f["min"], f["max"]) if f["type"] == "number" else rng.randint(int(f["min"]), int(f["max"])) elif dist == "normal": x = rng.gauss(f["mean"], f["sd"]) elif dist == "lognormal": x = math.exp(rng.gauss(f["mean"], f["sigma"])) else: x = _weighted(rng, f["values"], f.get("weights")) dep = f.get("depends") if dep: pv = _key(ctx.get(dep["field"])) x = x * float(dep.get("scale", {}).get(pv, 1.0)) + float(dep.get("shift", {}).get(pv, 0.0)) if f.get("min") is not None: x = max(x, f["min"]) if f.get("max") is not None: x = min(x, f["max"]) if f["type"] == "integer": return int(round(x)) return round(float(x), int(f.get("decimals", 2))) def _sample_field(f: dict, rng: random.Random, ctx: dict, ref_date: dt.date) -> Any: when = f.get("when") if when is not None: if _key(ctx.get(when["field"], _MISSING)) not in {_key(v) for v in when["in"]}: return _MISSING if f.get("missing_prob", 0) and rng.random() < f["missing_prob"]: return None t = f["type"] dep = f.get("depends") if t == "categorical": weights = f.get("weights") if dep: weights = dep["weights"].get(_key(ctx.get(dep["field"])), weights) return _weighted(rng, f["values"], weights) if t == "boolean": p = f.get("p_true", 0.5) if dep: p = dep["p_true"].get(_key(ctx.get(dep["field"])), p) return rng.random() < p if t in ("integer", "number"): return _numeric(f, rng, ctx) if t == "text": bank = f.get("bank") by = f.get("bank_by") if by: bank = by["banks"].get(_key(ctx.get(by["field"], _MISSING)), by.get("default") or bank) if not bank: # parent missing/null (missing_prob or when) and no default/bank: the text is unknown return None return _fill(rng.choice(bank), rng, f.get("slots") or {}, ctx) if t == "date": lo, hi = f["offset_days"] off = rng.randint(lo, hi) if dep: off += int(dep.get("shift", {}).get(_key(ctx.get(dep["field"])), 0)) return (ref_date + dt.timedelta(days=off)).isoformat() if t == "id": return "".join(str(rng.randint(0, 9)) if ch == "#" else chr(rng.randint(65, 90)) if ch == "@" else ch for ch in f["pattern"]) if t == "list": n = rng.randint(f.get("min_items", 1), f.get("max_items", 3)) if f.get("item_bank") is not None: picks = rng.sample(f["item_bank"], k=min(n, len(f["item_bank"]))) return [_fill(s, rng, f.get("slots") or {}, ctx) for s in picks] out = [] for _ in range(n): local = dict(ctx) item: dict = {} for sub in f["items"]: v = _sample_field(sub, rng, local, ref_date) local[sub["path"]] = v # hidden item fields are latent (usable as parents) and never shown, like top-level ones if v is not _MISSING and not sub.get("hidden"): _set_path(item, sub["path"], v) out.append(item) return out raise SamplingError(f"unknown field type {t!r}") def sample_state(spec: dict, rng: random.Random) -> dict: ref = dt.date.fromisoformat(spec.get("reference_date") or DEFAULT_REFERENCE_DATE) ctx: dict[str, Any] = {} state: dict = {} for f in spec["state_schema"]["fields"]: v = _sample_field(f, rng, ctx, ref) ctx[f["path"]] = v if v is not _MISSING and not f.get("hidden"): _set_path(state, f["path"], v) return state def sample_cases(spec: dict, n: int = 60, global_seed: int = 13, max_tries_factor: int = 30) -> list[dict]: """``n`` distinct cases (fewer only if the spec cannot produce that many distinct states).""" wid = spec["workflow_id"] seed = workflow_seed(wid, global_seed) rng = random.Random(seed) cases, seen = [], set() tries = 0 while len(cases) < n and tries < n * max_tries_factor: tries += 1 state = sample_state(spec, rng) h = content_hash(state) if h in seen: continue seen.add(h) cases.append({"case_id": f"{wid}-{len(cases):03d}", "workflow_id": wid, "state": state, "state_hash": h, "sampler": {"version": SAMPLER_VERSION, "global_seed": global_seed, "workflow_seed": seed, "draw": tries - 1}}) return cases