File size: 58,711 Bytes
31780cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
"""CAEL Verified Reasoning: a synthetic dataset of reasoning problems whose answers are computed, not guessed.



Every example is produced by a small program that builds the situation, computes the answer exactly, and writes the

working. Nothing is generated by a neural network. Areas: multi-step arithmetic, dates and times, logic and

constraints, conflicting sources, memory over a chat, unanswerable questions, and ARC-style grid transformations.



    python generate.py --out data --n 200000 --seed 2026



Deterministic: the same seed gives the same dataset. Licence of the output: CC BY 4.0.

"""
import argparse
import calendar
import hashlib
import itertools
import json
import math
import random
from collections import Counter
from datetime import date, timedelta
from decimal import ROUND_HALF_UP, Decimal
from fractions import Fraction
from pathlib import Path

VERSION = '1.1'

# ------------------------------------------------------------------ vocabulary
NAMES = ['Ada', 'Ben', 'Cleo', 'Dev', 'Eli', 'Fay', 'Gus', 'Hana', 'Ivan', 'Jade', 'Kai', 'Lina', 'Milo', 'Nora', 'Omar', 'Pia', 'Quinn',
         'Rosa', 'Sam', 'Tara', 'Uma', 'Vik', 'Wren', 'Xena', 'Yusuf', 'Zoe', 'Aiko', 'Bruno', 'Chen', 'Dara', 'Emil', 'Farah', 'Gita',
         'Hugo', 'Iris', 'Jonas', 'Kofi', 'Leila', 'Mateo', 'Nina', 'Olu', 'Priya', 'Rafa', 'Sana', 'Theo', 'Ugo', 'Vera', 'Wei', 'Yara',
         'Zain', 'Amara', 'Basil', 'Carmen', 'Diego', 'Esme', 'Felix', 'Greta', 'Hiro', 'Ines', 'Jun', 'Kira', 'Luca', 'Maya', 'Nils',
         'Oona', 'Paolo', 'Rhea', 'Soren', 'Tess', 'Viktor']
ITEMS = [('apple', 'apples'), ('marble', 'marbles'), ('sticker', 'stickers'), ('book', 'books'), ('card', 'cards'), ('cookie', 'cookies'),
         ('pencil', 'pencils'), ('shell', 'shells'), ('stamp', 'stamps'), ('egg', 'eggs'), ('roll', 'rolls'), ('cupcake', 'cupcakes'),
         ('button', 'buttons'), ('ticket', 'tickets'), ('plant pot', 'plant pots'), ('candle', 'candles'), ('jar', 'jars'), ('tile', 'tiles'),
         ('bottle', 'bottles'), ('battery', 'batteries'), ('ribbon', 'ribbons'), ('bead', 'beads'), ('spool', 'spools'), ('brick', 'bricks')]
GOODS = [('coffee', 'coffees'), ('muffin', 'muffins'), ('sandwich', 'sandwiches'), ('notebook', 'notebooks'), ('pen', 'pens'), ('juice', 'juices'),
         ('bagel', 'bagels'), ('tea', 'teas'), ('salad', 'salads'), ('ticket', 'tickets'), ('magazine', 'magazines'), ('soap', 'soaps')]
CONTAINERS = [('bag', 'bags'), ('box', 'boxes'), ('tin', 'tins'), ('jar', 'jars'), ('crate', 'crates'), ('basket', 'baskets'), ('tray', 'trays')]
CURRENCIES = [('$', 'dollars'), ('€', 'euros'), ('£', 'pounds')]
DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
CITIES = ['Harbor', 'Ridge', 'Vale', 'Brook', 'Summit', 'Delta', 'Cove', 'Mesa', 'Fjord', 'Pine', 'Dune', 'Marsh']
ONES = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
        'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
TENS = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
ORD = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh']


def words(n):
    if n < 20:
        return ONES[n]
    if n < 100:
        return TENS[n // 10] + ('' if n % 10 == 0 else '-' + ONES[n % 10])
    return str(n)


def num(rng, n, p=0.3):
    """A whole number written as digits, or (sometimes) as words."""
    return words(n) if n < 100 and rng.random() < p else str(n)


def money(sym, cents):
    cents = int(cents)
    if cents % 100 == 0:
        return f'{sym}{cents // 100:,}'
    return f'{sym}{cents // 100:,}.{cents % 100:02d}'


def plural(pair, n):
    return pair[0] if n == 1 else pair[1]


def show_date(d, style=0):
    if style == 1:
        return f'{MONTHS[d.month - 1]} {d.day}, {d.year}'
    return f'{d.day} {MONTHS[d.month - 1]} {d.year}'


def hhmm(m, twelve=False):
    m %= 1440
    h, mi = divmod(m, 60)
    if twelve:
        return f'{(h - 1) % 12 + 1}:{mi:02d} {"am" if h < 12 else "pm"}'
    return f'{h:02d}:{mi:02d}'


def ex(category, task, turns, answer, steps, check, rng_id, extra=None):
    row = dict(category=category, task=task, messages=[dict(role='user', content=t) for t in turns], answer=answer,
               solution=' '.join(steps) if isinstance(steps, list) else steps, verification=check, generator=f'cael-verified-reasoning-{VERSION}')
    if extra:
        row.update(extra)
    return row


# ------------------------------------------------------------------ A. multi-step arithmetic
def a_change(rng):
    sym, word = rng.choice(CURRENCIES)
    picks = rng.sample(GOODS, rng.randint(2, 3))
    total, parts, items = 0, [], []
    for g in picks:
        k = rng.randint(1, 5)
        price = rng.choice([75, 95, 120, 150, 180, 200, 225, 250, 275, 320, 350, 400, 450, 499, 600])
        total += k * price
        items.append(f'{num(rng, k)} {plural(g, k)} at {money(sym, price)} each')
        parts.append(f'{k} × {money(sym, price)} = {money(sym, k * price)}')
    note = next(v for v in (1000, 2000, 5000, 10000) if v >= total + 1)
    lead = rng.choice(['I bought', 'We ordered', 'At the café I got', 'My basket had'])
    q = rng.choice([f'I pay with a {money(sym, note)} note. How much change should I get?',
                    f'If I hand over {money(sym, note)}, what change do I get back?'])
    turns = [f'{lead} ' + ', '.join(items[:-1]) + f' and {items[-1]}. {q}']
    return ex('arithmetic', 'change', turns, money(sym, note - total),
              parts + [f'Total {money(sym, total)}.', f'Change: {money(sym, note)} − {money(sym, total)} = {money(sym, note - total)}.'],
              'exact integer arithmetic in cents', rng)


def a_discount_tax(rng):
    sym, _ = rng.choice(CURRENCIES)
    price = rng.choice(range(2000, 30001, 500))
    d = rng.choice([10, 15, 20, 25, 30, 40, 50])
    t = rng.choice([5, 8, 10, 12, 20])
    after = Decimal(price) * (100 - d) / 100
    final = (after * (100 + t) / 100).quantize(Decimal('1'), rounding=ROUND_HALF_UP)
    item = rng.choice(['jacket', 'lamp', 'chair', 'bike helmet', 'kettle', 'backpack', 'rug', 'printer'])
    tax = rng.choice(['sales tax', 'VAT', 'tax'])
    turns = [rng.choice([f'A {item} costs {money(sym, price)}. It is {d}% off, and then {t}% {tax} is added to the reduced price. What is the final price?',
                         f'The {item} was {money(sym, price)} before a {d}% discount. I also pay {t}% {tax} on the discounted price. What do I pay in total?'])]
    return ex('arithmetic', 'discount_then_tax', turns, money(sym, int(final)),
              [f'{d}% off {money(sym, price)} leaves {money(sym, int(after.quantize(Decimal("1"), rounding=ROUND_HALF_UP)))}.',
               f'Adding {t}% {tax} gives {money(sym, int(final))} (rounded to the nearest cent).'], 'exact decimal arithmetic, rounded half up to cents', rng)


def a_packs(rng):
    sym, _ = rng.choice(CURRENCIES)
    it = rng.choice(ITEMS)
    size = rng.randint(3, 12)
    need = rng.randint(size + 1, size * 9)
    if need % size == 0:
        need += 1
    price = rng.choice([150, 200, 250, 300, 400, 450, 500, 650, 800])
    k = math.ceil(need / size)
    pack = rng.choice(['pack', 'box', 'sleeve', 'bundle'])
    packs = 'boxes' if pack == 'box' else pack + 's'
    turns = [f'{it[1].capitalize()} are only sold in {packs} of {num(rng, size)}, at {money(sym, price)} a {pack}. I need {need} {it[1]}. What is the least I can spend?']
    return ex('arithmetic', 'packs', turns, money(sym, k * price),
              [f'{need} ÷ {size} = {need / size:.2f}, so {k} {packs} are needed ({k - 1} would give only {(k - 1) * size}).',
               f'{k} × {money(sym, price)} = {money(sym, k * price)}.'], 'ceiling division, then multiplication', rng)


def a_owed(rng):
    sym, _ = rng.choice(CURRENCIES)
    n = rng.randint(3, 8)
    share = rng.randint(6, 60) * 100 // 4 * 4 // 1
    share = rng.choice(range(500, 6001, 25))
    total = share * n
    back = rng.randint(0, n - 2)
    left = n - 1 - back
    what = rng.choice(['dinner bill', 'taxi fare', 'concert tickets', 'cabin rental', 'pizza order'])
    turns = [f'{words(n).capitalize()} of us split the {what} equally. I paid the whole {money(sym, total)}.',
             (f'{words(back).capitalize()} of the others {"has" if back == 1 else "have"} already paid me back. ' if back else '') +
             f'How much do the rest still owe me altogether?']
    return ex('arithmetic', 'shares_owed', turns, money(sym, share * left),
              [f'Each share is {money(sym, total)} ÷ {n} = {money(sym, share)}.',
               f'I owe my own share; {back} {"has" if back == 1 else "have"} paid, so {left} shares are outstanding.',
               f'{left} × {money(sym, share)} = {money(sym, share * left)}.'], 'exact division and multiplication', rng)


def a_rate_idle(rng):
    r = rng.randint(2, 30)
    T = rng.randint(8, 90)
    I = rng.randint(1, T - 2)
    thing = rng.choice(['labels', 'cards', 'pages', 'bottles', 'bolts', 'cups', 'tiles'])
    machine = rng.choice(['printer', 'press', 'machine', 'filler', 'cutter'])
    turns = [f'The {machine} makes {num(rng, r)} {thing} a minute while it runs. It was booked for {T} minutes but stood idle for {I} of them. How many {thing} did it make?']
    return ex('arithmetic', 'rate_with_idle_time', turns, str(r * (T - I)),
              [f'Running time: {T} − {I} = {T - I} minutes.', f'{r} × {T - I} = {r * (T - I)} {thing}.'], 'exact integer arithmetic', rng)


def a_bags(rng):
    it = rng.choice(ITEMS)
    c = rng.choice(CONTAINERS)
    m = rng.randint(4, 12)
    n = rng.randint(m * 2, m * 12)
    k = rng.randint(1, max(1, n // 6))
    full, rem = divmod(n - k, m)
    turns = [f'I made {n} {it[1]} and kept {num(rng, k)} aside. The rest go {m} to a {c[0]}. How many full {c[1]} can I fill, and how many {it[1]} are left over?']
    return ex('arithmetic', 'full_containers', turns, f'{full} full {plural(c, full)}, {rem} left over',
              [f'{n} − {k} = {n - k}.', f'{n - k} ÷ {m} = {full} remainder {rem}.'], 'integer division with remainder', rng)


def a_tally(rng):
    it = rng.choice(ITEMS)
    a = rng.randint(20, 80)
    corr = a - rng.randint(1, 6)
    add = rng.randint(3, 30)
    use = rng.randint(1, corr + add - 1)
    who = rng.choice(NAMES)
    explain = a - corr
    turns = [f'I counted {a} {it[1]} in the first box.',
             f'Make that {corr}: {words(explain)} of them were not {it[1]} at all. {who} has {add} more {it[1]} of their own.',
             f'If we use {num(rng, use)} of them, how many {it[1]} do we have left?']
    return ex('arithmetic', 'corrected_tally', turns, str(corr + add - use),
              [f'The count was corrected to {corr} (the {explain} explains the correction, it is not a separate change).',
               f'{corr} + {add} = {corr + add}.', f'{corr + add} − {use} = {corr + add - use}.'], 'running count with a correction', rng)


def a_unit_price(rng):
    sym, _ = rng.choice(CURRENCIES)
    unit, scale = rng.choice([('g', 1000), ('ml', 1000)])
    big = 'kg' if unit == 'g' else 'litre'
    while True:
        q1, q2 = rng.choice([250, 400, 500, 750, 1000]), rng.choice([300, 600, 800, 900, 1200, 1500])
        p1, p2 = rng.randint(150, 900), rng.randint(150, 1400)
        u1, u2 = Fraction(p1, q1), Fraction(p2, q2)
        if u1 != u2 and abs(u1 - u2) / max(u1, u2) > Fraction(3, 100):
            break
    names = rng.sample(['Brand A', 'Brand B', 'Shop X', 'Shop Y', 'Pack 1', 'Pack 2'], 2)
    prod = rng.choice(['rice', 'oats', 'coffee beans', 'flour', 'sugar']) if unit == 'g' else rng.choice(['juice', 'olive oil', 'milk', 'shampoo', 'cold brew'])
    win = names[0] if u1 < u2 else names[1]
    per = lambda p, q: money(sym, int((Decimal(p) * scale / q).quantize(Decimal('1'), rounding=ROUND_HALF_UP)))
    turns = [f'{names[0]} sells {q1} {unit} of {prod} for {money(sym, p1)}. {names[1]} sells {q2} {unit} for {money(sym, p2)}. Which is cheaper per {big}?']
    return ex('arithmetic', 'unit_price', turns, win,
              [f'{names[0]}: {money(sym, p1)} ÷ {q1} {unit} = {per(p1, q1)} per {big}.', f'{names[1]}: {money(sym, p2)} ÷ {q2} {unit} = {per(p2, q2)} per {big}.',
               f'{win} is cheaper.'], 'exact rational comparison', rng)


def a_scale_recipe(rng):
    base = rng.choice([2, 3, 4, 6])
    want = rng.choice([x for x in (2, 3, 4, 5, 6, 8, 9, 10, 12) if x != base])
    qty = rng.choice([60, 90, 120, 150, 180, 240, 300, 360])
    ing = rng.choice(['flour', 'sugar', 'rice', 'butter', 'oats', 'cheese'])
    got = Fraction(qty * want, base)
    if got.denominator != 1:
        qty = base * rng.randint(20, 100)
        got = Fraction(qty * want, base)
    turns = [f'A recipe for {base} people needs {qty} g of {ing}. How much {ing} for {want} people?']
    return ex('arithmetic', 'recipe_scaling', turns, f'{got} g', [f'{qty} g ÷ {base} = {Fraction(qty, base)} g per person.', f'× {want} = {got} g.'],
              'exact proportional scaling', rng)


def a_pay(rng):
    sym, _ = rng.choice(CURRENCIES)
    rate = rng.choice(range(1000, 3001, 50))
    h1 = rng.choice([3, 4, 5, 6, 7, 8])
    h2 = rng.choice([2, 2.5, 3, 4, 4.5, 6])
    spend = rng.choice(range(1000, 8001, 500))
    pay = int(rate * (h1 + h2))
    name = rng.choice(NAMES)
    turns = [f'{name} earns {money(sym, rate)} an hour. They worked {h1} hours on Monday and {h2:g} hours on Tuesday, then spent {money(sym, spend)}. How much of that pay is left?']
    return ex('arithmetic', 'pay_minus_spending', turns, money(sym, pay - spend),
              [f'Hours: {h1} + {h2:g} = {h1 + h2:g}.', f'Pay: {h1 + h2:g} × {money(sym, rate)} = {money(sym, pay)}.', f'Left: {money(sym, pay)} − {money(sym, spend)} = {money(sym, pay - spend)}.'],
              'exact arithmetic in cents', rng)


# ------------------------------------------------------------------ B. dates and times
def rand_date(rng, a=1990, b=2035):
    start, end = date(a, 1, 1), date(b, 12, 31)
    return start + timedelta(days=rng.randint(0, (end - start).days))


def b_days_between(rng):
    d1 = rand_date(rng)
    d2 = d1 + timedelta(days=rng.randint(5, 400))
    st = rng.randint(0, 1)
    turns = [f'How many days are there from {show_date(d1, st)} to {show_date(d2, st)}?']
    return ex('dates_times', 'days_between', turns, f'{(d2 - d1).days} days',
              [f'Counting from {show_date(d1)} up to {show_date(d2)} (not counting the first day) gives {(d2 - d1).days} days.'], 'Python datetime', rng)


def b_weekday(rng):
    d = rand_date(rng, 1900, 2099)
    turns = [rng.choice([f'What day of the week was {show_date(d)}?', f'Which weekday is {show_date(d, 1)}?'])]
    return ex('dates_times', 'weekday_of_date', turns, DAYS[d.weekday()], [f'In the Gregorian calendar {show_date(d)} falls on a {DAYS[d.weekday()]}.'],
              'Python datetime (proleptic Gregorian)', rng)


def b_date_plus(rng):
    d0 = rand_date(rng)
    unit = rng.choice(['days', 'weeks', 'months', 'years'])
    n = rng.randint(1, 18) if unit != 'days' else rng.randint(10, 200)
    if unit == 'days':
        d1 = d0 + timedelta(days=n)
    elif unit == 'weeks':
        d1 = d0 + timedelta(weeks=n)
    elif unit == 'months':
        i = d0.year * 12 + d0.month - 1 + n
        y, mo = divmod(i, 12)
        d1 = date(y, mo + 1, min(d0.day, calendar.monthrange(y, mo + 1)[1]))
    else:
        try:
            d1 = d0.replace(year=d0.year + n)
        except ValueError:
            d1 = date(d0.year + n, 2, 28)
    thing = rng.choice(['My membership starts', 'The warranty begins', 'The trial period starts', 'My lease begins'])
    turns = [f'{thing} on {show_date(d0)} and lasts {n} {unit[:-1] if n == 1 else unit}. On what date does it end?']
    note = ' (the month is shorter, so the date is moved to its last day)' if unit in ('months', 'years') and d1.day != d0.day else ''
    return ex('dates_times', 'date_plus_period', turns, show_date(d1), [f'{show_date(d0)} + {n} {unit} = {show_date(d1)}{note}.'],
              'calendar arithmetic with month-end clamping', rng)


def b_span(rng):
    a = rng.randint(0, 1439)
    d = rng.randint(15, 600)
    b = (a + d) % 1440
    twelve = rng.random() < 0.5
    turns = [f'My recording starts at {hhmm(a, twelve)} and stops at {hhmm(b, twelve)}{" the next day" if a + d >= 1440 else ""}. How many minutes long is it?']
    return ex('dates_times', 'duration_minutes', turns, f'{d} minutes', [f'From {hhmm(a, twelve)} to {hhmm(b, twelve)} is {d // 60} h {d % 60} min = {d} minutes.'],
              'modular clock arithmetic', rng)


def b_zone(rng):
    c1, c2 = rng.sample(CITIES, 2)
    k = rng.randint(1, 10)
    day = rng.randint(0, 6)
    t = rng.randint(0, 1439)
    ahead = rng.random() < 0.5
    shift = -k if ahead else k   # time in c2 = time in c1 + shift... c1 is k ahead of c2 -> c2 = c1 - k
    total = day * 1440 + t + shift * 60
    d2, t2 = DAYS[(total // 1440) % 7], total % 1440
    rel = 'ahead of' if ahead else 'behind'
    turns = [f'In a story, {c1} clocks run {k} hours {rel} {c2} clocks. An event starts {DAYS[day]} at {hhmm(t)} in {c1}. What day and time is that in {c2}?']
    return ex('dates_times', 'time_zone', turns, f'{d2} {hhmm(t2)}',
              [f'{c2} is {k} hours {"behind" if ahead else "ahead of"} {c1}, so {"subtract" if ahead else "add"} {k} hours: {d2} {hhmm(t2)}.'],
              'modular arithmetic over a week', rng)


def b_end_time(rng):
    start = rng.randint(6 * 60, 22 * 60)
    dur = rng.randint(20, 200)
    ext = rng.choice([0, 0, 10, 15, 20, 30])
    what = rng.choice(['The film', 'The meeting', 'The workshop', 'The match', 'The bake'])
    twelve = rng.random() < 0.5
    turns = [f'{what} starts at {hhmm(start, twelve)} and runs {dur // 60} hours {dur % 60} minutes.' if dur >= 60 else
             f'{what} starts at {hhmm(start, twelve)} and runs {dur} minutes.']
    if ext:
        turns.append(f'It then overruns by {ext} minutes. When does it end?')
    else:
        turns[0] += ' When does it end?'
    end = start + dur + ext
    return ex('dates_times', 'end_time', turns, hhmm(end, twelve), [f'{hhmm(start, twelve)} + {dur} min' + (f' + {ext} min' if ext else '') + f' = {hhmm(end, twelve)}.'],
              'clock arithmetic', rng)


def b_age(rng):
    born = rand_date(rng, 1940, 2015)
    on = born + timedelta(days=rng.randint(400, 365 * 70))
    years = on.year - born.year - ((on.month, on.day) < (born.month, born.day))
    name = rng.choice(NAMES)
    turns = [f'{name} was born on {show_date(born)}. How old were they on {show_date(on)}?']
    return ex('dates_times', 'age_on_date', turns, str(years),
              [f'{on.year} − {born.year} = {on.year - born.year}; the birthday {"had not yet come" if (on.month, on.day) < (born.month, born.day) else "had already passed"} that year, so the age is {years}.'],
              'calendar comparison', rng)


def b_work(rng):
    a = rng.randint(7 * 60, 10 * 60)
    b = a + rng.randint(6 * 60, 10 * 60)
    brk = rng.choice([20, 30, 45, 60])
    w = b - a - brk
    turns = [f'My shift runs from {hhmm(a)} to {hhmm(b)} with a {brk}-minute break. How long do I actually work?']
    return ex('dates_times', 'work_minus_break', turns, f'{w // 60} h {w % 60} min', [f'{hhmm(a)} to {hhmm(b)} is {(b - a) // 60} h {(b - a) % 60} min; minus {brk} min = {w // 60} h {w % 60} min.'],
              'clock arithmetic', rng)


def b_weeks_days(rng):
    d = rng.randint(0, 6)
    w, k = rng.randint(1, 8), rng.randint(1, 6)
    turns = [f'The notice went up on a {DAYS[d]}. The change takes effect exactly {words(w)} week{"s" if w > 1 else ""} and {words(k)} day{"s" if k > 1 else ""} later. Which weekday is that?']
    return ex('dates_times', 'weekday_after', turns, DAYS[(d + 7 * w + k) % 7],
              [f'{w} week{"s" if w > 1 else ""} bring{"" if w > 1 else "s"} you back to {DAYS[d]}; {k} more day{"s" if k > 1 else ""} give{"" if k > 1 else "s"} {DAYS[(d + k) % 7]}.'], 'arithmetic mod 7', rng)


# ------------------------------------------------------------------ C. logic and constraints
def c_lineup(rng):
    n = rng.randint(3, 6)
    names = rng.sample(NAMES, n)
    order = names[:]
    rng.shuffle(order)
    pos = {nm: i + 1 for i, nm in enumerate(order)}
    scene = rng.choice([('stand in a queue', 'first', 'last', 'in front of', 'behind'), ('sit in a row', 'on the left end', 'on the right end', 'to the left of', 'to the right of'),
                        ('finished a race', 'first', 'last', 'before', 'after')])

    def facts():
        cands = []
        for a, b in itertools.permutations(names, 2):
            if pos[b] - pos[a] == 1:
                cands.append((f'{b} is directly {scene[4]} {a}.' if scene[0] != 'finished a race' else f'{b} finished right after {a}.', lambda p, a=a, b=b: p[b] - p[a] == 1))
            if pos[a] < pos[b]:
                cands.append((f'{a} is {scene[3]} {b}.' if scene[0] != 'finished a race' else f'{a} finished before {b}.', lambda p, a=a, b=b: p[a] < p[b]))
            if abs(pos[a] - pos[b]) > 1 and a < b:
                cands.append((f'{a} is not next to {b}.', lambda p, a=a, b=b: abs(p[a] - p[b]) != 1))
        for a in names:
            if pos[a] == 1:
                cands.append((f'{a} is {scene[1]}.', lambda p, a=a: p[a] == 1))
            if pos[a] == n:
                cands.append((f'{a} is {scene[2]}.', lambda p, a=a: p[a] == len(p)))
            if pos[a] not in (1, n):
                cands.append((f'{a} is not at either end.', lambda p, a=a: p[a] not in (1, len(p))))
        return cands
    pool = facts()
    rng.shuffle(pool)
    chosen = []
    perms = [dict(zip(p, range(1, n + 1))) for p in itertools.permutations(names)]
    target = rng.choice(names) if rng.random() < 0.5 else None
    ask_pos = rng.randint(1, n)
    for text, f in pool:
        chosen.append((text, f))
        perms = [p for p in perms if f(p)]
        if len(perms) == 1:
            break
    if len(perms) != 1:
        return None
    origin = 'from the front' if scene[0].startswith('stand') else 'from the left' if 'row' in scene[0] else 'from first place'
    if target:
        q = f'In which position is {target}, counting {origin}?'
        answer = ORD[pos[target] - 1]
    else:
        q = f'Who is in position {ask_pos}, counting {origin}?'
        answer = order[ask_pos - 1]
    intro = f'{words(n).capitalize()} people {scene[0]}: {", ".join(sorted(names))}.'
    turns = [intro + ' ' + ' '.join(t for t, _ in chosen) + ' ' + q]
    return ex('logic', 'lineup', turns, answer,
              [f'Trying every order of the {n} people, only one satisfies all the statements: ' + ', '.join(order) + '.', f'So the answer is {answer}.'],
              f'exhaustive search over {math.factorial(n)} orders; exactly one survives', rng)


def c_if_then(rng):
    p, c = rng.choice([('it rains', 'the match is cancelled', 'it did not rain', 'the match was not cancelled', 'did it rain', 'is the match cancelled'),
                       ('the alarm goes off', 'the dog barks', 'the alarm did not go off', 'the dog did not bark', 'did the alarm go off', 'did the dog bark'),
                       ('the shop is open', 'the lights are on', 'the shop is closed', 'the lights are off', 'is the shop open', 'are the lights on'),
                       ('you press the button', 'the door opens', 'nobody pressed the button', 'the door stayed shut', 'was the button pressed', 'did the door open'),
                       ('the kettle boils', 'it clicks off', 'the kettle did not boil', 'it did not click off', 'did the kettle boil', 'did it click off')])[:2], None
    rows = {('it rains', 'the match is cancelled'): ('it rained', 'it did not rain', 'the match was cancelled', 'the match was not cancelled', 'Did it rain?', 'Was the match cancelled?'),
            ('the alarm goes off', 'the dog barks'): ('the alarm went off', 'the alarm did not go off', 'the dog barked', 'the dog did not bark', 'Did the alarm go off?', 'Did the dog bark?'),
            ('the shop is open', 'the lights are on'): ('the shop is open', 'the shop is not open', 'the lights are on', 'the lights are not on', 'Is the shop open?', 'Are the lights on?'),
            ('you press the button', 'the door opens'): ('the button was pressed', 'the button was not pressed', 'the door opened', 'the door did not open', 'Was the button pressed?', 'Did the door open?'),
            ('the kettle boils', 'it clicks off'): ('the kettle boiled', 'the kettle did not boil', 'it clicked off', 'it did not click off', 'Did the kettle boil?', 'Did it click off?')}
    P, notP, C, notC, askP, askC = rows[p]
    form = rng.choice(['ponens', 'tollens', 'affirm_consequent', 'deny_antecedent'])
    if form == 'ponens':
        fact, ask, ans, why = P, askC, 'Yes', 'modus ponens: the condition holds, so the result follows'
    elif form == 'tollens':
        fact, ask, ans, why = notC, askP, 'No', 'modus tollens: the result did not happen, so the condition cannot have held'
    elif form == 'affirm_consequent':
        fact, ask, ans, why = C, askP, 'Cannot be determined', 'affirming the consequent is invalid: the result could have another cause'
    else:
        fact, ask, ans, why = notP, askC, 'Cannot be determined', 'denying the antecedent is invalid: the rule says nothing when the condition fails'
    turns = [f'If {p[0]}, {p[1]}. {fact[0].upper() + fact[1:]}. {ask}']
    return ex('logic', f'conditional_{form}', turns, ans, [f'Rule: if {p[0]}, then {p[1]}. Known: {fact}.', why[0].upper() + why[1:] + '.'],
              'propositional logic (truth-table)', rng)


def c_compare(rng):
    adj = rng.choice([('taller', 'shorter', 'tallest', 'shortest'), ('older', 'younger', 'oldest', 'youngest'), ('heavier', 'lighter', 'heaviest', 'lightest'),
                      ('faster', 'slower', 'fastest', 'slowest')])
    n = rng.randint(3, 5)
    order = rng.sample(NAMES, n)            # order[0] has the most
    edges = [(order[i], order[i + 1]) for i in range(n - 1)]
    if n >= 4 and rng.random() < 0.3:
        edges.pop(rng.randint(1, n - 3))    # break the chain in the middle: the extremes may become unknown
    facts = [f'{a} is {adj[0]} than {b}.' if rng.random() < 0.6 else f'{b} is {adj[1]} than {a}.' for a, b in edges]
    rng.shuffle(facts)
    ask_most = rng.random() < 0.5
    beaten = {b for a, b in edges} if ask_most else {a for a, b in edges}
    named = {x for e in edges for x in e}
    cands = sorted(x for x in named if x not in beaten)
    if len(cands) == 1:
        ans = cands[0]
        why = f'Only {ans} is never on the losing side of a comparison, so {ans} is the {adj[2] if ask_most else adj[3]}.'
    else:
        ans = 'Cannot be determined'
        why = f'The comparisons do not connect everyone: {" or ".join(cands)} could each be the {adj[2] if ask_most else adj[3]}.'
    turns = [' '.join(facts) + f' Who is the {adj[2] if ask_most else adj[3]}?']
    return ex('logic', 'comparisons', turns, ans, why, 'graph of the stated comparisons (sources/sinks)', rng)


def c_syllogism(rng):
    a, b, c, x = rng.choice([('dogs', 'mammals', 'animals', 'Rex'), ('roses', 'flowers', 'plants', 'this bloom'), ('squares', 'rectangles', 'shapes', 'this tile'),
                             ('violins', 'string instruments', 'instruments', 'this one'), ('sparrows', 'birds', 'animals', 'Pip')])
    form = rng.choice(['valid', 'undistributed', 'member', 'nonmember'])
    if form == 'valid':
        turns = [f'All {a} are {b}. All {b} are {c}. Are all {a} {c}?']
        return ex('logic', 'syllogism', turns, 'Yes', f'Every one of the {a} is among the {b}, and every one of those is among the {c}.', 'set inclusion', rng)
    if form == 'undistributed':
        turns = [f'All {a} are {c}. All {b} are {c}. Are all {b} {a}?']
        return ex('logic', 'syllogism', turns, 'Cannot be determined', f'Both groups are inside the {c}, but that says nothing about how the {a} and the {b} relate.',
                  'set inclusion (undistributed middle)', rng)
    if form == 'member':
        turns = [f'All {b} are {c}. {x[0].upper() + x[1:]} is one of the {b}. Is {x} one of the {c}?']
        return ex('logic', 'syllogism', turns, 'Yes', f'{x} is among the {b}, and all {b} are {c}.', 'set membership', rng)
    turns = [f'All {a} are {b}. {x[0].upper() + x[1:]} is not one of the {b}. Could {x} be one of the {a}?']
    return ex('logic', 'syllogism', turns, 'No', f'Every one of the {a} is among the {b}; {x} is not among the {b}, so it cannot be one of the {a}.', 'contrapositive', rng)


# ------------------------------------------------------------------ D. conflicting and changing information
def d_sources(rng):
    kind = rng.choice(['no_priority', 'priority', 'correction', 'withdrawn', 'hearsay', 'newest'])
    label = rng.choice(['Report', 'Log', 'Witness', 'Note', 'Sheet'])
    L1, L2 = rng.sample(['A', 'B', 'C', 'North', 'South', 'Red', 'Blue', '1', '2'], 2)
    topic, vals = rng.choice([('the gate opened at', ['08:12', '08:20', '08:21', '07:55']), ('the meeting is in room', ['Elm', 'Ash', 'Oak', 'Birch']),
                              ('the delivery came at', ['10:00', '14:00', '11:30', '16:15']), ('the visitor count was', ['120', '125', '118', '131']),
                              ('the bell rang', ['once', 'twice', 'three times'])])
    v1, v2, v3 = rng.sample(vals, 3) if len(vals) >= 3 else (vals[0], vals[1], vals[0])
    s1, s2 = f'{label} {L1}', f'{label} {L2}'
    base = f'{s1} says {topic} {v1}. {s2} says {topic} {v2}.'
    if kind == 'no_priority':
        turns = [base + ' Neither source is more reliable than the other. What do these sources establish?']
        return ex('conflicting_sources', kind, turns, 'Cannot be determined', f'The two sources disagree ({v1} vs {v2}) and neither has priority, so the answer stays open.',
                  'rule-based resolution', rng)
    if kind == 'priority':
        win = rng.choice([s1, s2])
        turns = [f'When the sources disagree, trust {win}.', base + ' What should we record?']
        return ex('conflicting_sources', kind, turns, v1 if win == s1 else v2, f'By the stated rule {win} wins, so the value is {v1 if win == s1 else v2}.', 'rule-based resolution', rng)
    if kind == 'correction':
        to = v2 if rng.random() < 0.5 else v3
        turns = [base, f'{s1} has now corrected its entry to {to}. Do the sources agree now?']
        same = to == v2
        return ex('conflicting_sources', kind, turns, f'Yes, {to}' if same else 'No',
                  f'After the correction {s1} says {to} and {s2} says {v2}; ' + ('they agree.' if same else 'they still disagree.'), 'rule-based resolution', rng)
    if kind == 'withdrawn':
        gone = rng.choice([s1, s2])
        stay, sv = (s2, v2) if gone == s1 else (s1, v1)
        turns = [base, f'{gone} has withdrawn its statement. Which source still has a claim on record, and what does it say?']
        return ex('conflicting_sources', kind, turns, f'{stay}: {topic} {sv}', f'{gone} withdrew, so only {stay} remains: {topic} {sv}.', 'rule-based resolution', rng)
    if kind == 'hearsay':
        n_first = rng.randint(1, 3)
        n_copy = rng.randint(1, 2)
        names = rng.sample(NAMES, n_first + n_copy)
        lines = [f'{nm} saw it personally and says {topic} {rng.choice(vals)}.' for nm in names[:n_first]]
        lines += [f'{nm} only heard it from {rng.choice(names[:n_first])}.' for nm in names[n_first:]]
        rng.shuffle(lines)
        turns = [' '.join(lines) + ' How many first-hand accounts are there?']
        return ex('conflicting_sources', kind, turns, str(n_first), f'{n_first} {"person" if n_first == 1 else "people"} saw it themselves; the other {n_copy} only repeat{"s" if n_copy == 1 else ""} someone else.', 'counting by provenance', rng)
    y1 = rng.randint(2015, 2021)
    y2 = y1 + rng.randint(1, 3)
    order = rng.random() < 0.5
    turns = [(f'The leaflet printed in {y1} says {topic} {v1}. The website updated in {y2} says {topic} {v2}.' if order else
              f'The website updated in {y2} says {topic} {v2}. The leaflet printed in {y1} says {topic} {v1}.') + ' Which is the current information?']
    return ex('conflicting_sources', kind, turns, v2, f'The website ({y2}) is newer than the leaflet ({y1}), so its value {v2} is current.', 'recency rule', rng)


# ------------------------------------------------------------------ E. memory over a chat
DISTRACT = ['The weather is nice today.', 'I also need to buy milk.', 'My cousin is visiting next week.', 'The coffee here is good.', 'I finally fixed my bike.',
            'Work was busy today.', 'I started a new book.', 'The train was a bit late.']


def e_memory(rng):
    kind = rng.choice(['latest_value', 'moved_time', 'set_changes', 'which_of_two', 'never_said', 'declined_offer'])
    d = rng.sample(DISTRACT, 2)
    if kind == 'latest_value':
        attr = rng.choice([('locker', lambda: str(rng.randint(1, 99))), ('seat', lambda: f'{rng.randint(1, 40)}{rng.choice("ABCDEF")}'),
                           ('username', lambda: rng.choice(['blue', 'red', 'green', 'quiet', 'swift']) + '_' + rng.choice(['fox', 'owl', 'cat', 'wren', 'bee'])),
                           ('desk', lambda: str(rng.randint(1, 60)))])
        a, b = attr[1](), attr[1]()
        while b == a:
            b = attr[1]()
        turns = [f'My {attr[0]} is {a}.', d[0], f'They changed my {attr[0]} to {b} this week.', d[1], f'What is my {attr[0]} now?']
        return ex('memory', kind, turns, b, f'The {attr[0]} was {a} and was later changed to {b}; the latest value is {b}.', 'latest-write wins', rng)
    if kind == 'moved_time':
        t = rng.randint(8, 18) * 60 + rng.choice([0, 30])
        dt = rng.choice([15, 30, 45, 60, 90, 120])
        sign = rng.choice([1, -1])
        ev = rng.choice(['meeting', 'appointment', 'call', 'class'])
        moved = 'pushed back' if sign > 0 else 'moved forward'
        turns = [f'The {ev} is at {hhmm(t, True)}.', d[0], f'The {ev} got {moved} by {dt} minutes.', f'When is the {ev} now?']
        return ex('memory', kind, turns, hhmm(t + sign * dt, True), f'{hhmm(t, True)} {"+" if sign > 0 else "−"} {dt} min = {hhmm(t + sign * dt, True)}.', 'clock arithmetic on the latest state', rng)
    if kind == 'set_changes':
        pool = rng.sample(['guitar', 'violin', 'flute', 'drum', 'piano', 'cello', 'trumpet', 'harp'], 5)
        have = pool[:3]
        gone = rng.choice(have)
        new = pool[3]
        final = [x for x in have if x != gone] + [new]
        turns = [f'I have a {have[0]}, a {have[1]} and a {have[2]}.', f'I sold the {gone}.', d[0], f'I was given a {new}.', 'Which instruments do I have now?']
        return ex('memory', kind, turns, ', '.join(final), f'Start: {", ".join(have)}. Remove {gone}. Add {new}. Now: {", ".join(final)}.', 'set updates in order', rng)
    if kind == 'which_of_two':
        a, b = rng.sample(['Leeds', 'York', 'Bath', 'Oslo', 'Porto', 'Lyon', 'Graz', 'Turku'], 2)
        ask = rng.choice(['grow up', 'live'])
        turns = [f'I live in {a}.', d[0], f'I grew up in {b}.', f'Where did I {ask}?' if ask == 'grow up' else 'Where do I live?']
        return ex('memory', kind, turns, b if ask == 'grow up' else a, f'You live in {a} and grew up in {b}.', 'attribute lookup by relation', rng)
    if kind == 'never_said':
        item = rng.choice(['wool hat', 'striped apron', 'blue lamp', 'old map', 'tea set'])
        turns = [f'I bought a {item} at the market.', f'It came wrapped in brown paper.', 'How much did I tell you I paid for it?']
        return ex('memory', kind, turns, 'You did not say', 'No price was mentioned anywhere in the conversation.', 'absence check over the conversation', rng)
    day1, day2 = rng.sample(DAYS[:5], 2)
    turns = [f'My dentist appointment is on {day1}.', f'They offered me {day2} instead.', d[0], 'I said no. Which day is my appointment?']
    return ex('memory', kind, turns, day1, f'The offer of {day2} was declined, so the original {day1} stands.', 'state update only on acceptance', rng)


# ------------------------------------------------------------------ F. unanswerable or trick questions
def f_unanswerable(rng):
    kind = rng.choice(['missing_info', 'hidden_outcome', 'contradiction', 'too_few_clues', 'future_count', 'emptied'])
    if kind == 'missing_info':
        v = rng.choice(['train', 'bus', 'ferry', 'plane'])
        t = hhmm(rng.randint(6 * 60, 22 * 60))
        turns = [f'The {v} leaves at {t}. At what time does it arrive?']
        return ex('unanswerable', kind, turns, 'Cannot be determined', 'Only the departure time is given; without the journey time or timetable the arrival time is unknown.', 'missing premise', rng)
    if kind == 'hidden_outcome':
        who = rng.choice(NAMES)
        turns = [rng.choice([f'{who} rolled a die behind a screen. What number is showing?', f'{who} shuffled a deck and put it face down. Which card is on top?',
                             f'{who} flipped a coin and covered it. Is it heads or tails?', f'{who} drew a marble from a bag of {rng.randint(3, 12)} mixed colours without looking. What colour is it?',
                             f'{who} spun a wheel with {rng.randint(6, 20)} numbers while I looked away. Where did it stop?',
                             f'{who} hid a coin in one of {rng.randint(2, 6)} cups and shuffled them. Which cup is it under?'])]
        return ex('unanswerable', kind, turns, 'Cannot be determined', 'The outcome is random and hidden; nothing in the question reveals it.', 'hidden random outcome', rng)
    if kind == 'contradiction':
        n = rng.randint(2, 9)
        turns = [f'My box is completely empty and contains {n} apples. How many apples are in it?']
        return ex('unanswerable', kind, turns, 'Contradictory premise', 'A box cannot be completely empty and contain apples; the question contradicts itself.', 'contradiction check', rng)
    if kind == 'too_few_clues':
        a = rng.randint(1, 40)
        b = a + rng.randint(6, 15)
        par = rng.choice(['odd', 'even'])
        cands = [x for x in range(a + 1, b) if (x % 2 == 1) == (par == 'odd')]
        turns = [f'I picked a whole number strictly between {a} and {b}. It is {par}. Which number is it?']
        return ex('unanswerable', kind, turns, 'Cannot be determined', f'{len(cands)} numbers fit: {", ".join(map(str, cands))}.', 'enumeration of candidates', rng)
    if kind == 'future_count':
        turns = [rng.choice(['We are holding a garden party next August. Exactly how many guests will come?', 'How many people will visit the museum next Tuesday?'])]
        return ex('unanswerable', kind, turns, 'Cannot be determined', 'Future attendance depends on choices not yet made; it can be estimated, not known.', 'future event', rng)
    n = rng.randint(3, 9)
    it = rng.choice(ITEMS)
    turns = [f'The drawer held exactly {words(n)} {it[1]}. I took out all {words(n)} and put nothing back. What colour is the {it[0]} still in the drawer?']
    return ex('unanswerable', kind, turns, 'There is none', f'All {n} were removed, so no {it[0]} is left.', 'false premise', rng)


# ------------------------------------------------------------------ G. ARC-style grid transformations
def rand_grid(rng, h, w, density, colours):
    return [[rng.choice(colours) if rng.random() < density else 0 for _ in range(w)] for _ in range(h)]


def objects4(g):
    h, w = len(g), len(g[0])
    seen, out = set(), []
    for y in range(h):
        for x in range(w):
            if g[y][x] and (y, x) not in seen:
                c, stack, cells = g[y][x], [(y, x)], []
                seen.add((y, x))
                while stack:
                    a, b = stack.pop()
                    cells.append((a, b))
                    for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                        na, nb = a + dy, b + dx
                        if 0 <= na < h and 0 <= nb < w and (na, nb) not in seen and g[na][nb] == c:
                            seen.add((na, nb))
                            stack.append((na, nb))
                out.append(cells)
    return out


def t_flip_h(g): return [list(reversed(r)) for r in g]
def t_flip_v(g): return [list(r) for r in reversed(g)]
def t_rot90(g): return [list(r) for r in zip(*g[::-1])]
def t_transpose(g): return [list(r) for r in zip(*g)]


def t_gravity(g):
    h, w = len(g), len(g[0])
    out = [[0] * w for _ in range(h)]
    for x in range(w):
        col = [g[y][x] for y in range(h) if g[y][x]]
        for i, v in enumerate(reversed(col)):
            out[h - 1 - i][x] = v
    return out


def t_scale(k):
    return lambda g: [[v for v in r for _ in range(k)] for r in g for _ in range(k)]


def t_tile(g):
    return [r + r for r in g] + [r + r for r in g]


def t_mirror(g):
    return [r + list(reversed(r)) for r in g]


def t_border(c):
    def f(g):
        h, w = len(g), len(g[0])
        return [[c if y in (0, h - 1) or x in (0, w - 1) else g[y][x] for x in range(w)] for y in range(h)]
    return f


def t_recolour(m):
    return lambda g: [[m.get(v, v) for v in r] for r in g]


def t_crop_largest(g):
    objs = objects4(g)
    if not objs:
        raise ValueError
    sizes = sorted(len(o) for o in objs)
    if len(sizes) > 1 and sizes[-1] == sizes[-2]:
        raise ValueError
    o = max(objs, key=len)
    ys, xs = [p[0] for p in o], [p[1] for p in o]
    cells = set(o)
    return [[g[y][x] if (y, x) in cells else 0 for x in range(min(xs), max(xs) + 1)] for y in range(min(ys), max(ys) + 1)]


def t_stamp(c):
    def f(g):
        h, w = len(g), len(g[0])
        out = [r[:] for r in g]
        for y in range(h):
            for x in range(w):
                if g[y][x]:
                    for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                        yy, xx = y + dy, x + dx
                        if 0 <= yy < h and 0 <= xx < w and g[yy][xx] == 0:
                            out[yy][xx] = c
        return out
    return f


def t_span_rows(g):
    out = [r[:] for r in g]
    for y, r in enumerate(g):
        for c in set(r) - {0}:
            xs = [x for x, v in enumerate(r) if v == c]
            if len(xs) >= 2:
                for x in range(xs[0] + 1, xs[-1]):
                    if r[x] == 0:
                        if out[y][x] not in (0, c):
                            raise ValueError
                        out[y][x] = c
    return out


GRID_RULES = [
    ('flip_h', 'Mirror the grid left to right.', lambda rng: t_flip_h, 'any'),
    ('flip_v', 'Mirror the grid top to bottom.', lambda rng: t_flip_v, 'any'),
    ('rotate_90', 'Rotate the grid 90 degrees clockwise.', lambda rng: t_rot90, 'any'),
    ('transpose', 'Swap rows and columns (reflect across the main diagonal).', lambda rng: t_transpose, 'any'),
    ('gravity_down', 'Every coloured cell falls to the bottom of its column, keeping order.', lambda rng: t_gravity, 'sparse'),
    ('scale_2', 'Scale the grid up by 2: each cell becomes a 2×2 block.', lambda rng: t_scale(2), 'small'),
    ('scale_3', 'Scale the grid up by 3: each cell becomes a 3×3 block.', lambda rng: t_scale(3), 'tiny'),
    ('tile_2x2', 'Tile the grid twice across and twice down.', lambda rng: t_tile, 'small'),
    ('mirror_concat', 'Append the left-right mirror image to the right of the grid.', lambda rng: t_mirror, 'any'),
    ('border', 'Draw a one-cell frame of colour {c} around the edge of the grid.', lambda rng: ('c', rng.randint(1, 9)), 'any'),
    ('recolour', 'Recolour: {m}.', lambda rng: ('m', None), 'any'),
    ('crop_largest', 'Cut out the largest single-colour object, keeping only its cells.', lambda rng: t_crop_largest, 'objects'),
    ('stamp_cross', 'Every coloured cell gets colour {c} on its empty up, down, left and right neighbours.', lambda rng: ('s', rng.randint(1, 9)), 'very_sparse'),
    ('span_rows', 'In each row, fill the gap between the first and last cell of the same colour with that colour.', lambda rng: t_span_rows, 'row_pairs'),
]


def g_arc(rng):
    name, desc, make, kind = rng.choice(GRID_RULES)
    made = make(rng)
    colours = rng.sample(range(1, 10), rng.randint(1, 3))
    if isinstance(made, tuple) and made[0] == 'c':
        c = made[1]
        fn, desc = t_border(c), desc.format(c=c)
    elif isinstance(made, tuple) and made[0] == 's':
        c = made[1]
        colours = [x for x in colours if x != c] or [((c % 9) + 1)]
        fn, desc = t_stamp(c), desc.format(c=c)
    elif isinstance(made, tuple) and made[0] == 'm':
        src = colours[:]
        dst = rng.sample([x for x in range(1, 10) if x not in src], len(src))
        m = dict(zip(src, dst))
        fn, desc = t_recolour(m), desc.format(m=', '.join(f'{a}→{b}' for a, b in m.items()))
    else:
        fn = made
    pairs = []
    for _ in range(4):
        for _attempt in range(30):
            if kind == 'tiny':
                h, w = rng.randint(2, 4), rng.randint(2, 4)
            elif kind == 'small':
                h, w = rng.randint(2, 6), rng.randint(2, 6)
            else:
                h, w = rng.randint(3, 10), rng.randint(3, 10)
            dens = {'sparse': 0.3, 'very_sparse': 0.12, 'objects': 0.45, 'row_pairs': 0.18}.get(kind, rng.uniform(0.2, 0.6))
            g = rand_grid(rng, h, w, dens, colours)
            if kind == 'row_pairs':
                for r in g:
                    if rng.random() < 0.5:
                        c = rng.choice(colours)
                        a, b = sorted(rng.sample(range(w), 2))
                        r[a] = r[b] = c
            try:
                o = fn(g)
            except ValueError:
                continue
            if o != g and any(v for r in g for v in r):
                pairs.append((g, o))
                break
        else:
            return None
    show = lambda g: '\n'.join(' '.join(map(str, r)) for r in g)
    demo = '\n\n'.join(f'Example {i + 1}\nInput:\n{show(a)}\nOutput:\n{show(b)}' for i, (a, b) in enumerate(pairs[:3]))
    test_in, test_out = pairs[3]
    turns = [f'{demo}\n\nTest input:\n{show(test_in)}\n\nWhat is the test output grid?']
    return ex('arc_grids', name, turns, show(test_out), f'Rule: {desc} Applied to the test input it gives the grid above.',
              'rule applied programmatically to every pair', rng, extra=dict(grids=dict(train=[dict(input=a, output=b) for a, b in pairs[:3]],
                                                                                         test=dict(input=test_in, output=test_out)), rule=name))


# ------------------------------------------------------------------ H. composite multi-step tasks (harder)
def h_shift_pay(rng):
    sym, _ = rng.choice(CURRENCIES)
    a = rng.randint(6 * 60, 11 * 60) // 5 * 5
    b = a + rng.randint(5 * 60, 11 * 60) // 5 * 5
    brk = rng.choice([15, 20, 30, 45, 60])
    rate = rng.choice(range(1200, 3601, 60))           # per hour, divisible by 60 so per-minute pay is whole cents
    worked = b - a - brk
    pay = rate * worked // 60
    turns = [f'I worked from {hhmm(a)} to {hhmm(b)} with an unpaid {brk}-minute break. I am paid {money(sym, rate)} per hour. How much did I earn?']
    return ex('composite', 'shift_pay', turns, money(sym, pay),
              [f'{hhmm(a)} to {hhmm(b)} is {b - a} minutes; minus {brk} = {worked} minutes.', f'{worked} minutes × {money(sym, rate)} per 60 minutes = {money(sym, pay)}.'],
              'clock arithmetic then exact money arithmetic', rng)


def h_rental(rng):
    sym, _ = rng.choice(CURRENCIES)
    d1 = rand_date(rng, 2015, 2032)
    nights = rng.randint(2, 40)
    d2 = d1 + timedelta(days=nights)
    rate = rng.choice(range(2500, 25001, 250))
    deposit = rng.choice(range(5000, 50001, 2500))
    total = nights * rate
    thing = rng.choice(['cabin', 'flat', 'van', 'boat', 'studio'])
    turns = [f'I rent a {thing} from {show_date(d1)} to {show_date(d2)} at {money(sym, rate)} per night. I already paid a {money(sym, deposit)} deposit that counts towards the total. How much is still due?']
    due = total - deposit
    ans = money(sym, due) if due >= 0 else f'Nothing; {money(sym, -due)} should be refunded'
    return ex('composite', 'rental_due', turns, ans,
              [f'{show_date(d1)} to {show_date(d2)} is {nights} nights.', f'{nights} × {money(sym, rate)} = {money(sym, total)}.',
               f'{money(sym, total)} − {money(sym, deposit)} = {money(sym, due) if due >= 0 else "−" + money(sym, -due)}.'],
              'calendar arithmetic then exact money arithmetic', rng)


def h_flight(rng):
    c1, c2 = rng.sample(CITIES, 2)
    k = rng.randint(1, 9)
    ahead = rng.random() < 0.5
    day = rng.randint(0, 6)
    dep = rng.randint(0, 1439) // 5 * 5
    dur = rng.randint(60, 14 * 60) // 5 * 5
    shift = k if ahead else -k                          # c2 is k hours ahead of / behind c1
    arr = day * 1440 + dep + dur + shift * 60
    turns = [f'In a story, {c2} clocks are {k} hours {"ahead of" if ahead else "behind"} {c1} clocks. A flight leaves {c1} on {DAYS[day]} at {hhmm(dep)} local time and the flight takes {dur // 60} h {dur % 60} min. What day and local time does it land in {c2}?']
    return ex('composite', 'flight_arrival', turns, f'{DAYS[(arr // 1440) % 7]} {hhmm(arr % 1440)}',
              [f'Departure {DAYS[day]} {hhmm(dep)} + {dur // 60} h {dur % 60} min = {DAYS[((day * 1440 + dep + dur) // 1440) % 7]} {hhmm((dep + dur) % 1440)} in {c1} time.',
               f'{"Add" if ahead else "Subtract"} {k} hours for {c2}: {DAYS[(arr // 1440) % 7]} {hhmm(arr % 1440)}.'],
              'clock arithmetic over a week, then a time-zone shift', rng)


def h_budget_days(rng):
    sym, _ = rng.choice(CURRENCIES)
    d1 = rand_date(rng, 2016, 2032)
    d2 = d1 + timedelta(days=rng.randint(7, 90))
    daily = rng.choice(range(500, 6001, 50))
    have = rng.choice(range(10000, 400001, 1000))
    days = (d2 - d1).days + 1
    need = days * daily
    enough = have >= need
    turns = [f'I will travel from {show_date(d1)} to {show_date(d2)}, both days included, and budget {money(sym, daily)} a day. I have saved {money(sym, have)}. Is that enough, and by how much am I over or short?']
    ans = f'Yes, {money(sym, have - need)} to spare' if enough else f'No, {money(sym, need - have)} short'
    return ex('composite', 'trip_budget', turns, ans,
              [f'{show_date(d1)} to {show_date(d2)} inclusive is {days} days.', f'{days} × {money(sym, daily)} = {money(sym, need)}.',
               f'Saved {money(sym, have)}: ' + (f'{money(sym, have - need)} to spare.' if enough else f'{money(sym, need - have)} short.')],
              'inclusive calendar count then exact money arithmetic', rng)


# ------------------------------------------------------------------ wording variety and difficulty
LEADS = ['', '', '', 'Quick question: ', 'Can you help me with this? ', "I'm trying to work something out. ", 'Here is a puzzle. ', 'Help me check this: ']
TAILS = ['', '', '', ' Please show your working.', ' Just give me the answer.', ' Explain briefly.', ' I want to be sure I have this right.']


def vary(row, rng):
    """Wrap the first and last user turns in varied, natural phrasing (the problem itself is unchanged)."""
    if row['category'] == 'arc_grids':
        return row
    msgs = row['messages']
    lead, tail = rng.choice(LEADS), rng.choice(TAILS)
    if lead:
        msgs[0]['content'] = lead + msgs[0]['content']          # the original sentence keeps its capital letter
    if tail:
        msgs[-1]['content'] = msgs[-1]['content'] + tail
    return row


def difficulty(row):
    """A heuristic level: 1 (one step) to 5 (many steps or a large search). Documented in the card."""
    t, cat = row['task'], row['category']
    steps = row['solution'].count('.') + row['solution'].count(';')
    if cat == 'arc_grids':
        g = row['grids']['test']['input']
        cells = len(g) * len(g[0])
        hard = {'crop_largest': 1, 'span_rows': 1, 'stamp_cross': 1, 'gravity_down': 1, 'recolour': 0}.get(t, 0)
        return min(5, 1 + (cells > 20) + (cells > 50) + hard)
    if t == 'lineup':
        n = len(row['messages'][0]['content'].split(':', 1)[1].split('.', 1)[0].split(','))
        return min(5, n - 1)
    if cat == 'composite':
        return 4 if t != 'trip_budget' else 5
    if t in ('comparisons', 'corrected_tally', 'shares_owed', 'discount_then_tax', 'flight_arrival', 'time_zone', 'date_plus_period', 'age_on_date', 'weekday_after'):
        return 3
    if cat in ('unanswerable',) or t.startswith('conditional_affirm') or t.startswith('conditional_deny') or row['answer'] == 'Cannot be determined':
        return 3
    return max(1, min(3, steps - 1))


# ------------------------------------------------------------------ build
MIX = [  # (generator, share)
    (a_change, .04), (a_discount_tax, .035), (a_packs, .03), (a_owed, .03), (a_rate_idle, .025), (a_bags, .03), (a_tally, .025), (a_unit_price, .03),
    (a_scale_recipe, .02), (a_pay, .025),
    (b_days_between, .035), (b_weekday, .035), (b_date_plus, .03), (b_span, .025), (b_zone, .025), (b_end_time, .03), (b_age, .03), (b_work, .02), (b_weeks_days, .02),
    (c_lineup, .08), (c_if_then, .035), (c_compare, .035), (c_syllogism, .02),
    (d_sources, .09),
    (e_memory, .10),
    (f_unanswerable, .06),
    (g_arc, .12),
    (h_shift_pay, .03), (h_rental, .03), (h_flight, .03), (h_budget_days, .03),
]


def key_of(row):
    text = ' || '.join(m['content'] for m in row['messages']).lower()
    return hashlib.sha256(text.encode()).hexdigest()


def build(n, seed, exclude=frozenset(), keep=None, quota=None, attempts=8):
    """Generate up to n unique rows. `keep` filters rows (for the hard set); `quota` caps rows per category."""
    weights = [w for _, w in MIX]
    rows, seen, stats = [], set(exclude), Counter()
    per_cat = Counter()
    master = random.Random(seed)
    i = 0
    while len(rows) < n and i < n * attempts:
        i += 1
        gen = master.choices([g for g, _ in MIX], weights=weights)[0]
        rng = random.Random(f'{seed}:{i}')
        try:
            row = gen(rng)
        except (ValueError, IndexError, ZeroDivisionError):
            row = None
        if row is None:
            stats['rejected'] += 1
            continue
        k = key_of(row)                                  # duplicates are judged on the problem itself, before rewording
        if k in seen:
            stats['duplicates'] += 1
            continue
        row['difficulty'] = difficulty(row)
        if keep and not keep(row):
            continue
        if quota and per_cat[row['category']] >= quota.get(row['category'], 0):
            continue
        seen.add(k)
        vary(row, rng)
        row['grids'] = json.dumps(row['grids']) if 'grids' in row else ''
        row.setdefault('rule', '')
        row['key'] = k
        rows.append(row)
        per_cat[row['category']] += 1
    return rows, stats


COLUMNS = ['id', 'category', 'task', 'difficulty', 'messages', 'answer', 'solution', 'verification', 'grids', 'rule', 'generator']


def write(rows, out, name, per=250000):
    import pyarrow as pa
    import pyarrow.parquet as pq
    parts = max(1, math.ceil(len(rows) / per))
    for p in range(parts):
        chunk = rows[p * per:(p + 1) * per]
        table = pa.Table.from_pylist([{c: r[c] for c in COLUMNS} for r in chunk])
        pq.write_table(table, out / f'{name}-{p:05d}-of-{parts:05d}.parquet', compression='zstd')


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--out', default='data')
    ap.add_argument('--n', type=int, default=2000000, help='rows in train + test')
    ap.add_argument('--hard', type=int, default=1500, help='rows in the separate hard evaluation set')
    ap.add_argument('--seed', type=int, default=2026)
    ap.add_argument('--test-share', type=float, default=0.01)
    args = ap.parse_args()
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    rows, stats = build(args.n, args.seed)
    split = random.Random(args.seed + 1)
    test_ids = set(split.sample(range(len(rows)), int(len(rows) * args.test_share)))
    train, test = [], []
    for j, r in enumerate(rows):
        r['id'] = f'cvr-{j:07d}'
        (test if j in test_ids else train).append(r)
    # the hard set: a different seed, only difficulty >= 3, balanced by category, never a problem that is in train or test
    cats = sorted({r['category'] for r in rows})
    quota = {c: math.ceil(args.hard / len(cats)) for c in cats}
    hard, _ = build(args.hard, args.seed + 7919, exclude=frozenset(r['key'] for r in rows), keep=lambda r: r['difficulty'] >= 3,
                    quota=quota, attempts=400)
    for j, r in enumerate(hard):
        r['id'] = f'cvr-hard-{j:05d}'
    write(train, out, 'train')
    write(test, out, 'test')
    write(hard, out, 'hard')
    summary = dict(version=VERSION, seed=args.seed, train=len(train), test=len(test), hard=len(hard),
                   by_category=dict(Counter(r['category'] for r in rows).most_common()),
                   hard_by_category=dict(Counter(r['category'] for r in hard).most_common()),
                   difficulty=dict(sorted(Counter(r['difficulty'] for r in rows).items())),
                   duplicates_skipped=stats['duplicates'], by_task=dict(Counter(r['task'] for r in rows).most_common()))
    (out / 'stats.json').write_text(json.dumps(summary, indent=1), encoding='utf-8')
    print(json.dumps({k: v for k, v in summary.items() if k != 'by_task'}, indent=1))


if __name__ == '__main__':
    main()