File size: 5,317 Bytes
7e5adcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
"""Run the Blueprint through the Misata Studio engine and keep what the engine says about its own output."""
from __future__ import annotations

import json
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any

import pandas as pd

from . import blueprint as B


@dataclass
class EngineRun:
    tables: dict[str, pd.DataFrame]
    design: dict[str, Any]
    report: dict[str, Any]
    clickhouse_ddl: str = ""


DELIVERED = ("stores", "products", "customers", "orders", "order_lines", "returns")


def engine_clickhouse_ddl(bp: Any, tables: dict[str, pd.DataFrame]) -> str:
    """The DDL the engine's own ClickHouse export writes for these tables, kept to compare with clickhouse/ddl.sql."""
    import tempfile

    from misata_engine.export import ParquetSource, sql_ddl

    with tempfile.TemporaryDirectory() as tmp:
        for name in DELIVERED:
            (Path(tmp) / name).mkdir()
            tables[name][[c for c in tables[name].columns if not c.startswith("_")]].to_parquet(Path(tmp) / name / "part-0.parquet")
        return sql_ddl(bp, ParquetSource(tmp), "clickhouse")


def _plain(x: Any) -> Any:
    """A certificate or finding as JSON: numpy numbers, timestamps and sets made ordinary."""
    return json.loads(json.dumps(x, default=lambda o: o.item() if hasattr(o, "item") else str(o)))


def engine_commit() -> str:
    """The Misata Studio commit the engine came from (git, or MISATA_ENGINE_COMMIT for a copy of the tree), whether its
    files had changes, and a digest of its source files, which names the engine exactly either way."""
    import hashlib
    import os
    import subprocess

    import misata_engine

    here = Path(misata_engine.__file__).resolve().parent
    digest = hashlib.sha256()
    for f in sorted(here.rglob("*.py")):
        digest.update(f.relative_to(here).as_posix().encode() + b"\0" + f.read_bytes())
    files = f"source digest {digest.hexdigest()[:16]}"
    try:
        sha = subprocess.run(["git", "rev-parse", "HEAD"], cwd=here, capture_output=True, text=True, check=True).stdout.strip()
        dirty = subprocess.run(["git", "status", "--porcelain", "--", "."], cwd=here, capture_output=True, text=True, check=True).stdout.strip()
        return f"{sha}{' with uncommitted engine changes' if dirty else ''}, {files}"
    except (OSError, subprocess.CalledProcessError):
        return f"{os.environ.get('MISATA_ENGINE_COMMIT', 'commit unknown')}, {files}"


def run(seed: int, scale: float = 1.0) -> EngineRun:
    import misata_engine as me
    from misata_engine.blueprint.guide import lint, parse
    from misata_engine.oracle import scorecard

    design = B.build(scale=scale, seed=seed)
    bp, problems = parse(design)
    if bp is None:
        raise SystemExit("the Blueprint does not parse:\n  " + "\n  ".join(problems))
    started = time.time()
    res = me.run("", blueprint=bp, seed=seed)
    seconds = round(time.time() - started, 1)
    cert = res.certificate or {}
    if not res.passed or not cert.get("passed", True):
        said = [f.message for f in res.verdict.findings[:20]] + [w["text"] for w in cert.get("withdrawn_claims") or []]
        raise SystemExit("the engine did not pass the build:\n  " + "\n  ".join(said))
    tables = dict(res.tables)
    card = scorecard.score({k: v for k, v in tables.items() if k in ("customers", "products", "orders", "order_lines", "returns")})
    report = {
        "engine": "misata_engine (Misata Studio)",
        "engine_commit": engine_commit(),
        "seed": seed,
        "scale": scale,
        "seconds": seconds,
        "passed": bool(res.passed and cert.get("passed", True)),
        "lint": [str(w) for w in lint(bp)],
        "planned": list(bp.levers.get("_planned") or []),
        "notes": [str(n) for n in res.notes],
        "findings": [{"severity": str(f.severity), "message": f.message} for f in res.verdict.findings],
        "certificate": _plain(res.certificate),
        "realism_scorecard": scorecard.render(card),
        "rows": {k: len(v) for k, v in tables.items()},
    }
    return EngineRun(tables=tables, design=design, report=report, clickhouse_ddl=engine_clickhouse_ddl(bp, tables))


def score_delivered(parquet_dir: Path) -> str:
    """The engine's realism scorecard read on the delivered files, after every step that follows the engine; decimals are
    read as numbers."""
    import pyarrow as pa
    import pyarrow.parquet as pq

    from misata_engine.oracle import scorecard

    tables = {}
    for name in ("dim_product", "dim_customer", "dim_store", "orders", "order_lines", "returns"):
        t = pq.read_table(parquet_dir / f"{name}.parquet")
        cast = pa.schema([pa.field(f.name, pa.float64()) if pa.types.is_decimal(f.type) else f for f in t.schema])
        tables[name] = t.cast(cast).to_pandas()
    return scorecard.render(scorecard.score(tables))


def save_report(er: EngineRun, out: Path) -> None:
    out.mkdir(parents=True, exist_ok=True)
    (out / "blueprint.json").write_text(json.dumps(er.design, indent=1, ensure_ascii=False))
    (out / "engine_report.json").write_text(json.dumps(er.report, indent=1, ensure_ascii=False))
    (out / "realism_scorecard.txt").write_text(er.report["realism_scorecard"])
    (out / "engine_clickhouse_ddl.sql").write_text(er.clickhouse_ddl)