File size: 6,769 Bytes
5ce8adf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#!/usr/bin/env python3
"""Check data/ against the closebench package.

    python verify.py [--src /path/to/checkout] [--n 5] [--sample-seed 0]

On every row: row counts, seed sets, mode-by-seed, world/truth pairing.
For N random seeds (default 5), in both locales:
  1. rebuild the world from the package and compare the serialised record with the
     stored line byte for byte (worlds and truth files);
  2. "oracle": post the fixes from the stored truth row as adjusting entries on
     (a) the rebuilt world and (b) a world reconstructed purely from the JSONL rows
     (the README recipe) -- grade() must return passed=True, score=1.0 in both;
  3. en and ru rows carry identical numbers (dates, accounts, amounts, fixes).
Exit status 1 if anything fails.
"""
from __future__ import annotations
import argparse, json, os, random, sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from build import SEEDS, LANGS, DATA, mode_for, import_closebench, world_record, truth_record, dumps  # noqa: E402

FAILS = 0


def check(cond: bool, msg: str) -> bool:
    global FAILS
    print(("  ok    " if cond else "  FAIL  ") + msg)
    if not cond:
        FAILS += 1
    return cond


def read_jsonl(path: str) -> list[tuple[bytes, dict]]:
    """(raw line without newline, parsed object) per row."""
    with open(path, "rb") as f:
        return [(ln.rstrip(b"\n"), json.loads(ln)) for ln in f if ln.strip()]


def world_from_rows(wrow: dict, trow: dict | None = None):
    """Rebuild a gradeable World from dataset rows alone (no .build(), no seed replay)."""
    from closebench.world import World, Document, PlantedError
    from closebench.ledger import Entry, Line, D
    world = World(seed=wrow["seed"], lang=wrow["lang"], difficulty=wrow["mode"])
    world.name = wrow["company"]
    world.period_start, world.period_end = wrow["period"]["start"], wrow["period"]["end"]
    for e in wrow["entries"]:
        world.ledger.post(Entry(e["eid"], e["date"], e["memo"],
                                [Line(l["account"], D(l["debit"]), D(l["credit"])) for l in e["lines"]],
                                e["source"], e["ref"]))
    world.ledger._seq = len(wrow["entries"])
    world.documents = [Document(**d) for d in wrow["documents"]]
    if trow is not None:
        world.errors = [PlantedError(**err) for err in trow["errors"]]
    return world


def oracle(world, trow: dict) -> dict:
    """Post exactly the fix for every planted error, then grade."""
    from closebench.tools import Session
    from closebench.grader import grade
    s = Session(world)
    for err in trow["errors"]:
        fix = err["fix"]
        s.post_entry(fix["period"][1], err["err_id"], [
            {"account": fix["debit_account"], "debit": fix["amount"]},
            {"account": fix["credit_account"], "credit": fix["amount"]},
        ])
    return grade(world, s)


def numbers(wrow: dict, trow: dict):
    """Everything about a world except its text."""
    return ([(e["eid"], e["date"], e["source"], e["ref"], e["lines"]) for e in wrow["entries"]],
            [(d["doc_id"], d["kind"], d["date"]) for d in wrow["documents"]],
            [(x["err_id"], x["kind"], x["entry_ids"], x["accounts"], x["amount"], x["fix"]) for x in trow["errors"]])


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--src", help="closebench source checkout to import from (if not pip-installed)")
    ap.add_argument("--data", default=DATA)
    ap.add_argument("--n", type=int, default=5, help="how many random seeds to rebuild (default 5)")
    ap.add_argument("--sample-seed", type=int, help="fix the random choice of seeds")
    a = ap.parse_args()
    World, version = import_closebench(a.src)
    print(f"closebench {version}; data={a.data}")

    files = {}
    for lang in LANGS:
        for kind in ("worlds", "truth"):
            p = os.path.join(a.data, f"{kind}-{lang}.jsonl")
            files[kind, lang] = read_jsonl(p)

    print("structure")
    for (kind, lang), rows in sorted(files.items()):
        seeds = [r["seed"] for _, r in rows]
        check(len(rows) == len(SEEDS), f"{kind}-{lang}: {len(rows)} rows (expected {len(SEEDS)})")
        check(seeds == SEEDS, f"{kind}-{lang}: seeds are exactly {SEEDS[0]}..{SEEDS[49]}, {SEEDS[50]}..{SEEDS[-1]} in order")
        check(all(r["mode"] == mode_for(r["seed"]) and r["lang"] == lang for _, r in rows),
              f"{kind}-{lang}: mode matches seed rule and lang column on every row")
    for lang in LANGS:
        w_keys = [(r["seed"], r["mode"]) for _, r in files["worlds", lang]]
        t_keys = [(r["seed"], r["mode"]) for _, r in files["truth", lang]]
        check(w_keys == t_keys, f"{lang}: worlds and truth rows pair up one-to-one")
        check(all(len(r["errors"]) > 0 for _, r in files["truth", lang]), f"{lang}: every truth row has >= 1 error")

    rng = random.Random(a.sample_seed)
    picked = sorted(rng.sample(SEEDS, a.n))
    print(f"sampled seeds: {picked}" + (f" (--sample-seed {a.sample_seed})" if a.sample_seed is not None else " (random)"))
    idx = {sd: i for i, sd in enumerate(SEEDS)}
    for sd in picked:
        mode = mode_for(sd)
        for lang in LANGS:
            raw_w, wrow = files["worlds", lang][idx[sd]]
            raw_t, trow = files["truth", lang][idx[sd]]
            w = World(seed=sd, lang=lang, difficulty=mode).build()
            check(dumps(world_record(w)).encode("utf-8") == raw_w,
                  f"seed {sd} {lang} {mode}: rebuilt snapshot == stored worlds line, byte for byte ({len(raw_w):,d} bytes)")
            check(dumps(truth_record(w)).encode("utf-8") == raw_t,
                  f"seed {sd} {lang} {mode}: rebuilt truth == stored truth line, byte for byte")
            r1 = oracle(w, trow)
            check(r1["passed"] and r1["score"] == 1.0 and not r1["missed"] and not r1["spurious_entries"],
                  f"seed {sd} {lang}: oracle on package-built world -> score {r1['score']}, passed {r1['passed']}, "
                  f"{len(r1['found'])}/{len(trow['errors'])} found")
            r2 = oracle(world_from_rows(wrow, trow), trow)
            check(r2["passed"] and r2["score"] == 1.0,
                  f"seed {sd} {lang}: oracle on world rebuilt from JSONL rows -> score {r2['score']}, passed {r2['passed']}")
        check(numbers(files["worlds", "en"][idx[sd]][1], files["truth", "en"][idx[sd]][1])
              == numbers(files["worlds", "ru"][idx[sd]][1], files["truth", "ru"][idx[sd]][1]),
              f"seed {sd}: en and ru differ only in text")

    print(f"{'ALL CHECKS PASSED' if not FAILS else f'{FAILS} CHECK(S) FAILED'}")
    sys.exit(1 if FAILS else 0)


if __name__ == "__main__":
    main()