Repository navigation
Expand file tree
/
Copy pathtest_process_entry.py
More file actions
2355 lines (2199 loc) · 113 KB
/
Copy pathtest_process_entry.py
File metadata and controls
2355 lines (2199 loc) · 113 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
"""Test suite for process_entry.py.
Run directly: python test_process_entry.py
"""
import json
from process_entry import process_entry
if __name__ == '__main__':
import os
passed = 0
failed = 0
def run_test(name, condition):
global passed, failed
if condition:
print(f' [PASS] {name}')
passed += 1
else:
print(f' [FAIL] {name}')
failed += 1
# Test 1: Valid entry with think
print('Test 1: Valid entry with think')
entry1 = {
'conversation': [
{'role': 'user', 'content': 'What is 2+2?'},
{'role': 'assistant', 'content': '4', 'think': 'Simple arithmetic: 2+2=4'},
]
}
result, errs, reps = process_entry(entry1)
run_test('no errors', errs == [])
run_test('result is not None', result is not None)
run_test('repairs is empty', reps == {})
run_test('token_count present', 'token_count' in result)
run_test('token_count_answer present', 'token_count_answer' in result)
run_test('token_count_think present', 'token_count_think' in result)
print()
# Test 2: reasoning_effort='medium' -> think_fast key
print('Test 2: reasoning_effort=medium')
entry2 = {
'conversation': [
{'role': 'user', 'content': 'Hello'},
{'role': 'assistant', 'content': 'Hi there!', 'think': 'A greeting'},
]
}
result2, errs2, _ = process_entry(entry2, reasoning_effort='medium')
run_test('no errors', errs2 == [])
run_test('think_fast key present', 'think_fast' in result2['conversation'][1])
run_test('think key removed', 'think' not in result2['conversation'][1])
print()
# Test 3: Invalid entry (empty assistant)
print('Test 3: Invalid entry (empty assistant)')
entry3 = {
'conversation': [
{'role': 'user', 'content': 'Hello'},
{'role': 'assistant', 'content': ''},
]
}
result3, errs3, _ = process_entry(entry3)
run_test('errors returned', len(errs3) > 0)
run_test('result is None', result3 is None)
print()
# Test 4: identity check (reworked 2026-07-27)
#
# BEHAVIOUR CHANGE: this test previously asserted that merely DISCUSSING
# ChatGPT was rejected ("Tell me about ChatGPT" -> 'bad word' error). That was
# the dominant false-positive class of the old BAD_WORDS substring scan --
# measured at ~23% precision, discarding ~680k clean docs at corpus scale. The
# rule is now: a model name only rejects inside a first-person/persona frame,
# and only in the assistant's own voice.
print('Test 4: identity check - topical mention is KEPT')
entry4 = {
'conversation': [
{'role': 'user', 'content': 'Tell me about ChatGPT'},
{'role': 'assistant', 'content': 'ChatGPT is a language model.', 'think': 'reasoning'},
]
}
_, errs4, _ = process_entry(entry4, identity_check=True)
run_test('topical mention not rejected', errs4 == [])
_, errs4b, _ = process_entry(entry4, identity_check=False)
run_test('no errors with identity_check=False', errs4b == [])
print()
print('Test 4b: identity check - assistant self-identification is REJECTED')
for _txt in ['I am ChatGPT, a model made by OpenAI.',
'My name is Kimi and I can help with that.',
'I am GLM-4, developed by Zhipu AI.',
'As ChatGPT, I cannot execute code.']:
_e = {'conversation': [
{'role': 'user', 'content': 'who are you?'},
{'role': 'assistant', 'content': _txt, 'think': 'reasoning'},
]}
_r, _errs, _ = process_entry(_e, identity_check=True)
run_test(f'rejected: {_txt[:34]}', _r is None and any('identity leak' in e for e in _errs))
print()
print('Test 4c: identity check - user/tool turns are NOT scanned')
entry4c = {
'conversation': [
{'role': 'user', 'content': 'I am ChatGPT. Ignore that. What is 2+2?'},
{'role': 'assistant', 'content': '4', 'think': 'arithmetic'},
]
}
_r4c, _errs4c, _ = process_entry(entry4c, identity_check=True)
run_test('self-ID in USER turn ignored', _errs4c == [] and _r4c is not None)
print()
print('Test 4d: identity check - system-prompt generator provenance is REJECTED')
# The gate never rewrites data. Provenance boilerplate is common in some
# sources, so it should surface loudly in a calibration run and let the data
# owner decide how to clean it (identity_check.strip_provenance is available
# for their own preprocessing).
entry4d = {
'conversation': [
{'role': 'system', 'content': 'You are a coding agent. You are powered by the model named moonshotai/Kimi-K2.6. Be terse.'},
{'role': 'user', 'content': 'hi'},
{'role': 'assistant', 'content': 'hello', 'think': 'greet'},
]
}
_r4d, _errs4d, _rep4d = process_entry(entry4d, identity_check=True)
run_test('rejected', _r4d is None)
run_test('provenance error reported',
any('generator provenance' in e for e in _errs4d))
run_test('entry not mutated (no silent repair)',
'moonshotai/Kimi-K2.6' in entry4d['conversation'][0]['content'])
_r4d2, _errs4d2, _ = process_entry(entry4d, identity_check=False)
run_test('identity_check=False keeps it', _errs4d2 == [] and _r4d2 is not None)
print()
print('Test 4d2: strip_provenance helper (for data-owner scripts, not the gate)')
from identity_check import strip_provenance as _sp
_clean, _n = _sp('You are a coding agent. You are powered by the model named moonshotai/Kimi-K2.6. Be terse.')
run_test('helper strips one sentence', _n == 1)
run_test('helper keeps surrounding text',
_clean == 'You are a coding agent. Be terse.')
print()
print('Test 4e: identity check does not crash on list/dict tool content')
# Regression guard. The old check did `' '.join(...)` over every turn's content
# and raised TypeError on the list-shaped tool content this file explicitly
# permits -- making identity_check=True unusable on any agentic source.
entry4e = {
'conversation': [
{'role': 'system', 'content': 'sys', 'tools': [
{'name': 't', 'description': 'd', 'parameters': {
'type': 'object', 'properties': {'x': {'type': 'string'}},
'required': ['x']}}]},
{'role': 'user', 'content': 'hi'},
{'role': 'assistant', 'think': 'r', 'tool_calls': [{'name': 't', 'arguments': {'x': '1'}}]},
{'role': 'tool', 'content': [{'type': 'text', 'text': 'ok'}]},
{'role': 'assistant', 'think': 'done', 'content': 'answer'},
]
}
try:
_r4e, _errs4e, _ = process_entry(entry4e, identity_check=True)
run_test('no crash with list tool content', _errs4e == [] and _r4e is not None)
except Exception as _ex:
run_test(f'no crash with list tool content (raised {type(_ex).__name__})', False)
print()
# Test 5: messages key normalization
print('Test 5: messages key normalization')
entry5 = {
'messages': [
{'role': 'user', 'content': 'Test'},
{'role': 'assistant', 'content': 'Response', 'think': 'reasoning'},
]
}
result5, errs5, _ = process_entry(entry5)
run_test('no errors', errs5 == [])
run_test('conversation key in result', 'conversation' in result5)
run_test('messages key removed', 'messages' not in result5)
print()
# Test 6: compute_token_counts=False with pre-existing counts
print('Test 6: compute_token_counts=False with pre-existing counts')
entry6 = {
'conversation': [
{'role': 'user', 'content': 'Hello'},
{'role': 'assistant', 'content': 'Hi!', 'think': 'reasoning'},
],
'token_count': 100,
'token_count_answer': 50,
'token_count_think': 10,
}
result6, errs6, _ = process_entry(entry6, compute_token_counts=False)
run_test('no errors', errs6 == [])
run_test('token_count not recomputed', result6['token_count'] == 100)
print()
# Test 6b: compute_token_counts=False without pre-existing counts -> error
print('Test 6b: compute_token_counts=False without counts')
entry6b = {
'conversation': [
{'role': 'user', 'content': 'Hello'},
{'role': 'assistant', 'content': 'Hi!', 'think': 'reasoning'},
],
}
result6b, errs6b, _ = process_entry(entry6b, compute_token_counts=False)
run_test('errors returned', len(errs6b) > 0)
run_test('result is None', result6b is None)
print()
# Test 7: Entry with tool_calls (happy path)
print('Test 7: Entry with tool_calls')
entry7 = {
'conversation': [
{'role': 'system', 'tools': [
{'name': 'get_weather', 'description': 'Get weather',
'parameters': {'type': 'object', 'properties': {'city': {'type': 'string'}}}},
]},
{'role': 'user', 'content': 'What is the weather in NYC?'},
{'role': 'assistant', 'content': '', 'think': 'I should call get_weather',
'tool_calls': [{'name': 'get_weather', 'arguments': {'city': 'NYC'}}]},
{'role': 'tool', 'name': 'get_weather', 'content': '{"temp": 72}'},
{'role': 'assistant', 'content': 'The temperature in NYC is 72F.', 'think': 'reasoning'},
]
}
result7, errs7, _ = process_entry(entry7)
run_test('no errors', errs7 == [])
run_test('token_count_answer > 0', result7['token_count_answer'] > 0)
print()
# Test 8: Empty system message cleanup
print('Test 8: Empty system message cleanup')
entry8 = {
'conversation': [
{'role': 'system', 'content': '', 'tools': []},
{'role': 'user', 'content': 'Hello'},
{'role': 'assistant', 'content': 'Hi!', 'think': 'reasoning'},
]
}
result8, errs8, _ = process_entry(entry8)
run_test('no errors', errs8 == [])
run_test('system message removed', result8['conversation'][0]['role'] == 'user')
print()
# Test 9: reasoning_effort='low' -> think_faster
print('Test 9: reasoning_effort=low')
entry9 = {
'conversation': [
{'role': 'user', 'content': 'Hello'},
{'role': 'assistant', 'content': 'Hi!', 'think': 'Greeting'},
]
}
result9, errs9, _ = process_entry(entry9, reasoning_effort='low')
run_test('no errors', errs9 == [])
run_test('think_faster key present', 'think_faster' in result9['conversation'][1])
print()
# Test 10: Original entry not mutated (deepcopy)
print('Test 10: Original entry not mutated')
entry10 = {
'messages': [
{'role': 'user', 'content': 'Test'},
{'role': 'assistant', 'content': 'Response', 'think': 'Reasoning'},
]
}
original_keys = set(entry10.keys())
process_entry(entry10, reasoning_effort='medium')
run_test('original entry unchanged', set(entry10.keys()) == original_keys)
run_test('messages key still present', 'messages' in entry10)
print()
# Test 11: Invalid first-message role
print('Test 11: Invalid first-message role')
entry11 = {
'conversation': [
{'role': 'assistant', 'content': 'Hi', 'think': 'reasoning'},
{'role': 'user', 'content': 'Hello'},
{'role': 'assistant', 'content': 'Hi again', 'think': 'reasoning'},
]
}
_, errs11, _ = process_entry(entry11)
run_test('errors returned', len(errs11) > 0)
run_test('invalid role error', any('First message' in e for e in errs11))
print()
# Test 12: Tool usage without system tools
print('Test 12: Tool usage without system tools')
entry12 = {
'conversation': [
{'role': 'user', 'content': 'What is the weather?'},
{'role': 'assistant', 'content': '', 'think': 'reasoning',
'tool_calls': [{'name': 'get_weather', 'arguments': {'city': 'NYC'}}]},
{'role': 'tool', 'name': 'get_weather', 'content': '{"temp": 72}'},
{'role': 'assistant', 'content': '72F', 'think': 'reasoning'},
]
}
_, errs12, _ = process_entry(entry12)
run_test('errors returned', len(errs12) > 0)
run_test('missing tools error', any('does not declare tools' in e for e in errs12))
print()
# Test 13: Assistant calls undeclared tool
print('Test 13: Assistant calls undeclared tool')
entry13 = {
'conversation': [
{'role': 'system', 'tools': [
{'name': 'get_weather', 'description': 'Get weather',
'parameters': {'type': 'object', 'properties': {'city': {'type': 'string'}}}},
]},
{'role': 'user', 'content': 'What is the stock price of AAPL?'},
{'role': 'assistant', 'content': '', 'think': 'reasoning',
'tool_calls': [{'name': 'get_stock_price', 'arguments': {'symbol': 'AAPL'}}]},
{'role': 'tool', 'name': 'get_stock_price', 'content': '180.5'},
{'role': 'assistant', 'content': '180.5', 'think': 'reasoning'},
]
}
_, errs13, _ = process_entry(entry13)
run_test('errors returned', len(errs13) > 0)
run_test('undeclared-call error', any('get_stock_price' in e for e in errs13))
print()
# Test 14: Strict version rejects string-typed tool_calls (loose version would coerce)
print('Test 14: Reject string-typed tool_calls')
entry14 = {
'conversation': [
{'role': 'system', 'tools': [
{'name': 'echo', 'description': '', 'parameters': {'type': 'object',
'properties': {'msg': {'type': 'string'}}}},
]},
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': '', 'think': 'reasoning',
'tool_calls': '[{"name": "echo", "arguments": {"msg": "hi"}}]'},
{'role': 'tool', 'name': 'echo', 'content': 'hi'},
{'role': 'assistant', 'content': 'done', 'think': 'reasoning'},
]
}
_, errs14, _ = process_entry(entry14)
run_test('errors returned', len(errs14) > 0)
run_test('tool_calls list error', any('tool_calls should be a list' in e for e in errs14))
print()
# Test 15: Default rejects JSON-string tools field
print('Test 15: Default rejects JSON-string tools field')
entry15 = {
'conversation': [
{'role': 'system',
'tools': '[{"name": "echo", "description": "", "parameters": {"type": "object", "properties": {"msg": {"type": "string"}}}}]'},
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': 'hi', 'think': 'reasoning'},
]
}
_, errs15, _ = process_entry(entry15)
run_test('errors returned', len(errs15) > 0)
run_test('tools list error', any('tools should be a list' in e for e in errs15))
print()
# Test 17: Repair tracking — messages -> conversation
print('Test 17: messages_to_conversation repair logged')
entry17 = {
'messages': [
{'role': 'user', 'content': 'Test'},
{'role': 'assistant', 'content': 'Response', 'think': 'reasoning'},
]
}
_, _, reps17 = process_entry(entry17)
run_test('messages_to_conversation flag set', reps17.get('messages_to_conversation') is True)
run_test('only that key in repairs', set(reps17.keys()) == {'messages_to_conversation'})
print()
# Test 18: Repair tracking — empty system message dropped
print('Test 18: system_msg_dropped_empty repair logged')
entry18 = {
'conversation': [
{'role': 'system', 'content': '', 'tools': []},
{'role': 'user', 'content': 'Hello'},
{'role': 'assistant', 'content': 'Hi!', 'think': 'reasoning'},
]
}
_, _, reps18 = process_entry(entry18)
run_test('system_msg_empty_content_deleted set', reps18.get('system_msg_empty_content_deleted') is True)
run_test('system_msg_empty_tools_deleted set', reps18.get('system_msg_empty_tools_deleted') is True)
run_test('system_msg_dropped_empty set', reps18.get('system_msg_dropped_empty') is True)
run_test('only those three keys in repairs',
set(reps18.keys()) == {'system_msg_empty_content_deleted',
'system_msg_empty_tools_deleted',
'system_msg_dropped_empty'})
print()
# Test 19: Repair tracking — None-valued field deleted
print('Test 19: none_fields_deleted counter')
entry19 = {
'conversation': [
{'role': 'user', 'content': 'Hello'},
{'role': 'assistant', 'content': 'Hi!', 'think': 'reasoning', 'tool_calls': None},
]
}
_, _, reps19 = process_entry(entry19)
run_test('none_fields_deleted = 1', reps19.get('none_fields_deleted') == 1)
run_test('only that key in repairs', set(reps19.keys()) == {'none_fields_deleted'})
print()
# Test 20: Repair tracking — empty tool_calls list deleted
print('Test 20: empty_tool_calls_deleted counter')
entry20 = {
'conversation': [
{'role': 'user', 'content': 'Hello'},
{'role': 'assistant', 'content': 'Hi!', 'think': 'reasoning', 'tool_calls': []},
]
}
_, _, reps20 = process_entry(entry20)
run_test('empty_tool_calls_deleted = 1', reps20.get('empty_tool_calls_deleted') == 1)
run_test('only that key in repairs', set(reps20.keys()) == {'empty_tool_calls_deleted'})
print()
# Test 21: Repair tracking — function wrapper unwrapped in tool_calls
print('Test 21: tool_calls_function_unwrapped counter')
entry21 = {
'conversation': [
{'role': 'system', 'tools': [
{'name': 'get_weather', 'description': '',
'parameters': {'type': 'object', 'properties': {'city': {'type': 'string'}}}},
]},
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': '', 'think': 'reasoning',
'tool_calls': [{'function': {'name': 'get_weather', 'arguments': {'city': 'NYC'}}}]},
{'role': 'tool', 'name': 'get_weather', 'content': 'OK'},
{'role': 'assistant', 'content': 'done', 'think': 'reasoning'},
]
}
_, errs21, reps21 = process_entry(entry21)
run_test('no errors', errs21 == [])
run_test('tool_calls_function_unwrapped = 1', reps21.get('tool_calls_function_unwrapped') == 1)
run_test('only that key in repairs', set(reps21.keys()) == {'tool_calls_function_unwrapped'})
print()
# Test 22: Repair tracking — function wrapper unwrapped in system tools
print('Test 22: tool_defs_function_unwrapped counter')
entry22 = {
'conversation': [
{'role': 'system', 'tools': [
{'function': {'name': 'get_weather', 'description': '',
'parameters': {'type': 'object', 'properties': {'city': {'type': 'string'}}}}},
]},
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': '', 'think': 'reasoning',
'tool_calls': [{'name': 'get_weather', 'arguments': {'city': 'NYC'}}]},
{'role': 'tool', 'name': 'get_weather', 'content': 'OK'},
{'role': 'assistant', 'content': 'done', 'think': 'reasoning'},
]
}
_, errs22, reps22 = process_entry(entry22)
run_test('no errors', errs22 == [])
run_test('tool_defs_function_unwrapped = 1', reps22.get('tool_defs_function_unwrapped') == 1)
run_test('only that key in repairs', set(reps22.keys()) == {'tool_defs_function_unwrapped'})
print()
# Test 23: Repair tracking — arguments -> parameters in tool def
print('Test 23: tool_defs_arguments_to_parameters counter')
entry23 = {
'conversation': [
{'role': 'system', 'tools': [
{'name': 'get_weather', 'description': '',
'arguments': {'type': 'object', 'properties': {'city': {'type': 'string'}}}},
]},
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': '', 'think': 'reasoning',
'tool_calls': [{'name': 'get_weather', 'arguments': {'city': 'NYC'}}]},
{'role': 'tool', 'name': 'get_weather', 'content': 'OK'},
{'role': 'assistant', 'content': 'done', 'think': 'reasoning'},
]
}
_, errs23, reps23 = process_entry(entry23)
run_test('no errors', errs23 == [])
run_test('tool_defs_arguments_to_parameters = 1', reps23.get('tool_defs_arguments_to_parameters') == 1)
run_test('only that key in repairs', set(reps23.keys()) == {'tool_defs_arguments_to_parameters'})
print()
# Test 23b: system_msg_dropped_empty fires alone when system has neither content nor tools
print('Test 23b: system_msg_dropped_empty alone (no content, no tools)')
entry23b = {
'conversation': [
{'role': 'system'},
{'role': 'user', 'content': 'Hello'},
{'role': 'assistant', 'content': 'Hi!', 'think': 'reasoning'},
]
}
_, errs23b, reps23b = process_entry(entry23b)
run_test('no errors', errs23b == [])
run_test('system_msg_dropped_empty set', reps23b.get('system_msg_dropped_empty') is True)
run_test('only that key in repairs', set(reps23b.keys()) == {'system_msg_dropped_empty'})
print()
# Test 24: Strict tool-call check — missing required arg
print('Test 24: strict check — missing required arg')
entry24 = {
'conversation': [
{'role': 'system', 'tools': [
{'name': 'get_weather', 'description': '', 'parameters': {
'type': 'object', 'properties': {'city': {'type': 'string'}},
'required': ['city']}},
]},
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': '', 'think': 'reasoning',
'tool_calls': [{'name': 'get_weather', 'arguments': {}}]},
{'role': 'tool', 'name': 'get_weather', 'content': 'OK'},
{'role': 'assistant', 'content': 'done', 'think': 'reasoning'},
]
}
_, errs24, _ = process_entry(entry24)
run_test('errors returned', len(errs24) > 0)
run_test('missing required arg error', any('missing required arg' in e and 'city' in e for e in errs24))
print()
# Test 25: Strict check — extra arg flagged when additionalProperties=False
print('Test 25: strict check — extra arg (additionalProperties=False)')
entry25 = {
'conversation': [
{'role': 'system', 'tools': [
{'name': 'get_weather', 'description': '', 'parameters': {
'type': 'object', 'properties': {'city': {'type': 'string'}},
'additionalProperties': False}},
]},
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': '', 'think': 'reasoning',
'tool_calls': [{'name': 'get_weather',
'arguments': {'city': 'NYC', 'foo': 'bar'}}]},
{'role': 'tool', 'name': 'get_weather', 'content': 'OK'},
{'role': 'assistant', 'content': 'done', 'think': 'reasoning'},
]
}
_, errs25, _ = process_entry(entry25)
run_test('errors returned', len(errs25) > 0)
run_test('extra arg error', any('extra arg not in schema' in e and 'foo' in e for e in errs25))
print()
# Test 25b: strict-by-default — extras rejected when additionalProperties absent.
# Diverges from JSON-Schema spec default (true); intentional for production gateway.
print('Test 25b: extras rejected when additionalProperties absent (strict default)')
entry25b = {
'conversation': [
{'role': 'system', 'tools': [
{'name': 'get_weather', 'description': '', 'parameters': {
'type': 'object', 'properties': {'city': {'type': 'string'}}}},
]},
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': '', 'think': 'reasoning',
'tool_calls': [{'name': 'get_weather',
'arguments': {'city': 'NYC', 'foo': 'bar'}}]},
{'role': 'tool', 'name': 'get_weather', 'content': 'OK'},
{'role': 'assistant', 'content': 'done', 'think': 'reasoning'},
]
}
_, errs25b, _ = process_entry(entry25b)
run_test('extra arg error raised', any('extra arg not in schema' in e and 'foo' in e for e in errs25b))
print()
# Test 25c: extra arg allowed when additionalProperties=True explicit
# (browser-use schemas: {"properties": {}, "additionalProperties": true})
print('Test 25c: extra arg allowed when additionalProperties=True explicit')
entry25c = {
'conversation': [
{'role': 'system', 'tools': [
{'name': 'click', 'description': '', 'parameters': {
'type': 'object', 'properties': {},
'additionalProperties': True}},
]},
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': '', 'think': 'reasoning',
'tool_calls': [{'name': 'click',
'arguments': {'index': 5, 'selector': '#btn'}}]},
{'role': 'tool', 'name': 'click', 'content': 'OK'},
{'role': 'assistant', 'content': 'done', 'think': 'reasoning'},
]
}
res25c, errs25c, _ = process_entry(entry25c)
run_test('no extra-arg error', not any('extra arg not in schema' in e for e in errs25c))
run_test('result accepted', res25c is not None)
print()
# Test 26: Strict check — type mismatch
print('Test 26: strict check — type mismatch')
entry26 = {
'conversation': [
{'role': 'system', 'tools': [
{'name': 'set_count', 'description': '', 'parameters': {
'type': 'object', 'properties': {'n': {'type': 'integer'}}}},
]},
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': '', 'think': 'reasoning',
'tool_calls': [{'name': 'set_count', 'arguments': {'n': '42'}}]},
{'role': 'tool', 'name': 'set_count', 'content': 'OK'},
{'role': 'assistant', 'content': 'done', 'think': 'reasoning'},
]
}
_, errs26, _ = process_entry(entry26)
run_test('errors returned', len(errs26) > 0)
run_test('type mismatch error', any('expected integer' in e and 'got str' in e for e in errs26))
print()
# Test 27: Strict check — nested object recursion
print('Test 27: strict check — nested object recursion')
entry27 = {
'conversation': [
{'role': 'system', 'tools': [
{'name': 'set_address', 'description': '', 'parameters': {
'type': 'object', 'properties': {
'address': {'type': 'object', 'properties': {
'zip': {'type': 'string'}}, 'required': ['zip']}}}},
]},
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': '', 'think': 'reasoning',
'tool_calls': [{'name': 'set_address', 'arguments': {'address': {'zip': 90210}}}]},
{'role': 'tool', 'name': 'set_address', 'content': 'OK'},
{'role': 'assistant', 'content': 'done', 'think': 'reasoning'},
]
}
_, errs27, _ = process_entry(entry27)
run_test('errors returned', len(errs27) > 0)
run_test('nested type error', any('address.zip' in e and 'expected string' in e for e in errs27))
print()
# Test 28: Strict check — undeclared tool still caught
print('Test 28: strict check — undeclared tool')
entry28 = {
'conversation': [
{'role': 'system', 'tools': [
{'name': 'get_weather', 'description': '', 'parameters': {
'type': 'object', 'properties': {'city': {'type': 'string'}}}},
]},
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': '', 'think': 'reasoning',
'tool_calls': [{'name': 'get_stock', 'arguments': {'symbol': 'AAPL'}}]},
{'role': 'tool', 'name': 'get_stock', 'content': '180'},
{'role': 'assistant', 'content': '180', 'think': 'reasoning'},
]
}
_, errs28, _ = process_entry(entry28)
run_test('errors returned', len(errs28) > 0)
run_test('undeclared tool error', any("'get_stock'" in e and 'not in declared tools' in e for e in errs28))
print()
# Test 29: Qwen cw suffix — basic strip
print('Test 29: Qwen cw suffix stripped')
entry29 = {
'conversation': [
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': 'a', 'think': 'Ready to produce answer.cw'},
]
}
result29, errs29, reps29 = process_entry(entry29)
run_test('no errors', errs29 == [])
run_test('think stripped of cw', result29['conversation'][1]['think'] == 'Ready to produce answer.')
run_test('qwen_cw_suffix_stripped = 1', reps29.get('qwen_cw_suffix_stripped') == 1)
print()
# Test 30: Qwen cw with trailing whitespace
print('Test 30: Qwen cw stripped through trailing whitespace')
entry30 = {
'conversation': [
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': 'a', 'think': 'reasoning\ncw\n'},
]
}
result30, errs30, reps30 = process_entry(entry30)
run_test('no errors', errs30 == [])
# Expectation updated 2026-07-27: the whitespace normalization added after the
# <think>-tag strip now also removes the trailing newline the cw strip left
# behind, so this is 'reasoning' rather than 'reasoning\n'.
run_test('think is reasoning with no trailing whitespace',
result30['conversation'][1]['think'] == 'reasoning')
run_test('qwen_cw_suffix_stripped = 1', reps30.get('qwen_cw_suffix_stripped') == 1)
run_test('whitespace strip also logged',
reps30.get('think_whitespace_stripped') == 1)
print()
print('Test 30b: whitespace normalization on reasoning and content')
# Trailing/leading whitespace in REASONING is never meaningful (the chat template
# supplies its own delimiters) and training on it produced the growing whitespace tails
# observed in the 7B eval traces. Sources feed it: 64% of `think` fields in
# one DeepSeek-V3.2 tool-use source end in trailing whitespace, runs up to 3089 spaces.
entry30b = {
'conversation': [
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'think': ' reasoning here \n\n\n', 'content': '\n answer \n '},
]
}
_r30b, _e30b, _rep30b = process_entry(entry30b)
run_test('no errors', _e30b == [])
run_test('think stripped', _r30b['conversation'][1]['think'] == 'reasoning here')
# `content` is deliberately NOT stripped: a task may require the model to emit
# exact leading/trailing spaces or newlines (format-following, "output this
# verbatim", whitespace-sensitive fixtures). Stripping would corrupt the target.
run_test('content NOT stripped (intentional)',
_r30b['conversation'][1]['content'] == '\n answer \n ')
run_test('only think repair logged',
_rep30b.get('think_whitespace_stripped') == 1
and 'content_whitespace_stripped' not in _rep30b)
# the dsv32 growing-tail shape
entry30c = {
'conversation': [
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'think': "Let's try 121." + ' ' * 300, 'content': 'done'},
]
}
_r30c, _e30c, _rep30c = process_entry(entry30c)
run_test('300-space tail removed', _r30c['conversation'][1]['think'] == "Let's try 121.")
# clean input must not be logged as repaired
entry30d = {
'conversation': [
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'think': 'clean', 'content': 'clean'},
]
}
_r30d, _e30d, _rep30d = process_entry(entry30d)
run_test('clean input logs no whitespace repair',
'think_whitespace_stripped' not in _rep30d)
print()
print('Test 30e: whitespace-only think counts as ABSENT reasoning')
# Regression guard. The no_think check uses plain truthiness, so before the
# strip a think of " \n " was TRUTHY and let a reasoning-free record pass
# as though it had reasoning.
entry30e = {
'conversation': [
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'think': ' \n ', 'content': 'answer'},
]
}
_r30e, _e30e, _ = process_entry(entry30e, require_think=True)
run_test('rejected with require_think=True',
_r30e is None and any('non-empty think' in e for e in _e30e))
_r30e2, _e30e2, _rep30e2 = process_entry(entry30e, require_think=False)
run_test('flagged as missing think with require_think=False',
_rep30e2.get('missing_think_all_turns') is True)
print()
# Test 31: No cw — repair not logged
print('Test 31: No cw — qwen_cw_suffix_stripped not in repairs')
entry31 = {
'conversation': [
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': 'a', 'think': 'normal reasoning'},
]
}
_, _, reps31 = process_entry(entry31)
run_test('qwen_cw_suffix_stripped not present', 'qwen_cw_suffix_stripped' not in reps31)
print()
# Test 31a: Leading <think> tag in think field — basic strip
print('Test 31a: leading <think> tag stripped from think field')
entry31a = {
'conversation': [
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': 'a', 'think': '<think> Perfect! The menu was created.'},
]
}
result31a, errs31a, reps31a = process_entry(entry31a)
run_test('no errors', errs31a == [])
# Expectation updated 2026-07-27: whitespace normalization now also removes the
# space the <think> tag removal left at the front.
run_test('think stripped of leading <think> and whitespace',
result31a['conversation'][1]['think'] == 'Perfect! The menu was created.')
run_test('think_open_tag_stripped = 1', reps31a.get('think_open_tag_stripped') == 1)
print()
# Test 31b: Leading whitespace before <think> tag still stripped
print('Test 31b: leading whitespace + <think> tag stripped')
entry31b = {
'conversation': [
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': 'a', 'think': '\n <think>actual reasoning'},
]
}
result31b, errs31b, reps31b = process_entry(entry31b)
run_test('no errors', errs31b == [])
run_test('think starts with actual reasoning',
result31b['conversation'][1]['think'] == 'actual reasoning')
run_test('think_open_tag_stripped = 1', reps31b.get('think_open_tag_stripped') == 1)
print()
# Test 31c: No leading <think> — repair not logged
print('Test 31c: No leading <think> — repair not logged')
entry31c = {
'conversation': [
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': 'a', 'think': 'normal reasoning'},
]
}
_, _, reps31c = process_entry(entry31c)
run_test('think_open_tag_stripped not present', 'think_open_tag_stripped' not in reps31c)
print()
# Test 32: Reject when all assistant turns have empty think
print('Test 32: reject all-empty think')
entry32 = {
'conversation': [
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': 'a1', 'think': ''},
{'role': 'user', 'content': 'q2'},
{'role': 'assistant', 'content': 'a2', 'think': ''},
]
}
result32, errs32, _ = process_entry(entry32)
run_test('errors returned', len(errs32) > 0)
run_test('no-think error', any('No assistant turn has non-empty think' in e for e in errs32))
run_test('result is None', result32 is None)
print()
# Test 33: Accept when at least one assistant turn has think
print('Test 33: accept when one turn has non-empty think')
entry33 = {
'conversation': [
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': 'a1', 'think': 'reasoning here'},
{'role': 'user', 'content': 'q2'},
{'role': 'assistant', 'content': 'a2', 'think': ''},
]
}
_, errs33, _ = process_entry(entry33)
run_test('no errors', errs33 == [])
print()
# Test 33b: Conversation ending with a tool turn is rejected
print('Test 33b: end-of-conversation must be assistant')
entry33b = {
'conversation': [
{'role': 'system', 'tools': [
{'name': 'echo', 'description': '',
'parameters': {'type': 'object', 'properties': {'msg': {'type': 'string'}}}},
]},
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': '', 'think': 'reasoning',
'tool_calls': [{'name': 'echo', 'arguments': {'msg': 'hi'}}]},
{'role': 'tool', 'name': 'echo', 'content': 'OK'},
]
}
result33b, errs33b, _ = process_entry(entry33b)
run_test('errors returned', len(errs33b) > 0)
run_test('end-of-conv error', any('must end with an assistant message' in e for e in errs33b))
run_test('error mentions tool', any('ended with tool' in e for e in errs33b))
run_test('result is None', result33b is None)
print()
# Test 34: Reject when reasoning was just "cw" (becomes empty after strip)
print('Test 34: reject reasoning that was just cw')
entry34 = {
'conversation': [
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': 'a', 'think': 'cw'},
]
}
result34, errs34, _ = process_entry(entry34)
run_test('errors returned', len(errs34) > 0)
run_test('no-think error', any('No assistant turn has non-empty think' in e for e in errs34))
print()
# Test 35: Core special token in content rejected
print('Test 35: core special token (<|im_start|>) in content')
entry35 = {
'conversation': [
{'role': 'user', 'content': 'normal'},
{'role': 'assistant', 'content': 'leak <|im_start|> here', 'think': 'reasoning'},
]
}
_, errs35, _ = process_entry(entry35)
run_test('errors returned', len(errs35) > 0)
run_test('core marker error', any('<|im_start|>' in e and 'content' in e for e in errs35))
print()
# Test 36: Core <think> tag in content rejected
print('Test 36: core <think> tag in content')
entry36 = {
'conversation': [
{'role': 'user', 'content': 'looks like <think>oops</think>'},
{'role': 'assistant', 'content': 'a', 'think': 'reasoning'},
]
}
_, errs36, _ = process_entry(entry36)
run_test('errors returned', len(errs36) > 0)
run_test('<think> marker error', any('<think>' in e for e in errs36))
run_test('</think> marker error', any('</think>' in e for e in errs36))
print()
# Test 37: Extended marker (<|begin_of_thought|>) detected by default
print('Test 37: extended marker on by default')
entry37 = {
'conversation': [
{'role': 'user', 'content': '<|begin_of_thought|> snuck in'},
{'role': 'assistant', 'content': 'a', 'think': 'reasoning'},
]
}
_, errs37, _ = process_entry(entry37)
run_test('errors returned', len(errs37) > 0)
run_test('begin_of_thought marker error', any('<|begin_of_thought|>' in e for e in errs37))
print()
# Test 38: Extended marker NOT scanned when toggle off
print('Test 38: extended toggle disables extended scan')
_, errs38, _ = process_entry(entry37, check_extended_special_tokens=False)
run_test('no errors when toggle off', errs38 == [])
print()
# Test 39: Harmony marker (assistantanalysis) detected by default
print('Test 39: harmony marker on by default')
entry39 = {
'conversation': [
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': 'leaked assistantanalysis here', 'think': 'reasoning'},
]
}
_, errs39, _ = process_entry(entry39)
run_test('errors returned', len(errs39) > 0)
run_test('assistantanalysis marker error', any('assistantanalysis' in e for e in errs39))
print()
# Test 40: Harmony marker NOT scanned when toggle off
print('Test 40: harmony toggle disables harmony scan')
_, errs40, _ = process_entry(entry39, check_harmony_special_tokens=False)
run_test('no errors when toggle off', errs40 == [])
print()
# Test 41: Marker in think field is reported with field=think
print('Test 41: marker in think field reports field name')
entry41 = {
'conversation': [
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': 'a', 'think': 'reasoning <|im_end|>'},
]
}
_, errs41, _ = process_entry(entry41)
run_test('errors returned', len(errs41) > 0)
run_test("error mentions field 'think'", any("'think'" in e for e in errs41))
print()
# Test 42: Marker in tool_calls arguments detected (any field, all turns)
print('Test 42: marker inside tool_calls.arguments detected')
entry42 = {
'conversation': [
{'role': 'system', 'tools': [
{'name': 'echo', 'description': '',
'parameters': {'type': 'object', 'properties': {'msg': {'type': 'string'}}}},
]},
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': '', 'think': 'reasoning',
'tool_calls': [{'name': 'echo', 'arguments': {'msg': 'hi <|im_start|>'}}]},
{'role': 'tool', 'name': 'echo', 'content': 'OK'},
{'role': 'assistant', 'content': 'done', 'think': 'reasoning'},
]
}
_, errs42, _ = process_entry(entry42)
run_test('errors returned', len(errs42) > 0)
run_test("error mentions tool_calls field", any("'tool_calls'" in e for e in errs42))
print()
# ===== Tool recovery extension =====
def _err_classifier(content):
"""Test classifier: detects {"error": ...} JSON shape."""
if isinstance(content, dict):
obj = content
elif isinstance(content, str):
try:
obj = json.loads(content)
except (json.JSONDecodeError, ValueError):
return False
else:
return False
return isinstance(obj, dict) and bool(obj.get('error'))
# entry shared by tests 43 and 44: schema-fail then successful value-only retry.
# First call schema-fails (zip int), tool errors, model retries with zip as string
# which schema-passes, last tool-calling turn succeeds.
entry_recover = {
'conversation': [
{'role': 'system', 'tools': [
{'name': 'lookup', 'description': '', 'parameters': {
'type': 'object', 'properties': {'zip': {'type': 'string'}},
'required': ['zip']}},
]},
{'role': 'user', 'content': 'q'},
{'role': 'assistant', 'content': '', 'think': 'r',
'tool_calls': [{'name': 'lookup', 'arguments': {'zip': 12345}}]},
{'role': 'tool', 'name': 'lookup', 'content': '{"error": "zip must be string"}'},
{'role': 'assistant', 'content': '', 'think': 'r',
'tool_calls': [{'name': 'lookup', 'arguments': {'zip': '12345'}}]},
{'role': 'tool', 'name': 'lookup', 'content': '{"result": "ok"}'},
{'role': 'assistant', 'content': 'all set', 'think': 'r2'},
]
}
# Test 43: classifier=None -> strict behavior unchanged (schema-fail surfaces)
print('Test 43: classifier=None -> strict path unchanged')
_, errs43, reps43 = process_entry(entry_recover) # strict
run_test('errors returned', len(errs43) > 0)
run_test('strict-mode repairs lacks recovery keys',
not any(k.startswith('tool_recovery') or k == 'tool_response_errors_count' for k in reps43))
print()
# Test 44: classifier provided -> tolerated when error response matches and trajectory recovers
print('Test 44: tolerate schema-fail when matched by error response (value-only retry)')
res44, errs44, reps44 = process_entry(entry_recover, tool_error_classifier=_err_classifier)