-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfalsify.py
More file actions
4127 lines (3678 loc) · 135 KB
/
falsify.py
File metadata and controls
4127 lines (3678 loc) · 135 KB
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Falsification Engine — pre-registration + CI for AI-agent claims."""
from __future__ import annotations
import argparse
import difflib
import hashlib
import html as html_module
import importlib
import json
import platform
import re
import shutil
import socket
import statistics
import string
import subprocess
import sys
import tempfile
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable
import yaml
__version__ = "0.3.0"
EXIT_PASS = 0
EXIT_FAIL = 10
EXIT_BAD_SPEC = 2
EXIT_HASH_MISMATCH = 3
SCRIPT_DIR = Path(__file__).resolve().parent
TEMPLATE_PATH = SCRIPT_DIR / "examples" / "template.yaml"
SCHEMA_PATH = SCRIPT_DIR / "hypothesis.schema.yaml"
FALSIFY_DIR = Path(".falsify")
# Inlined data files (v0.2.0): pyproject.toml's py-modules layout cannot ship
# data files in the wheel under setuptools, so the file paths above only resolve
# in dev mode. The constants below are the source of truth bundled inside the
# Python module itself, ensuring `falsify init` and `falsify lock` work on a
# clean `pip install falsify` without any external file fetch.
_BUNDLED_SCHEMA_YAML = """\
schema_version: 1
type: object
required:
- claim
- falsification
- experiment
properties:
claim:
type: string
required: true
description: >
One-sentence hypothesis that can, in principle, be proven wrong.
Must be a concrete, falsifiable statement — not a vibe.
falsification:
type: object
required: true
description: >
The conditions under which the claim is considered falsified.
properties:
failure_criteria:
type: array
required: true
min_items: 1
description: >
One or more conditions. If ANY criterion triggers on a run,
the claim is FAIL.
items:
type: object
required: [metric, direction, threshold]
properties:
metric:
type: string
description: >
Name of the metric. Must be a key returned by the
experiment's metric_fn.
direction:
type: string
enum: [above, below, equals]
description: >
Direction that must hold for the claim to PASS.
Comparisons are STRICT — boundary equality FAILS.
above: observed > threshold (strictly greater, NOT >=)
below: observed < threshold (strictly less, NOT <=)
equals: |observed - threshold| < 1e-9
A claim like "at least N" with integer values must set
threshold to N-1 and direction to above (so observed=N
PASSes as N > N-1). Setting threshold=N with direction
above would FAIL at the exact boundary.
threshold:
type: number
description: Numeric threshold the metric is compared to.
minimum_sample_size:
type: integer
required: true
minimum: 1
description: >
Minimum n before a verdict is considered valid. Runs with
fewer samples return an indeterminate verdict, not PASS.
stopping_rule:
type: string
required: true
description: >
When to stop collecting evidence — e.g. "after 1000 samples"
or "after 1 epoch over the eval set". Locked at pre-registration
time to prevent optional stopping.
experiment:
type: object
required: true
description: The reproducible procedure that generates evidence.
properties:
command:
type: string
required: true
description: Shell command that runs the experiment.
dataset:
type: string
required: false
description: Path or identifier of the dataset under test.
metric_fn:
type: string
required: true
pattern: "^[A-Za-z_][\\\\w.]*:[A-Za-z_]\\\\w*$"
description: >
Dotted import path and function, separated by a colon.
Example: "my_pkg.metrics:accuracy". The function must return
a dict keyed by metric name.
environment:
type: object
required: false
description: Environment pins used to reproduce the run.
properties:
python:
type: string
description: Python version spec, e.g. "3.11" or ">=3.11,<3.13".
packages:
type: array
items:
type: string
description: PEP-508 requirement string, e.g. "numpy==2.0.0".
artifacts:
type: object
required: false
description: Files the experiment is expected to produce.
properties:
outputs:
type: array
items:
type: string
description: Path (glob allowed) of an expected output artifact.
placeholder_markers:
- "<"
- "TODO"
- "FIXME"
- "REPLACE_ME"
- "XXX"
"""
_BUNDLED_TEMPLATE_YAML = """\
# Falsification Engine — claim spec
#
# Fill in every placeholder before running `falsify lock`.
# Placeholders: "<...>", TODO, FIXME, REPLACE_ME, XXX.
# A spec with any placeholder left in a string field cannot be locked
# (the CLI will exit 2: bad spec).
claim: "<one-sentence hypothesis that can, in principle, be proven wrong>"
falsification:
failure_criteria:
- metric: "<metric name, must match a key returned by metric_fn>"
direction: "<above|below|equals>"
threshold: 0.0 # TODO: real threshold
minimum_sample_size: 1 # TODO: real n
stopping_rule: "<when to stop — e.g. 'after 1000 samples' or 'after 1 epoch'>"
experiment:
command: "<shell command that runs the experiment, e.g. python run.py>"
dataset: "<path or identifier of the dataset under test>"
metric_fn: "<module:function>" # e.g. my_pkg.metrics:accuracy
environment:
python: "3.11"
packages:
- "<package==version>"
artifacts:
outputs:
- "<path/to/expected/output>"
"""
_FALLBACK_PLACEHOLDER_MARKERS = ("<", "TODO", "FIXME", "REPLACE_ME", "XXX")
_RUN_TIMEOUT_S = 300
_EQUALS_EPSILON = 1e-9
_AFFIRMATIVE_KEYWORDS = (
"confirmed",
"proven",
"validated",
"works",
"successful",
)
EXIT_GUARD_VIOLATION = 11
_TYPE_CHECKERS: dict[str, Callable[[Any], bool]] = {
"string": lambda v: isinstance(v, str),
"integer": lambda v: isinstance(v, int) and not isinstance(v, bool),
"number": lambda v: isinstance(v, (int, float)) and not isinstance(v, bool),
"array": lambda v: isinstance(v, list),
"object": lambda v: isinstance(v, dict),
"boolean": lambda v: isinstance(v, bool),
}
_INIT_TEMPLATES: dict[str, dict[str, str]] = {
"accuracy": {
"spec.yaml": (
'claim: "Classifier accuracy is at least 80% on the holdout sample."\n'
"falsification:\n"
" failure_criteria:\n"
" - metric: accuracy\n"
" direction: above\n"
" threshold: 0.80\n"
" minimum_sample_size: 20\n"
' stopping_rule: "fixed-n"\n'
"experiment:\n"
' command: "echo ready"\n'
' dataset: "data.csv"\n'
' metric_fn: "__MODULE_PATH__.metric:accuracy"\n'
),
"metric.py": (
'"""Classifier accuracy: matches / total."""\n'
"import csv\n"
"from pathlib import Path\n\n"
"def accuracy(_run_dir):\n"
' path = Path(__file__).parent / "data.csv"\n'
" rows = list(csv.DictReader(path.open()))\n"
" if not rows:\n"
" return 0.0, 0\n"
' correct = sum(1 for r in rows if r["predicted"] == r["actual"])\n'
" return correct / len(rows), len(rows)\n"
),
"data.csv": (
"id,predicted,actual\n"
"1,cat,cat\n2,dog,dog\n3,bird,bird\n4,cat,dog\n5,dog,dog\n"
"6,cat,cat\n7,bird,bird\n8,dog,bird\n9,cat,cat\n10,dog,dog\n"
"11,bird,bird\n12,cat,cat\n13,dog,bird\n14,cat,cat\n15,dog,dog\n"
"16,bird,bird\n17,cat,cat\n18,dog,dog\n19,bird,bird\n20,cat,cat\n"
),
"README.md": (
"# accuracy template\n\n"
"Asserts a classifier's holdout accuracy is at least 80%.\n\n"
"**Files:** `spec.yaml` (claim + threshold), `metric.py`\n"
"(stdlib `csv` reader), `data.csv` (20 hand-crafted rows,\n"
"17 correct → 0.85). The shipped data passes; mutate it to\n"
"make it fail.\n\n"
"**Modify:** swap `data.csv` for your own holdout, retune\n"
"the `threshold` in `spec.yaml`, then `lock --force`.\n"
"See [TUTORIAL.md](../../TUTORIAL.md) for the full pipeline.\n"
),
},
"latency": {
"spec.yaml": (
'claim: "P95 request latency stays below 200ms."\n'
"falsification:\n"
" failure_criteria:\n"
" - metric: p95_latency_ms\n"
" direction: below\n"
" threshold: 200\n"
" minimum_sample_size: 20\n"
' stopping_rule: "fixed-n"\n'
"experiment:\n"
' command: "echo ready"\n'
' dataset: "data.csv"\n'
' metric_fn: "__MODULE_PATH__.metric:p95_latency"\n'
),
"metric.py": (
'"""P95 latency: nearest-rank percentile over latency_ms column."""\n'
"import csv\n"
"import math\n"
"from pathlib import Path\n\n"
"def p95_latency(_run_dir):\n"
' path = Path(__file__).parent / "data.csv"\n'
' values = sorted(float(r["latency_ms"])\n'
" for r in csv.DictReader(path.open()))\n"
" n = len(values)\n"
" if n == 0:\n"
" return 0.0, 0\n"
" idx = max(0, math.ceil(0.95 * n) - 1)\n"
" return values[idx], n\n"
),
"data.csv": (
"request_id,latency_ms\n"
"r01,52\nr02,67\nr03,71\nr04,84\nr05,55\n"
"r06,90\nr07,73\nr08,68\nr09,82\nr10,95\n"
"r11,77\nr12,61\nr13,88\nr14,79\nr15,66\n"
"r16,103\nr17,124\nr18,182\nr19,191\nr20,196\n"
),
"README.md": (
"# latency template\n\n"
"Asserts a service's p95 request latency stays under 200ms.\n\n"
"**Files:** `spec.yaml` (threshold = 200, direction = below),\n"
"`metric.py` (nearest-rank p95 over the `latency_ms` column),\n"
"`data.csv` (20 hand-crafted samples; sorted index 18 is 191ms).\n\n"
"**Modify:** point `data.csv` at your own benchmark output,\n"
"tune `threshold` in `spec.yaml`, then `lock --force`. See\n"
"[TUTORIAL.md](../../TUTORIAL.md).\n"
),
},
"brier": {
"spec.yaml": (
'claim: "Probabilistic predictions are calibrated (Brier score below 0.25)."\n'
"falsification:\n"
" failure_criteria:\n"
" - metric: brier_score\n"
" direction: below\n"
" threshold: 0.25\n"
" minimum_sample_size: 20\n"
' stopping_rule: "fixed-n"\n'
"experiment:\n"
' command: "echo ready"\n'
' dataset: "data.csv"\n'
' metric_fn: "__MODULE_PATH__.metric:brier_score"\n'
),
"metric.py": (
'"""Brier score: mean squared error between predicted_prob and actual."""\n'
"import csv\n"
"from pathlib import Path\n\n"
"def brier_score(_run_dir):\n"
' path = Path(__file__).parent / "data.csv"\n'
" rows = list(csv.DictReader(path.open()))\n"
" if not rows:\n"
" return 0.0, 0\n"
' total = sum((float(r["predicted_prob"]) - float(r["actual"])) ** 2\n'
" for r in rows)\n"
" return total / len(rows), len(rows)\n"
),
"data.csv": (
"event_id,predicted_prob,actual\n"
"e01,0.90,1\ne02,0.10,0\ne03,0.85,1\ne04,0.15,0\ne05,0.92,1\n"
"e06,0.08,0\ne07,0.78,1\ne08,0.22,0\ne09,0.88,1\ne10,0.12,0\n"
"e11,0.83,1\ne12,0.18,0\ne13,0.95,1\ne14,0.05,0\ne15,0.80,1\n"
"e16,0.20,0\ne17,0.85,0\ne18,0.15,1\ne19,0.90,1\ne20,0.10,0\n"
),
"README.md": (
"# brier template\n\n"
"Asserts probabilistic predictions are calibrated: Brier\n"
"score (mean squared error vs the binary actual) below 0.25.\n\n"
"**Files:** `spec.yaml`, `metric.py` (one-liner Brier), and\n"
"20 rows of `(event_id, predicted_prob, actual)` in\n"
"`data.csv`. Shipped data has 18 confident-correct + 2\n"
"confident-wrong → Brier ≈ 0.09.\n\n"
"**Modify:** swap in your model's calibration data; retune\n"
"threshold; `lock --force`. See [TUTORIAL.md](../../TUTORIAL.md).\n"
),
},
"llm-judge": {
"spec.yaml": (
'claim: "LLM judges agree with the reference at least 75% of the time."\n'
"falsification:\n"
" failure_criteria:\n"
" - metric: agreement_rate\n"
" direction: above\n"
" threshold: 0.75\n"
" minimum_sample_size: 20\n"
' stopping_rule: "fixed-n"\n'
"experiment:\n"
' command: "echo ready"\n'
' dataset: "data.jsonl"\n'
' metric_fn: "__MODULE_PATH__.metric:agreement_rate"\n'
),
"metric.py": (
'"""LLM-judge agreement rate: fraction of rows where agreement is true."""\n'
"import json\n"
"from pathlib import Path\n\n"
"def agreement_rate(_run_dir):\n"
' path = Path(__file__).parent / "data.jsonl"\n'
" rows = []\n"
" with path.open() as f:\n"
" for line in f:\n"
" line = line.strip()\n"
" if line:\n"
" rows.append(json.loads(line))\n"
" if not rows:\n"
" return 0.0, 0\n"
' agree = sum(1 for r in rows if r.get("agreement"))\n'
" return agree / len(rows), len(rows)\n"
),
"data.jsonl": (
'{"prompt": "2+2?", "answer_a": "4", "answer_b": "Four", "agreement": true}\n'
'{"prompt": "Capital of France?", "answer_a": "Paris", "answer_b": "Paris", "agreement": true}\n'
'{"prompt": "Color of the sky?", "answer_a": "Blue", "answer_b": "Cyan", "agreement": false}\n'
'{"prompt": "Speed of light unit?", "answer_a": "m/s", "answer_b": "meters per second", "agreement": true}\n'
'{"prompt": "Largest ocean?", "answer_a": "Pacific", "answer_b": "Pacific Ocean", "agreement": true}\n'
'{"prompt": "Pi to 2 decimals?", "answer_a": "3.14", "answer_b": "3.14159", "agreement": false}\n'
'{"prompt": "Author of 1984?", "answer_a": "Orwell", "answer_b": "George Orwell", "agreement": true}\n'
'{"prompt": "Boiling point of water (C)?", "answer_a": "100", "answer_b": "100", "agreement": true}\n'
'{"prompt": "Number of planets?", "answer_a": "8", "answer_b": "9", "agreement": false}\n'
'{"prompt": "JS framework by Facebook?", "answer_a": "React", "answer_b": "React.js", "agreement": true}\n'
'{"prompt": "DNA base count?", "answer_a": "4", "answer_b": "Four", "agreement": true}\n'
'{"prompt": "Symbol for gold?", "answer_a": "Au", "answer_b": "Au", "agreement": true}\n'
'{"prompt": "Sum of angles in triangle?", "answer_a": "180", "answer_b": "180 degrees", "agreement": true}\n'
'{"prompt": "Tallest mountain?", "answer_a": "Everest", "answer_b": "K2", "agreement": false}\n'
'{"prompt": "Currency of Japan?", "answer_a": "Yen", "answer_b": "Japanese Yen", "agreement": true}\n'
'{"prompt": "First president of USA?", "answer_a": "Washington", "answer_b": "George Washington", "agreement": true}\n'
'{"prompt": "HTTP status for OK?", "answer_a": "200", "answer_b": "200", "agreement": true}\n'
'{"prompt": "Atomic number of H?", "answer_a": "1", "answer_b": "1", "agreement": true}\n'
'{"prompt": "Author of Hamlet?", "answer_a": "Shakespeare", "answer_b": "William Shakespeare", "agreement": true}\n'
'{"prompt": "Sides of a hexagon?", "answer_a": "6", "answer_b": "6", "agreement": true}\n'
),
"README.md": (
"# llm-judge template\n\n"
"Asserts your LLM-judge agrees with the reference at least\n"
"75% of the time across pairwise prompts.\n\n"
"**Files:** `spec.yaml`, `metric.py` (counts the\n"
"`agreement` field), `data.jsonl` (20 prompts; 16 marked\n"
"agreement=true → 0.80).\n\n"
"**To plug in a real LLM judge:** rewrite `metric.py` to\n"
"send each `(prompt, answer_a, answer_b)` triple to your\n"
"judge model and recompute `agreement` at evaluation time.\n"
"Then `lock --force`. See [TUTORIAL.md](../../TUTORIAL.md).\n"
),
},
"ab": {
"spec.yaml": (
'claim: "Variant B has at least a 5 percentage-point absolute lift over A."\n'
"falsification:\n"
" failure_criteria:\n"
" - metric: ab_lift\n"
" direction: above\n"
" threshold: 0.05\n"
" minimum_sample_size: 20\n"
' stopping_rule: "fixed-n"\n'
"experiment:\n"
' command: "echo ready"\n'
' dataset: "data.csv"\n'
' metric_fn: "__MODULE_PATH__.metric:ab_lift"\n'
),
"metric.py": (
'"""A/B test lift: conversion(B) - conversion(A)."""\n'
"import csv\n"
"from pathlib import Path\n\n"
"def ab_lift(_run_dir):\n"
' path = Path(__file__).parent / "data.csv"\n'
" rows = list(csv.DictReader(path.open()))\n"
" if not rows:\n"
" return 0.0, 0\n"
' a = [r for r in rows if r["variant"] == "a"]\n'
' b = [r for r in rows if r["variant"] == "b"]\n'
" if not a or not b:\n"
" return 0.0, len(rows)\n"
' rate_a = sum(int(r["converted"]) for r in a) / len(a)\n'
' rate_b = sum(int(r["converted"]) for r in b) / len(b)\n'
" return rate_b - rate_a, len(rows)\n"
),
"data.csv": (
"user_id,variant,converted\n"
"u01,a,0\nu02,a,1\nu03,a,0\nu04,a,1\nu05,a,0\n"
"u06,a,0\nu07,a,0\nu08,a,0\nu09,a,0\nu10,a,0\n"
"u11,b,0\nu12,b,1\nu13,b,1\nu14,b,0\nu15,b,1\n"
"u16,b,0\nu17,b,0\nu18,b,0\nu19,b,0\nu20,b,0\n"
),
"README.md": (
"# ab template\n\n"
"Asserts that variant B's conversion rate exceeds variant\n"
"A's by at least 5 percentage points (absolute lift).\n\n"
"**Files:** `spec.yaml` (threshold 0.05, direction above),\n"
"`metric.py` (lift = rate_b - rate_a), `data.csv` (20 rows,\n"
"10 per variant; A=0.20, B=0.30 → lift 0.10).\n\n"
"**Modify:** swap in your real experiment's per-user\n"
"conversions; the column names (`variant`, `converted`)\n"
"are what the metric reads. `lock --force` after edits.\n"
"See [TUTORIAL.md](../../TUTORIAL.md).\n"
),
},
}
def _cmd_init_template(args: argparse.Namespace) -> int:
template_name = args.template
if template_name not in _INIT_TEMPLATES:
avail = ", ".join(sorted(_INIT_TEMPLATES))
print(
f"falsify init: unknown template {template_name!r}; "
f"available: {avail}",
file=sys.stderr,
)
return EXIT_BAD_SPEC
# Default to a Python-import-safe name (snake_case) when the
# template flag uses kebab-case (e.g. --template llm-judge).
default_name = template_name.replace("-", "_")
name = args.claim_name or args.name or default_name
target_dir = Path(args.dir) if args.dir else Path("claims") / name
files = _INIT_TEMPLATES[template_name]
if target_dir.exists():
existing = [
f for f in files
if (target_dir / f).exists()
]
if existing and not args.force:
print(
f"falsify init: files exist; use --force to overwrite: "
f"{', '.join(existing)} in {target_dir}",
file=sys.stderr,
)
return EXIT_BAD_SPEC
module_path = (
str(target_dir).replace("\\", "/").replace("/", ".").strip(".")
)
target_dir.mkdir(parents=True, exist_ok=True)
for filename, content in files.items():
rendered = (
content
.replace("__MODULE_PATH__", module_path)
.replace("__NAME__", name)
)
(target_dir / filename).write_text(rendered)
falsify_dir = FALSIFY_DIR / name
falsify_dir.mkdir(parents=True, exist_ok=True)
(falsify_dir / "spec.yaml").write_text(
(target_dir / "spec.yaml").read_text()
)
print(f"Scaffolded `{template_name}` template at {target_dir}/")
print(f" spec mirrored to .falsify/{name}/spec.yaml")
print()
print("Next steps:")
print(f" python3 falsify.py lock {name}")
print(f" python3 falsify.py run {name}")
print(f" python3 falsify.py verdict {name}")
return EXIT_PASS
def cmd_init(args: argparse.Namespace) -> int:
if args.template:
return _cmd_init_template(args)
name = args.name or args.claim_name
if not name:
print(
"falsify init: claim name required (positional or --name) "
"unless --template is given",
file=sys.stderr,
)
return 1
target_dir = FALSIFY_DIR / name
spec_path = target_dir / "spec.yaml"
if target_dir.exists() and not args.force:
print(
f"falsify init: {target_dir} already exists "
f"(use --force to overwrite)",
file=sys.stderr,
)
return 1
target_dir.mkdir(parents=True, exist_ok=True)
if TEMPLATE_PATH.exists():
spec_path.write_text(TEMPLATE_PATH.read_text())
else:
# Fallback: bundled template (pip-installed wheel ships data inline).
spec_path.write_text(_BUNDLED_TEMPLATE_YAML)
print(f"Created {spec_path}")
print("Next: edit the spec, replace placeholders, then `falsify lock`.")
return EXIT_PASS
def _stub(name: str) -> int:
print(f"falsify {name}: not yet implemented", file=sys.stderr)
return 1
def _load_schema() -> dict:
if SCHEMA_PATH.exists():
with SCHEMA_PATH.open() as f:
return yaml.safe_load(f)
# Fallback: bundled schema (used when installed via pip wheel where the
# external file isn't shipped). See _BUNDLED_SCHEMA_YAML at the top of
# this module.
return yaml.safe_load(_BUNDLED_SCHEMA_YAML)
def _collect_required_keys(node: dict) -> list[str]:
top = node.get("required")
if isinstance(top, list):
return list(top)
props = node.get("properties") or {}
return [
k for k, v in props.items()
if isinstance(v, dict) and v.get("required") is True
]
def _validate_against_schema(
value: Any,
schema: dict,
path: str,
errors: list[str],
) -> None:
ty = schema.get("type")
if ty in _TYPE_CHECKERS and not _TYPE_CHECKERS[ty](value):
errors.append(
f"{path or '<root>'}: expected {ty}, got {type(value).__name__}"
)
return
enum = schema.get("enum")
if enum is not None and value not in enum:
errors.append(f"{path}: {value!r} not in {list(enum)}")
pattern = schema.get("pattern")
if pattern and isinstance(value, str) and not re.match(pattern, value):
errors.append(f"{path}: {value!r} does not match pattern {pattern!r}")
minimum = schema.get("minimum")
if (
minimum is not None
and isinstance(value, (int, float))
and not isinstance(value, bool)
and value < minimum
):
errors.append(f"{path}: must be >= {minimum} (got {value})")
if ty == "object" and isinstance(value, dict):
for key in _collect_required_keys(schema):
if key not in value:
prefix = f"{path}." if path else ""
errors.append(f"{prefix}{key}: missing required field")
props = schema.get("properties") or {}
for key, sub in value.items():
if key in props and isinstance(props[key], dict):
sub_path = f"{path}.{key}" if path else key
_validate_against_schema(sub, props[key], sub_path, errors)
if ty == "array" and isinstance(value, list):
min_items = schema.get("min_items")
if isinstance(min_items, int) and len(value) < min_items:
errors.append(
f"{path}: must have at least {min_items} item(s) (got {len(value)})"
)
items_schema = schema.get("items")
if isinstance(items_schema, dict):
for i, item in enumerate(value):
_validate_against_schema(
item, items_schema, f"{path}[{i}]", errors
)
def _find_placeholders(
value: Any,
markers: tuple[str, ...],
path: str = "",
) -> list[tuple[str, str]]:
found: list[tuple[str, str]] = []
if isinstance(value, dict):
for k, v in value.items():
sub = f"{path}.{k}" if path else k
found.extend(_find_placeholders(v, markers, sub))
elif isinstance(value, list):
for i, item in enumerate(value):
found.extend(_find_placeholders(item, markers, f"{path}[{i}]"))
elif isinstance(value, str):
for marker in markers:
if marker in value:
found.append((path, value))
break
return found
def _canonicalize(spec: Any) -> str:
"""Render a YAML tree in a stable form suitable for hashing."""
return yaml.safe_dump(
spec,
sort_keys=True,
default_flow_style=False,
allow_unicode=True,
width=4096,
)
def cmd_lock(args: argparse.Namespace) -> int:
claim_dir = FALSIFY_DIR / args.name
spec_path = claim_dir / "spec.yaml"
lock_path = claim_dir / "spec.lock.json"
if not spec_path.exists():
print(
f"falsify lock: {spec_path} not found — "
f"run `falsify init {args.name}` first",
file=sys.stderr,
)
return 1
try:
raw_text = spec_path.read_text()
spec = yaml.safe_load(raw_text)
except yaml.YAMLError as e:
print(f"falsify lock: failed to parse {spec_path}: {e}", file=sys.stderr)
return EXIT_BAD_SPEC
if not isinstance(spec, dict):
print(
f"falsify lock: {spec_path} must be a YAML mapping at the top level",
file=sys.stderr,
)
return EXIT_BAD_SPEC
schema = _load_schema()
markers_raw = schema.get("placeholder_markers") or _FALLBACK_PLACEHOLDER_MARKERS
markers = tuple(str(m) for m in markers_raw)
placeholders = _find_placeholders(spec, markers)
if placeholders:
print(
f"falsify lock: {spec_path} still contains placeholder values:",
file=sys.stderr,
)
for field_path, val in placeholders:
print(f" - {field_path}: {val!r}", file=sys.stderr)
print(
"Replace placeholders with real values, then re-run `falsify lock`.",
file=sys.stderr,
)
return EXIT_BAD_SPEC
errors: list[str] = []
_validate_against_schema(spec, schema, "", errors)
if errors:
print(f"falsify lock: invalid spec {spec_path}:", file=sys.stderr)
for err in errors:
print(f" - {err}", file=sys.stderr)
return EXIT_BAD_SPEC
canonical = _canonicalize(spec)
spec_hash = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
if lock_path.exists() and not args.force:
try:
existing = json.loads(lock_path.read_text())
except json.JSONDecodeError:
existing = None
if isinstance(existing, dict):
existing_hash = existing.get("spec_hash")
if isinstance(existing_hash, str):
if existing_hash == spec_hash:
print(
f"Already locked {args.name} @ {spec_hash[:12]} "
f"— spec unchanged."
)
return EXIT_PASS
print(
f"falsify lock: {spec_path} has been modified since last lock "
f"(was {existing_hash[:12]}, now {spec_hash[:12]}). "
f"Use --force to relock.",
file=sys.stderr,
)
return EXIT_HASH_MISMATCH
lock_data = {
"spec_hash": spec_hash,
"locked_at": datetime.now(timezone.utc).isoformat(),
"canonical_yaml": canonical,
}
lock_path.write_text(
json.dumps(lock_data, indent=2, sort_keys=True) + "\n"
)
print(f"✓ Locked {args.name} @ {spec_hash[:12]}")
for c in spec["falsification"]["failure_criteria"]:
print(f" claim: {c['metric']} {c['direction']} {c['threshold']}")
return EXIT_PASS
def _render_unified_diff(
a_text: str, b_text: str, label_a: str, label_b: str
) -> None:
"""Write a colored unified diff to stdout.
ANSI escapes are emitted only when stdout is a TTY.
"""
use_color = sys.stdout.isatty()
for line in difflib.unified_diff(
a_text.splitlines(keepends=True),
b_text.splitlines(keepends=True),
fromfile=label_a,
tofile=label_b,
):
if use_color:
if line.startswith("+++") or line.startswith("---"):
line = "\x1b[1m" + line + "\x1b[0m"
elif line.startswith("+"):
line = "\x1b[32m" + line + "\x1b[0m"
elif line.startswith("-"):
line = "\x1b[31m" + line + "\x1b[0m"
elif line.startswith("@@"):
line = "\x1b[36m" + line + "\x1b[0m"
sys.stdout.write(line)
def _canonical_and_hash(spec: Any) -> tuple[str, str]:
canonical = _canonicalize(spec)
return canonical, hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def _diff_file_vs_file(path_a: Path, path_b: Path) -> int:
for p in (path_a, path_b):
if not p.exists():
print(f"falsify diff: {p} not found", file=sys.stderr)
return EXIT_BAD_SPEC
try:
spec_a = yaml.safe_load(path_a.read_text())
spec_b = yaml.safe_load(path_b.read_text())
except yaml.YAMLError as e:
print(f"falsify diff: YAML parse error: {e}", file=sys.stderr)
return EXIT_BAD_SPEC
yaml_a, hash_a = _canonical_and_hash(spec_a)
yaml_b, hash_b = _canonical_and_hash(spec_b)
if yaml_a == yaml_b:
print(f"Files are canonically identical @ {hash_a[:12]}")
return EXIT_PASS
_render_unified_diff(
yaml_a, yaml_b,
f"{path_a}@{hash_a[:12]}",
f"{path_b}@{hash_b[:12]}",
)
return EXIT_HASH_MISMATCH
def _diff_lock_vs_file(name: str) -> int:
claim_dir = FALSIFY_DIR / name
spec_path = claim_dir / "spec.yaml"
lock_path = claim_dir / "spec.lock.json"
if not spec_path.exists():
print(
f"falsify diff: {spec_path} not found — "
f"run `falsify init {name}` first",
file=sys.stderr,
)
return EXIT_BAD_SPEC
if not lock_path.exists():
print(
f"falsify diff: no lock at {lock_path} — "
f"run `falsify lock {name}` first",
file=sys.stderr,
)
return EXIT_BAD_SPEC
try:
lock_data = json.loads(lock_path.read_text())
except (OSError, json.JSONDecodeError) as e:
print(f"falsify diff: failed to read {lock_path}: {e}", file=sys.stderr)
return EXIT_BAD_SPEC
locked_hash = lock_data.get("spec_hash") if isinstance(lock_data, dict) else None
locked_yaml = (
lock_data.get("canonical_yaml") if isinstance(lock_data, dict) else None
)
try:
current_spec = yaml.safe_load(spec_path.read_text())
except yaml.YAMLError as e:
print(f"falsify diff: failed to parse {spec_path}: {e}", file=sys.stderr)
return EXIT_BAD_SPEC
current_yaml, current_hash = _canonical_and_hash(current_spec)
if not isinstance(locked_yaml, str):
if isinstance(locked_hash, str) and locked_hash == current_hash:
print(
f"Lock has no canonical_yaml field (legacy format). "
f"Spec is unchanged @ {current_hash[:12]}; nothing to diff."
)
print(
f"Re-lock with `falsify lock {name} --force` to populate "
f"canonical_yaml for future diffs.",
)
return EXIT_PASS
print(
f"falsify diff: legacy lock — no canonical_yaml stored and "
f"spec has drifted. Re-lock with "
f"`falsify lock {name} --force` to enable diff.",
file=sys.stderr,
)
return EXIT_BAD_SPEC
locked_short = (locked_hash or "?")[:12]
current_short = current_hash[:12]
if locked_yaml == current_yaml:
print(f"Lock and current spec are identical @ {current_short}")
return EXIT_PASS
_render_unified_diff(
locked_yaml,
current_yaml,
f"locked@{locked_short}",
f"current@{current_short}",
)
return EXIT_HASH_MISMATCH
def cmd_diff(args: argparse.Namespace) -> int:
if args.file_vs_file:
path_a, path_b = args.file_vs_file
return _diff_file_vs_file(Path(path_a), Path(path_b))
if not args.name:
print(
"falsify diff: name is required for lock-vs-file mode "
"(or pass --file-vs-file A B)",
file=sys.stderr,
)
return EXIT_BAD_SPEC
return _diff_lock_vs_file(args.name)
def _load_locked_spec(
claim_dir: Path,
) -> tuple[dict | None, dict | None, str]:
"""Return (spec, lock_data, error_message). On error, spec and lock are None."""
spec_path = claim_dir / "spec.yaml"
lock_path = claim_dir / "spec.lock.json"
if not lock_path.exists():
return None, None, (
f"no locked spec at {lock_path} — "
f"run `falsify lock {claim_dir.name}` first."
)
if not spec_path.exists():
return None, None, f"{spec_path} not found."
try:
spec = yaml.safe_load(spec_path.read_text())
except yaml.YAMLError as e:
return None, None, f"failed to parse {spec_path}: {e}"
try:
lock_data = json.loads(lock_path.read_text())
except json.JSONDecodeError as e:
return None, None, f"failed to parse {lock_path}: {e}"
return spec, lock_data, ""
def _verify_lock_hash(spec: dict, lock_data: dict) -> bool:
current_hash = hashlib.sha256(
_canonicalize(spec).encode("utf-8")
).hexdigest()
return lock_data.get("spec_hash") == current_hash
def _update_latest_pointer(claim_dir: Path, timestamp: str) -> None:
latest = claim_dir / "latest_run"
if latest.is_symlink() or latest.exists():
latest.unlink()
try:
latest.symlink_to(Path("runs") / timestamp)
except OSError:
latest.write_text(timestamp + "\n")
def _resolve_latest_run(claim_dir: Path) -> Path | None:
latest = claim_dir / "latest_run"
if latest.is_symlink():
target = latest.readlink()
if target.is_absolute():
return target
return (claim_dir / target).resolve()
if latest.is_file():
ts = latest.read_text().strip()
if ts:
return claim_dir / "runs" / ts
return None
def cmd_run(args: argparse.Namespace) -> int:
claim_dir = FALSIFY_DIR / args.name
spec, lock_data, err = _load_locked_spec(claim_dir)