File size: 24,330 Bytes
fd8b1ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
"""Cheat suite: every way of faking an answer, built from the honest reference and scored. Every cheat scores 0.

    python3 run_cheat_suite.py --environments F --reference DIR --engine ENGINE [--only id,id] [--out F]

DIR holds the honest reference replies made through the harness proxy by run_reference.py:
<id>.txt and <id>.harness.jsonl (made here, on the verifier, for any task that has none). For every
task, each vector below that applies to its family is built from the honest reply and scored by
score.py with the harness log as the call record. The honest reply must score reward 1 and graded 1;
every cheat reward 0 and graded 0. One JSON line per task and vector to --out; exit 1 on any cheat
above 0 or an honest reply below 1.

  honest                        the reference reply and its harness log (control: 1)
  honest_reply_log_matches      with a reply-side calls.jsonl equal to the harness log (control: 1)
  honest_numbers_respelled      the harness log with whole numbers spelt 18 where the card has 18.0 (control: 1)
  copied_proof_other_task       a proof copied from another task's card
  nudged_figure                 the design value moved inside the bracket, the original proof kept
  figure_plus_10_percent        the design value times 1.1, the original proof kept
  no_request_behind             the card with no calls in the harness log (forensics: free calls only)
  card_request_not_run          the card's request differs from the one the harness log shows was run
  edited_call_log               a reply-side calls.jsonl that differs from the harness log (a call dropped)
  over_budget                   more computing calls than the budget
  forbidden_tool                a ruled-out tool (find_flip) in the log
  no_harness_log                no harness log; only the reply-side log
  harness_log_edited            the harness log edited after the run (its chain breaks)
  stale_engine_tag              the task's reference marked as built on engine 0.15.0
  swapped_sides                 passing and failing (holds and stops) swapped
  binding_misnamed              another constraint named as binding
  proof_from_other_design       the failing design (stops side) carrying the passing one's proof
  failing_given_as_passing      the failing design given for both
  proof_uppercase               the proof in upper-case hex
  extra_argument                a request with one argument more than the template
  stop_misnamed, step_misnamed  the stop or step the card must name, wrong
  missing_solve                 a chained design without its solve (coupled) or its next run (continued) or its
                                last stage (staged)
  solve_handed_other_run        a solve (coupled), a next run (continued) or a later stage (staged) handed the other
                                design's first request and its proof
  next_start_rounded            continued: the next run's start state rounded to 9 significant figures (as sent)
  next_proof_copied             continued: the failing design's next proof replaced by the passing design's
  next_request_edited           continued: the next run's last segment one step longer than the task's (as sent)

The design shapes (score.design_shape): run, coupled, continued, solve, staged. A vector that edits "the first
request" edits the design's first entry: run, solve, or the first stage.
  every_row_genuine             forensics: {"false_rows": {}}
  every_row_false               forensics: every row named false with the first reason
  every_row_false_true_reasons  forensics: the false rows with their reasons and every genuine row too

Licence: Apache-2.0.
"""
import argparse
import copy
import json
import math
import os
import sys
import tempfile

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from score import (FREE_TOOLS, Replay, canonical, close_verifier, continuation_of, design_shape,  # noqa: E402
                   load_environments, open_verifier, read_card, read_harness_log, score, set_path, write_harness_log)


def respelled(value):
    """Whole floats written as ints (18.0 -> 18), as a client may send what a card writes as 18.0."""
    if isinstance(value, dict):
        return {k: respelled(v) for k, v in value.items()}
    if isinstance(value, list):
        return [respelled(v) for v in value]
    if isinstance(value, float) and value.is_integer() and abs(value) < 2 ** 53:
        return int(value)
    return value


def computing(calls):
    return [(t, a) for t, a in calls if t not in FREE_TOOLS]


def replace_call(calls, tool, old, new):
    """The log with the first call of tool with arguments old sent with new instead."""
    out, done = [], False
    for t, a in calls:
        if not done and t == tool and canonical(a) == canonical(old):
            out.append((t, new))
            done = True
        else:
            out.append((t, a))
    if not done:
        raise ValueError("the call to replace is not in the log")
    return out


def parts_of(env):
    """The keys of one design on the card, in order, and the tool of each."""
    spec = env["check"]["design"]
    shape = design_shape(spec)
    if shape == "staged":
        return [(st["key"], st["tool"]) for st in spec["stages"]]
    return {"solve": [("solve", "solve")], "continued": [("run", "run_trajectory"), ("next", "run_trajectory")],
            "coupled": [("run", "run_trajectory"), ("solve", "solve")]}.get(shape, [("run", "run_trajectory")])


def moved_design(env, design, x):
    """(design, [(tool, old arguments, new arguments)]): one boundary design with its value set to x."""
    spec = env["check"]["design"]
    var = spec["variable"]
    shape = design_shape(spec)
    new = copy.deepcopy(design)
    changes = []
    if shape in ("staged", "solve") or (shape == "continued" and var.get("on") == "next"):
        key = var["stage"] if shape == "staged" else ("solve" if shape == "solve" else "next")
        tool = dict(parts_of(env))[key]
        for place in [var["path"]] + list(var.get("also") or []):
            set_path(new[key]["request"]["arguments"], place, x)
        return new, [(tool, design[key]["request"]["arguments"], new[key]["request"]["arguments"])]
    run_old = design["run"]["request"]["arguments"]
    run_new = new["run"]["request"]["arguments"]
    if var["kind"] == "entry_angle_deg":
        g = math.radians(x)
        run_new["initial"]["radial_speed_m_s"] = -var["speed_m_s"] * math.sin(g)
        run_new["initial"]["transverse_speed_m_s"] = var["speed_m_s"] * math.cos(g)
    elif var.get("on", "run") == "run":
        for place in [var["path"]] + list(var.get("also") or []):
            set_path(run_new, place, x)
    if var.get("on", "run") == "run" or var["kind"] == "entry_angle_deg":
        changes.append(("run_trajectory", run_old, run_new))
        for key in ("solve", "next"):
            if new.get(key):
                new[key]["request"]["arguments"]["from"]["request"] = copy.deepcopy(run_new)
                if key == "next":
                    for place in continuation_of(spec)[3]:
                        set_path(new[key]["request"]["arguments"], place, x)
                changes.append((dict(parts_of(env)).get(key, "solve"), design[key]["request"]["arguments"],
                                new[key]["request"]["arguments"]))
    else:
        set_path(new["solve"]["request"]["arguments"], var["path"], x)
        changes.append(("solve", design["solve"]["request"]["arguments"], new["solve"]["request"]["arguments"]))
    return new, changes


def moved_budget(env, side, x):
    check = env["check"]
    new = copy.deepcopy(side)
    for place in [check["variable"]] + list(check.get("also") or []):
        set_path(new["request"]["arguments"], place, x)
    return new, [(check["tool"], side["request"]["arguments"], new["request"]["arguments"])]


def apply_changes(calls, changes):
    for tool, old, new in changes:
        calls = replace_call(calls, tool, old, new)
    return calls


def other_proof(env, others, family_tool):
    """A proof from another task's honest card, for the same kind of request (any part of any design or side)."""
    for other_id, other_card in others:
        if other_id == env["id"] or not isinstance(other_card, dict):
            continue
        for side in ("passing", "failing", "holds", "stops"):
            part = other_card.get(side)
            candidates = [part] if side in ("holds", "stops") else (list(part.values()) if isinstance(part, dict) else [])
            for one in candidates:
                if (isinstance(one, dict) and isinstance(one.get("proof"), str) and isinstance(one.get("request"), dict)
                        and one["request"].get("tool") == family_tool):
                    return other_id, one["proof"]
    return None, None


def stale(env):
    out = copy.deepcopy(env)
    out["reference"]["engine_tag"] = "v0.15.0"
    out["reference"]["gateway_version"] = "0.15.0"
    return out


def edited_log_file(calls, folder):
    """A harness log of calls, chained, then one line's arguments edited without its chain."""
    path = os.path.join(folder, "edited.harness.jsonl")
    write_harness_log(path, calls)
    lines = open(path).read().splitlines()
    pick = max(i for i, l in enumerate(lines) if json.loads(l)["tool"] not in FREE_TOOLS)
    entry = json.loads(lines[pick])
    entry["arguments"] = dict(entry["arguments"], edited=True)
    lines[pick] = json.dumps(entry, sort_keys=True)
    open(path, "w").write("\n".join(lines) + "\n")
    return read_harness_log(path)


def vectors(env, card, calls, others, scratch):
    """[(name, expect, env, card, calls, reply_calls, log_problem)] and [(name, why not)]."""
    family, check, ref = env["family"], env["check"], env["reference"]
    out, skipped = [], []
    add = lambda name, expect, card_, calls_, reply_calls=None, env_=None, log_problem=None: out.append(  # noqa: E731
        (name, expect, env_ or env, card_, calls_, reply_calls, log_problem))
    add("honest", 1, card, calls)
    add("honest_reply_log_matches", 1, card, calls, reply_calls=list(calls))
    add("honest_numbers_respelled", 1, card, [(t, respelled(a)) for t, a in calls])
    comp = computing(calls)

    # ---- the call record, the same for every family
    if family == "forensics":
        add("no_request_behind", 0, card, [c for c in calls if c[0] in FREE_TOOLS])
    else:
        add("no_request_behind", 0, card, [])
    last = max(i for i, c in enumerate(calls) if c[0] not in FREE_TOOLS)
    add("edited_call_log", 0, card, calls, reply_calls=calls[:last] + calls[last + 1:])
    if check.get("budget"):
        add("over_budget", 0, card, calls + [comp[0]] * (check["budget"] - len(comp) + 1))
    else:
        skipped.append(("over_budget", "the task has no call budget"))
    forbidden = check.get("forbidden") or []
    if forbidden:
        tool = "find_flip" if "find_flip" in forbidden else forbidden[0]
        add("forbidden_tool", 0, card, [(tool, {})] + list(calls))
    else:
        skipped.append(("forbidden_tool", "the task rules out no tool"))
    add("no_harness_log", 0, card, None, reply_calls=list(calls))
    edited_calls, problem = edited_log_file(calls, scratch)
    add("harness_log_edited", 0, card, edited_calls, log_problem=problem)
    add("stale_engine_tag", 0, card, calls, env_=stale(env))

    if family in ("tradeoff", "chain_design"):
        xp, xf = ref["passing"]["x"], ref["failing"]["x"]
        parts = parts_of(env)
        first, first_tool = parts[0]
        shape = design_shape(check["design"])
        oid, proof = other_proof(env, others, first_tool)
        bad = copy.deepcopy(card)
        bad["passing"][first]["proof"] = proof
        add("copied_proof_other_task", 0, bad, calls)
        for name, x in (("nudged_figure", 0.5 * (xp + xf)), ("figure_plus_10_percent", xp * 1.1)):
            design, changes = moved_design(env, card["passing"], x)
            add(name, 0, dict(card, passing=design), apply_changes(calls, changes))
        design, changes = moved_design(env, card["passing"], 0.5 * (xp + xf))
        add("card_request_not_run", 0, card, apply_changes(calls, changes[:1]))
        add("swapped_sides", 0, dict(card, passing=card["failing"], failing=card["passing"]), calls)
        other = [c["id"] for c in check["constraints"] if c["id"] != card["binding"]]
        add("binding_misnamed", 0, dict(card, binding=other[0] if other else "none"), calls)
        bad = copy.deepcopy(card)
        for key, _ in parts:
            if bad["failing"][key]["proof"] != card["passing"][key]["proof"]:
                bad["failing"][key]["proof"] = card["passing"][key]["proof"]
                break
        add("proof_from_other_design", 0, bad, calls)
        add("failing_given_as_passing", 0, dict(card, passing=copy.deepcopy(card["failing"])), calls)
        bad = copy.deepcopy(card)
        bad["passing"][first]["proof"] = bad["passing"][first]["proof"].upper()
        add("proof_uppercase", 0, bad, calls)
        bad = copy.deepcopy(card)
        bad["passing"][first]["request"]["arguments"]["note"] = "the same run"
        changes = [(first_tool, card["passing"][first]["request"]["arguments"], bad["passing"][first]["request"]["arguments"])]
        add("extra_argument", 0, bad, apply_changes(calls, changes))
        if card["failing"].get("stopped"):
            bad = copy.deepcopy(card)
            bad["failing"]["stopped"] = "SomeOtherStop"
            add("stop_misnamed", 0, bad, calls)
            if "step" in card["failing"]:
                bad = copy.deepcopy(card)
                bad["failing"]["step"] = card["failing"]["step"] + 1
                add("step_misnamed", 0, bad, calls)
            else:
                skipped.append(("step_misnamed", "the stop that binds is a solve's: it has no step"))
        else:
            skipped += [("stop_misnamed", "no stop binds"), ("step_misnamed", "no stop binds")]
        if len(parts) > 1:
            last = parts[-1][0]
            bad = copy.deepcopy(card)
            del bad["passing"][last]
            add("missing_solve", 0, bad, calls)
            # the later request handed the other design's earlier request and proof (or, staged, its later request)
            bad = copy.deepcopy(card)
            later = bad["passing"][last]["request"]["arguments"]
            if shape in ("coupled", "continued"):
                later["from"]["run_seal"] = card["failing"]["run"]["proof"]
                later["from"]["request"] = copy.deepcopy(card["failing"]["run"]["request"]["arguments"])
                same = card["failing"]["run"]["proof"] == card["passing"]["run"]["proof"]
            else:
                bad["passing"][last] = copy.deepcopy(card["failing"][last])
                same = card["failing"][parts[0][0]]["proof"] == card["passing"][parts[0][0]]["proof"]
            if same:
                skipped.append(("solve_handed_other_run", "the two designs share one first request"))
            else:
                add("solve_handed_other_run", 0, bad, apply_changes(calls, [(parts[-1][1], card["passing"][last]["request"]["arguments"],
                                                                            bad["passing"][last]["request"]["arguments"])])
                    if shape in ("coupled", "continued") else calls)
        else:
            skipped += [("missing_solve", "a design of one request"), ("solve_handed_other_run", "a design of one request")]
        if shape == "continued":
            bad = copy.deepcopy(card)
            start = bad["failing"]["next"]["request"]["arguments"]["initial"]
            for k, v in start.items():
                if isinstance(v, float) and v != 0.0:
                    start[k] = float("%.9g" % v)
            if start == card["failing"]["next"]["request"]["arguments"]["initial"]:
                for k, v in start.items():
                    if isinstance(v, float):
                        start[k] = v * (1 + 1e-12) if v else 1e-12
                        break
            add("next_start_rounded", 0, bad, apply_changes(calls, [("run_trajectory", card["failing"]["next"]["request"]["arguments"],
                                                                     bad["failing"]["next"]["request"]["arguments"])]))
            bad = copy.deepcopy(card)
            bad["failing"]["next"]["proof"] = card["passing"]["next"]["proof"]
            add("next_proof_copied", 0, bad, calls)
            bad = copy.deepcopy(card)
            bad["failing"]["next"]["request"]["arguments"]["segments"][-1]["steps"] += 1
            add("next_request_edited", 0, bad, apply_changes(calls, [("run_trajectory", card["failing"]["next"]["request"]["arguments"],
                                                                      bad["failing"]["next"]["request"]["arguments"])]))
        else:
            skipped += [(v, "not a continued design") for v in ("next_start_rounded", "next_proof_copied", "next_request_edited")]
        skipped += [(v, "forensics only") for v in ("every_row_genuine", "every_row_false", "every_row_false_true_reasons")]

    elif family == "budget":
        xh, xs = ref["holds"]["x"], ref["stops"]["x"]
        oid, proof = other_proof(env, others, check["tool"])
        bad = copy.deepcopy(card)
        bad["holds"]["proof"] = proof
        add("copied_proof_other_task", 0, bad, calls)
        for name, x in (("nudged_figure", 0.5 * (xh + xs)), ("figure_plus_10_percent", xs * 1.1)):
            side, changes = moved_budget(env, card["stops"], x)
            add(name, 0, dict(card, stops=side), apply_changes(calls, changes))
        side, changes = moved_budget(env, card["stops"], 0.5 * (xh + xs))
        add("card_request_not_run", 0, card, apply_changes(calls, changes))
        add("swapped_sides", 0, dict(card, holds={k: v for k, v in card["stops"].items() if k != "stopped"},
                                     stops=dict(card["holds"], stopped=check["stop"])), calls)
        bad = copy.deepcopy(card)
        bad["stops"]["stopped"] = "SomeOtherStop"
        add("stop_misnamed", 0, bad, calls)
        bad = copy.deepcopy(card)
        bad["stops"]["proof"] = card["holds"]["proof"]
        add("proof_from_other_design", 0, bad, calls)
        bad = copy.deepcopy(card)
        bad["holds"]["proof"] = bad["holds"]["proof"].upper()
        add("proof_uppercase", 0, bad, calls)
        bad = copy.deepcopy(card)
        bad["holds"]["request"]["arguments"]["note"] = "the same run"
        add("extra_argument", 0, bad, apply_changes(calls, [(check["tool"], card["holds"]["request"]["arguments"],
                                                             bad["holds"]["request"]["arguments"])]))
        skipped += [(v, "not a budget card") for v in ("binding_misnamed", "failing_given_as_passing", "step_misnamed",
                                                         "missing_solve", "solve_handed_other_run", "every_row_genuine",
                                                         "every_row_false", "every_row_false_true_reasons",
                                                         "next_start_rounded", "next_proof_copied", "next_request_edited")]
    else:
        rows = [r["row"] for r in check["rows"]]
        reasons = check.get("reasons") or ["value_altered"]
        truth = ref["false_rows"]
        if truth:
            add("every_row_genuine", 0, {"false_rows": {}}, calls)
        else:
            skipped.append(("every_row_genuine", "the table has no false row: that is the right answer"))
        add("every_row_false", 0, {"false_rows": {r: reasons[0] for r in rows}}, calls)
        add("every_row_false_true_reasons", 0, {"false_rows": {r: truth.get(r, reasons[0]) for r in rows}}, calls)
        skipped += [(v, "a forensics card carries no request or proof") for v in (
            "copied_proof_other_task", "nudged_figure", "figure_plus_10_percent", "card_request_not_run", "swapped_sides",
            "binding_misnamed", "proof_from_other_design", "failing_given_as_passing", "proof_uppercase", "extra_argument",
            "stop_misnamed", "step_misnamed", "missing_solve", "solve_handed_other_run",
            "next_start_rounded", "next_proof_copied", "next_request_edited")]
    return out, skipped


def ensure_reference(env, folder, engine):
    reply_path = os.path.join(folder, env["id"] + ".txt")
    log_path = os.path.join(folder, env["id"] + ".harness.jsonl")
    if os.path.isfile(reply_path) and os.path.isfile(log_path):
        return
    from run_reference import proxied, reference_reply
    verifier = proxied(engine, log_path)
    try:
        reply, calls = reference_reply(env, verifier)
    finally:
        close_verifier(verifier)
    open(reply_path, "w", encoding="utf-8").write(reply + "\n")


def main():
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("--environments", required=True)
    parser.add_argument("--reference", required=True)
    parser.add_argument("--engine", required=True)
    parser.add_argument("--only")
    parser.add_argument("--out")
    args = parser.parse_args()
    environments = load_environments(args.environments)
    os.makedirs(args.reference, exist_ok=True)
    for env in environments:
        ensure_reference(env, args.reference, args.engine)
    honest = {}
    for env in environments:
        card, problem = read_card(open(os.path.join(args.reference, env["id"] + ".txt"), encoding="utf-8").read())
        calls, log_problem = read_harness_log(os.path.join(args.reference, env["id"] + ".harness.jsonl"))
        if problem or log_problem or calls is None:
            sys.exit("the honest reference of %s cannot be read: %s" % (env["id"], problem or log_problem or "no harness log"))
        honest[env["id"]] = (card, calls)
    others = [(i, c) for i, (c, _) in honest.items()]
    if args.only:
        wanted = set(args.only.split(","))
        environments = [e for e in environments if e["id"] in wanted]
    verifier = open_verifier(args.engine)
    rows, failures, by_vector = [], 0, {}
    scratch = tempfile.mkdtemp(prefix="ztp_cheats_")
    try:
        for env in environments:
            card, calls = honest[env["id"]]
            replay = Replay(verifier)
            built, skipped = vectors(env, card, calls, others, scratch)
            for name, expect, env_, card_, calls_, reply_calls, log_problem in built:
                row = score(env_, "A reply.\n\n" + json.dumps(card_), replay, calls_, reply_calls, "harness", log_problem)
                ok = (row["reward"] == 1 and row["graded"] == 1.0) if expect else (row["reward"] == 0 and row["graded"] == 0.0)
                failures += not ok
                one = {"task": env["id"], "family": env["family"], "vector": name, "applies": True, "expect": expect,
                       "reward": row["reward"], "graded": row["graded"], "verdict": row["verdict"], "reason": row["reason"], "ok": ok}
                rows.append(one)
                tally = by_vector.setdefault(name, [0, 0, 0])
                tally[0] += 1
                tally[1] += not ok
                print("%-4s %-52s %-30s reward %d graded %.4f %s" % ("ok" if ok else "FAIL", env["id"], name, row["reward"],
                                                                     row["graded"], (row["reason"] or "")[:110]), flush=True)
            for name, why in skipped:
                rows.append({"task": env["id"], "family": env["family"], "vector": name, "applies": False, "why": why})
                by_vector.setdefault(name, [0, 0, 0])[2] += 1
    finally:
        close_verifier(verifier)
    if args.out:
        with open(args.out, "w", encoding="utf-8") as f:
            for row in rows:
                f.write(json.dumps(row) + "\n")
    print("\n%-30s %6s %6s %6s" % ("vector", "tasks", "fail", "n/a"))
    for name in sorted(by_vector):
        print("%-30s %6d %6d %6d" % (name, *by_vector[name]))
    scored = [r for r in rows if r["applies"]]
    print("\n%d tasks, %d scored attempts (%d honest controls, %d cheats); %d failures" % (
        len(environments), len(scored), sum(1 for r in scored if r["expect"]), sum(1 for r in scored if not r["expect"]), failures))
    sys.exit(1 if failures else 0)


if __name__ == "__main__":
    main()