"""Illustrative salon AST checker, not a production schema or a risk estimator. Run: python validate-example.py Only Python's standard library is used. No eval/exec, persistence or actions. """ import copy import json import math from datetime import date, datetime from pathlib import Path # Dimensions are (money, service count, time). UNITS = {"1": (0, 0, 0), "service/month": (0, 1, -1), "CU/service": (1, -1, 0), "CU/month": (1, 0, -1)} INPUT_UNITS = {"slots": "service/month", "bookings": "service/month", "show_rate": "1", "price": "CU/service", "variable_cost": "CU/service", "fixed_cost": "CU/month"} def require(condition, message): if not condition: raise ValueError(message) def number(value): require(type(value) in (int, float) and math.isfinite(value), "Values must be finite numbers; booleans are not numbers") return value def validate(doc): require(doc["schemaVersion"] == "0.1.0-proposal", "Unsupported schemaVersion") require(doc["status"] == "illustrative_proposal" and doc["productionReady"] is False, "This example must remain marked as an illustrative proposal") require(doc["immutability"]["status"] == "proposed_only", "Immutability is proposed, not implemented") context, decision, model, run, trigger = ( doc[k] for k in ("context", "decision", "model", "run", "trigger")) require(context["orientation"] == "exploratory", "Expected exploratory context") require(context["probability"] is None, "Unknown context probability must remain null") require(run["computedRiskProbability"] is None and run["actualRiskProbability"] is None, "Unknown risk probabilities must remain null, not zero") require(run["probabilityStatus"] == "not_computed" and run["seed"] is None, "This deterministic example does not compute risk probability") require(run["contextId"] == context["id"] and run["decisionId"] == decision["id"], "Run context/decision references do not match") require(run["modelVersion"] == model["version"], "Run modelVersion does not match") require(model["timeStep"] == "month" and model["units"] == { "money": "CU", "quantity": "service", "time": "month"}, "Model units do not match") decided_at = datetime.fromisoformat(decision["decidedAt"].replace("Z", "+00:00")) require(decided_at.tzinfo is not None, "decidedAt must include a timezone") require(date.fromisoformat(model["asOf"]) <= decided_at.date(), "Model is available after decision") require(decision["action"] == "keep_schedule" and decision["owner"], "Invalid decision") assumptions = doc["assumptions"] inputs = {a["id"]: a for a in assumptions} require(len(inputs) == len(assumptions), "Duplicate assumption IDs") require(set(inputs) == set(INPUT_UNITS), "Unexpected or missing assumption IDs") require(len(run["assumptionIds"]) == len(set(run["assumptionIds"])) and set(run["assumptionIds"]) == set(inputs), "Run assumption references do not match") for key, item in inputs.items(): require(item["unit"] == INPUT_UNITS[key], "Input unit mismatch: " + key) require(item["kind"] == "scenario_value" and item["source"] == "illustrative" and item["owner"], "Invalid assumption provenance: " + key) as_of, review_at = date.fromisoformat(item["asOf"]), date.fromisoformat(item["reviewAt"]) require(as_of <= decided_at.date() and review_at >= as_of, "Invalid assumption dates") require(number(item["value"]) >= 0, "Negative assumption: " + key) require(inputs["show_rate"]["value"] <= 1, "show_rate must be between 0 and 1") require(all(float(inputs[k]["value"]).is_integer() for k in ("slots", "bookings")), "Slots and bookings must be integer counts in this example") require(inputs["price"]["value"] > inputs["variable_cost"]["value"], "A finite positive break-even requires positive contribution per service") formulas, cache, active = model["formulas"], {}, set() require(set(formulas) == {"completed_expected", "profit", "break_even"}, "Unexpected formula IDs") def reference(key): if key in inputs: return inputs[key]["value"], UNITS[inputs[key]["unit"]] require(key in formulas, "Unknown reference: " + key) require(key not in active, "Cyclic formula: " + key) if key not in cache: active.add(key) cache[key] = evaluate(formulas[key]) active.remove(key) return cache[key] def evaluate(node): require(isinstance(node, dict), "AST node must be an object") if set(node) == {"ref"}: require(isinstance(node["ref"], str), "Reference must be a string") return reference(node["ref"]) if set(node) == {"const", "unit"}: require(node["unit"] in UNITS, "Unknown constant unit") return number(node["const"]), UNITS[node["unit"]] require(set(node) == {"op", "args"} and node["op"] in ("min", "mul", "sub", "div") and isinstance(node["args"], list) and len(node["args"]) == 2, "Unsupported AST operation or shape") (a, ua), (b, ub) = (evaluate(arg) for arg in node["args"]) op = node["op"] if op in ("min", "sub"): require(ua == ub, "Expression unit mismatch") value, unit = (min(a, b) if op == "min" else a - b), ua elif op == "mul": value, unit = a * b, tuple(x + y for x, y in zip(ua, ub)) else: require(b != 0, "Division by zero") value, unit = a / b, tuple(x - y for x, y in zip(ua, ub)) return number(value), unit require(set(run["outputs"]) == set(formulas), "Output IDs do not match formulas") computed = {} for key in formulas: value, unit = reference(key) output = run["outputs"][key] require(output["unit"] in UNITS and unit == UNITS[output["unit"]], "Output unit mismatch: " + key) require(math.isclose(value, number(output["value"]), rel_tol=1e-12, abs_tol=1e-9), "Output mismatch: " + key) computed[key] = value require(0 <= computed["completed_expected"] <= inputs["slots"]["value"], "Completed services exceed capacity") require(trigger["metric"] in run["outputs"] and trigger["operator"] == "lt" and trigger["unit"] == run["outputs"][trigger["metric"]]["unit"], "Trigger metric, operator or unit mismatch") require(number(trigger["threshold"]) >= 0 and trigger["window"] == "month" and type(trigger["persistence"]) is int and trigger["persistence"] >= 1 and trigger["owner"] and trigger["action"] == "review_waitlist" and trigger["status"] == "proposed", "Invalid trigger") # No trigger is fired: persistence needs a history of distinct monthly windows. return computed def main(): doc = json.loads(Path(__file__).with_name("scenario-model-example.json").read_text(encoding="utf-8")) result = validate(doc) require(result == {"completed_expected": 468, "profit": 1360, "break_even": 400}, "Unexpected result for the published illustration") print("PASS: completed_expected=468, profit=1360, break_even=400; risk probabilities=null") # Each case alters one property and must fail for its intended reason. cases = [ ("unknown reference", ("model", "formulas", "profit", "args", 1, "ref"), "missing", "Unknown reference"), ("wrong unit", ("assumptions", 3, "unit"), "service/month", "Input unit mismatch"), ("impossible show rate", ("assumptions", 2, "value"), 1.1, "show_rate"), ("stale model version", ("run", "modelVersion"), "2.0.0", "modelVersion"), ("stale output", ("run", "outputs", "profit", "value"), 999, "Output mismatch"), ("unknown context became zero", ("context", "probability"), 0, "probability must remain null"), ("unknown computed risk became zero", ("run", "computedRiskProbability"), 0, "risk probabilities must remain null"), ("unsupported code operation", ("model", "formulas", "profit", "op"), "eval", "Unsupported AST") ] for name, path, replacement, expected_message in cases: changed = copy.deepcopy(doc) target = changed for component in path[:-1]: target = target[component] target[path[-1]] = replacement try: validate(changed) except ValueError as error: require(expected_message in str(error), "Wrong failure for " + name + ": " + str(error)) print("PASS negative: " + name) else: raise AssertionError("Expected rejection: " + name) print("Illustration only: no immutable archive, probability estimation or trigger execution.") if __name__ == "__main__": main()