-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadversarial_round10_spec.rb
More file actions
1661 lines (1447 loc) · 66.7 KB
/
Copy pathadversarial_round10_spec.rb
File metadata and controls
1661 lines (1447 loc) · 66.7 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
# frozen_string_literal: true
# Adversarial QA round 10 -- THE FINAL ROUND. Production certification audit.
# Rounds 1-8 found ~40 bugs. This round either finds the LAST remaining bugs
# or certifies each module as production-ready.
#
# For each module: "Would I trust this code to handle $10K/month in LLM spend
# without human supervision?"
RSpec.describe "Adversarial QA round 10 -- production certification audit" do
before { RubyLLM::Contract.reset_configuration! }
# ===========================================================================
# 1. PARSER -- is it bulletproof now?
# ===========================================================================
describe "CERTIFICATION: Parser" do
# -------------------------------------------------------------------------
# Real-world LLM response patterns
# -------------------------------------------------------------------------
describe "real-world LLM response patterns" do
it "parses clean JSON object" do
result = RubyLLM::Contract::Parser.parse('{"name": "Alice", "age": 30}', strategy: :json)
expect(result).to eq({ name: "Alice", age: 30 })
end
it "parses clean JSON array" do
result = RubyLLM::Contract::Parser.parse("[1, 2, 3]", strategy: :json)
expect(result).to eq([1, 2, 3])
end
it "parses deeply nested JSON (4 levels)" do
json = '{"a": {"b": {"c": {"d": "deep"}}}}'
result = RubyLLM::Contract::Parser.parse(json, strategy: :json)
expect(result).to eq({ a: { b: { c: { d: "deep" } } } })
end
it "parses JSON with escaped quotes in string values" do
json = '{"text": "He said \\"hello\\""}'
result = RubyLLM::Contract::Parser.parse(json, strategy: :json)
expect(result).to eq({ text: 'He said "hello"' })
end
it "parses JSON with unicode escape sequences" do
json = '{"emoji": "\\u2764"}'
result = RubyLLM::Contract::Parser.parse(json, strategy: :json)
expect(result[:emoji]).to be_a(String)
end
it "parses JSON with newlines in string values" do
json = '{"text": "line1\\nline2"}'
result = RubyLLM::Contract::Parser.parse(json, strategy: :json)
expect(result[:text]).to include("\n")
end
it "parses JSON with boolean values" do
json = '{"active": true, "deleted": false}'
result = RubyLLM::Contract::Parser.parse(json, strategy: :json)
expect(result).to eq({ active: true, deleted: false })
end
it "parses JSON with null value" do
json = '{"name": null}'
result = RubyLLM::Contract::Parser.parse(json, strategy: :json)
expect(result).to eq({ name: nil })
end
it "parses JSON with mixed array types" do
json = '{"items": [1, "two", true, null, {"nested": "obj"}]}'
result = RubyLLM::Contract::Parser.parse(json, strategy: :json)
expect(result[:items].length).to eq(5)
expect(result[:items][4]).to eq({ nested: "obj" })
end
it "parses JSON with empty object" do
result = RubyLLM::Contract::Parser.parse("{}", strategy: :json)
expect(result).to eq({})
end
it "parses JSON with empty array" do
result = RubyLLM::Contract::Parser.parse("[]", strategy: :json)
expect(result).to eq([])
end
it "parses JSON with leading/trailing whitespace" do
result = RubyLLM::Contract::Parser.parse(" \n{\"ok\": true}\n ", strategy: :json)
expect(result).to eq({ ok: true })
end
it "parses JSON with BOM prefix" do
bom = "\xEF\xBB\xBF"
result = RubyLLM::Contract::Parser.parse("#{bom}{\"ok\": true}", strategy: :json)
expect(result).to eq({ ok: true })
end
it "parses JSON array wrapped in code fences" do
text = "```json\n[{\"id\": 1}, {\"id\": 2}]\n```"
result = RubyLLM::Contract::Parser.parse(text, strategy: :json)
expect(result).to eq([{ id: 1 }, { id: 2 }])
end
it "parses JSON with large numeric values" do
json = '{"big": 9999999999999}'
result = RubyLLM::Contract::Parser.parse(json, strategy: :json)
expect(result[:big]).to eq(9_999_999_999_999)
end
it "parses JSON with float values" do
json = '{"pi": 3.14159, "negative": -2.5}'
result = RubyLLM::Contract::Parser.parse(json, strategy: :json)
expect(result[:pi]).to be_within(0.00001).of(3.14159)
expect(result[:negative]).to eq(-2.5)
end
it "parses Hash input directly (passthrough)" do
result = RubyLLM::Contract::Parser.parse({ "name" => "Bob" }, strategy: :json)
expect(result).to eq({ name: "Bob" })
end
it "parses Array input directly (passthrough)" do
result = RubyLLM::Contract::Parser.parse([1, 2, 3], strategy: :json)
expect(result).to eq([1, 2, 3])
end
end
# -------------------------------------------------------------------------
# Edge cases
# -------------------------------------------------------------------------
describe "edge cases" do
it "raises ParseError for whitespace-only response" do
expect do
RubyLLM::Contract::Parser.parse(" \n\t ", strategy: :json)
end.to raise_error(RubyLLM::Contract::ParseError)
end
it "parses single number string as JSON" do
result = RubyLLM::Contract::Parser.parse("42", strategy: :json)
expect(result).to eq(42)
end
it "raises ParseError for the string 'undefined'" do
expect do
RubyLLM::Contract::Parser.parse("undefined", strategy: :json)
end.to raise_error(RubyLLM::Contract::ParseError)
end
it "handles response that is ONLY whitespace" do
expect do
RubyLLM::Contract::Parser.parse("", strategy: :json)
end.to raise_error(RubyLLM::Contract::ParseError)
end
it "handles response with null bytes in string values" do
# JSON with embedded \u0000 -- this is valid JSON but may cause issues
json = '{"data": "hello\u0000world"}'
result = RubyLLM::Contract::Parser.parse(json, strategy: :json)
expect(result[:data]).to include("hello")
end
end
# -------------------------------------------------------------------------
# extract_json bracket matching correctness
# -------------------------------------------------------------------------
describe "extract_json bracket matching with braces in strings" do
it "correctly handles { and } inside JSON string values" do
json = '{"template": "Hello {name}, welcome to {place}"}'
result = RubyLLM::Contract::Parser.parse(json, strategy: :json)
expect(result[:template]).to eq("Hello {name}, welcome to {place}")
end
it "correctly handles nested braces in string values" do
json = '{"code": "function() { return {}; }"}'
result = RubyLLM::Contract::Parser.parse(json, strategy: :json)
expect(result[:code]).to eq("function() { return {}; }")
end
it "correctly handles brackets inside string values" do
json = '{"regex": "[a-z]{3,5}"}'
result = RubyLLM::Contract::Parser.parse(json, strategy: :json)
expect(result[:regex]).to eq("[a-z]{3,5}")
end
it "correctly handles escaped quotes adjacent to braces" do
json = '{"val": "\\\"{\\\"}"}' # JSON: {"val": "\"{\"}"} -- tricky escaping
# This is intentionally testing that the bracket matcher does not get
# confused by escaped quotes near braces. We just need it not to crash.
expect do
RubyLLM::Contract::Parser.parse(json, strategy: :json)
end.not_to raise_error(TypeError)
end
it "raises ParseError when first balanced brackets are not valid JSON" do
text = 'The function takes {params} and returns: {"result": "ok"}'
# extract_json finds {params} first (balanced braces), but it is not valid JSON.
# JSON.parse("{params}") fails, so ParseError is raised. The second JSON object
# is never reached. This is a documented limitation of first-bracket extraction.
expect do
RubyLLM::Contract::Parser.parse(text, strategy: :json)
end.to raise_error(RubyLLM::Contract::ParseError)
end
it "handles deeply nested mixed brackets" do
json = '{"a": [{"b": [1, 2]}, {"c": {"d": [3]}}]}'
result = RubyLLM::Contract::Parser.parse(json, strategy: :json)
expect(result[:a].length).to eq(2)
expect(result[:a][0][:b]).to eq([1, 2])
expect(result[:a][1][:c][:d]).to eq([3])
end
end
# -------------------------------------------------------------------------
# Text strategy
# -------------------------------------------------------------------------
describe "text strategy" do
it "returns raw string as-is" do
result = RubyLLM::Contract::Parser.parse("hello world", strategy: :text)
expect(result).to eq("hello world")
end
it "returns nil as-is" do
result = RubyLLM::Contract::Parser.parse(nil, strategy: :text)
expect(result).to be_nil
end
it "returns non-string values as-is" do
result = RubyLLM::Contract::Parser.parse(42, strategy: :text)
expect(result).to eq(42)
end
end
describe "unknown strategy" do
it "raises ArgumentError" do
expect do
RubyLLM::Contract::Parser.parse("test", strategy: :xml)
end.to raise_error(ArgumentError, /Unknown parse strategy/)
end
end
end
# ===========================================================================
# 2. SCHEMA VALIDATOR -- complete JSON Schema compliance
# ===========================================================================
describe "CERTIFICATION: SchemaValidator" do
def make_schema(schema_hash)
schema_data = schema_hash
Class.new do
define_method(:to_json_schema) do
{ schema: schema_data }
end
end.new
end
# -------------------------------------------------------------------------
# Type checking for every JSON Schema type
# -------------------------------------------------------------------------
describe "type checking" do
it "validates string type" do
schema = make_schema(type: "object", properties: { name: { type: "string" } })
expect(RubyLLM::Contract::SchemaValidator.validate({ name: "Alice" }, schema)).to be_empty
errors = RubyLLM::Contract::SchemaValidator.validate({ name: 42 }, schema)
expect(errors.join).to match(/expected string/i)
end
it "validates integer type" do
schema = make_schema(type: "object", properties: { count: { type: "integer" } })
expect(RubyLLM::Contract::SchemaValidator.validate({ count: 5 }, schema)).to be_empty
errors = RubyLLM::Contract::SchemaValidator.validate({ count: 5.5 }, schema)
expect(errors.join).to match(/expected integer/i)
end
it "validates number type (accepts both int and float)" do
schema = make_schema(type: "object", properties: { score: { type: "number" } })
expect(RubyLLM::Contract::SchemaValidator.validate({ score: 5 }, schema)).to be_empty
expect(RubyLLM::Contract::SchemaValidator.validate({ score: 5.5 }, schema)).to be_empty
errors = RubyLLM::Contract::SchemaValidator.validate({ score: "five" }, schema)
expect(errors.join).to match(/expected number/i)
end
it "validates boolean type" do
schema = make_schema(type: "object", properties: { active: { type: "boolean" } })
expect(RubyLLM::Contract::SchemaValidator.validate({ active: true }, schema)).to be_empty
expect(RubyLLM::Contract::SchemaValidator.validate({ active: false }, schema)).to be_empty
errors = RubyLLM::Contract::SchemaValidator.validate({ active: "true" }, schema)
expect(errors.join).to match(/expected boolean/i)
end
it "validates array type" do
schema = make_schema(type: "object", properties: { tags: { type: "array" } })
expect(RubyLLM::Contract::SchemaValidator.validate({ tags: [1, 2] }, schema)).to be_empty
errors = RubyLLM::Contract::SchemaValidator.validate({ tags: "not array" }, schema)
expect(errors.join).to match(/expected array/i)
end
it "validates object type" do
schema = make_schema(type: "object", properties: { meta: { type: "object" } })
expect(RubyLLM::Contract::SchemaValidator.validate({ meta: { k: "v" } }, schema)).to be_empty
errors = RubyLLM::Contract::SchemaValidator.validate({ meta: "not object" }, schema)
expect(errors.join).to match(/expected object/i)
end
end
# -------------------------------------------------------------------------
# Constraint checking
# -------------------------------------------------------------------------
describe "enum constraint" do
it "accepts value in enum" do
schema = make_schema(type: "object", properties: { color: { type: "string", enum: %w[red green blue] } })
expect(RubyLLM::Contract::SchemaValidator.validate({ color: "red" }, schema)).to be_empty
end
it "rejects value not in enum" do
schema = make_schema(type: "object", properties: { color: { type: "string", enum: %w[red green blue] } })
errors = RubyLLM::Contract::SchemaValidator.validate({ color: "yellow" }, schema)
expect(errors.join).to match(/enum/)
end
end
describe "minimum/maximum constraints" do
it "accepts value within range" do
schema = make_schema(type: "object", properties: { age: { type: "integer", minimum: 0, maximum: 150 } })
expect(RubyLLM::Contract::SchemaValidator.validate({ age: 25 }, schema)).to be_empty
end
it "rejects value below minimum" do
schema = make_schema(type: "object", properties: { age: { type: "integer", minimum: 0 } })
errors = RubyLLM::Contract::SchemaValidator.validate({ age: -1 }, schema)
expect(errors.join).to match(/below minimum/)
end
it "rejects value above maximum" do
schema = make_schema(type: "object", properties: { age: { type: "integer", maximum: 150 } })
errors = RubyLLM::Contract::SchemaValidator.validate({ age: 200 }, schema)
expect(errors.join).to match(/above maximum/)
end
it "accepts value at exact minimum" do
schema = make_schema(type: "object", properties: { age: { type: "integer", minimum: 0 } })
expect(RubyLLM::Contract::SchemaValidator.validate({ age: 0 }, schema)).to be_empty
end
it "accepts value at exact maximum" do
schema = make_schema(type: "object", properties: { age: { type: "integer", maximum: 150 } })
expect(RubyLLM::Contract::SchemaValidator.validate({ age: 150 }, schema)).to be_empty
end
end
describe "minLength/maxLength constraints" do
it "accepts string within length bounds" do
schema = make_schema(type: "object", properties: { name: { type: "string", minLength: 2, maxLength: 50 } })
expect(RubyLLM::Contract::SchemaValidator.validate({ name: "Alice" }, schema)).to be_empty
end
it "rejects string below minLength" do
schema = make_schema(type: "object", properties: { name: { type: "string", minLength: 5 } })
errors = RubyLLM::Contract::SchemaValidator.validate({ name: "Al" }, schema)
expect(errors.join).to match(/minLength/)
end
it "rejects string above maxLength" do
schema = make_schema(type: "object", properties: { name: { type: "string", maxLength: 3 } })
errors = RubyLLM::Contract::SchemaValidator.validate({ name: "Alice" }, schema)
expect(errors.join).to match(/maxLength/)
end
end
describe "minItems/maxItems constraints" do
it "accepts array within item count bounds" do
schema = make_schema(type: "object", properties: { items: { type: "array", minItems: 1, maxItems: 5 } })
expect(RubyLLM::Contract::SchemaValidator.validate({ items: [1, 2, 3] }, schema)).to be_empty
end
it "rejects array below minItems" do
schema = make_schema(type: "object", properties: { items: { type: "array", minItems: 2 } })
errors = RubyLLM::Contract::SchemaValidator.validate({ items: [1] }, schema)
expect(errors.join).to match(/minItems/)
end
it "rejects array above maxItems" do
schema = make_schema(type: "object", properties: { items: { type: "array", maxItems: 2 } })
errors = RubyLLM::Contract::SchemaValidator.validate({ items: [1, 2, 3] }, schema)
expect(errors.join).to match(/maxItems/)
end
end
describe "required constraint" do
it "accepts when all required fields present" do
schema = make_schema(type: "object", required: %w[name age],
properties: { name: { type: "string" }, age: { type: "integer" } })
expect(RubyLLM::Contract::SchemaValidator.validate({ name: "Alice", age: 30 }, schema)).to be_empty
end
it "rejects when required field missing" do
schema = make_schema(type: "object", required: %w[name age],
properties: { name: { type: "string" }, age: { type: "integer" } })
errors = RubyLLM::Contract::SchemaValidator.validate({ name: "Alice" }, schema)
expect(errors.join).to match(/missing required field.*age/)
end
end
describe "additionalProperties constraint" do
it "rejects extra keys when additionalProperties: false" do
schema = make_schema(type: "object", additionalProperties: false,
properties: { name: { type: "string" } })
errors = RubyLLM::Contract::SchemaValidator.validate({ name: "Alice", extra: "bad" }, schema)
expect(errors.join).to match(/additional property/)
end
it "allows extra keys when additionalProperties is not false" do
schema = make_schema(type: "object", properties: { name: { type: "string" } })
expect(RubyLLM::Contract::SchemaValidator.validate({ name: "Alice", extra: "ok" }, schema)).to be_empty
end
end
# -------------------------------------------------------------------------
# Combination constraints
# -------------------------------------------------------------------------
describe "combination: required + enum" do
it "reports both missing required and enum violation" do
schema = make_schema(
type: "object",
required: %w[status color],
properties: {
status: { type: "string", enum: %w[active inactive] },
color: { type: "string", enum: %w[red blue] }
}
)
# status present but wrong enum; color missing entirely
errors = RubyLLM::Contract::SchemaValidator.validate({ status: "unknown" }, schema)
expect(errors.length).to be >= 2
expect(errors.join(" ")).to match(/missing required field.*color/)
expect(errors.join(" ")).to match(/enum/)
end
end
describe "combination: array of objects with required + minItems" do
it "validates complex nested structure" do
schema = make_schema(
type: "object",
properties: {
users: {
type: "array",
minItems: 2,
items: {
type: "object",
required: %w[name email],
properties: {
name: { type: "string", minLength: 1 },
email: { type: "string" },
age: { type: "integer", minimum: 0 }
}
}
}
}
)
# Valid
valid_data = { users: [{ name: "Alice", email: "a@b.com", age: 30 },
{ name: "Bob", email: "b@b.com" }] }
expect(RubyLLM::Contract::SchemaValidator.validate(valid_data, schema)).to be_empty
# minItems violation
too_few = { users: [{ name: "Alice", email: "a@b.com" }] }
errors = RubyLLM::Contract::SchemaValidator.validate(too_few, schema)
expect(errors.join).to match(/minItems/)
# missing required in nested object
missing_email = { users: [{ name: "Alice" }, { name: "Bob", email: "b@b.com" }] }
errors = RubyLLM::Contract::SchemaValidator.validate(missing_email, schema)
expect(errors.join).to match(/missing required field.*email/)
end
end
# -------------------------------------------------------------------------
# 4 levels of nesting
# -------------------------------------------------------------------------
describe "4 levels of nesting" do
it "validates deeply nested structure" do
schema = make_schema(
type: "object",
properties: {
level1: {
type: "object",
required: %w[level2],
properties: {
level2: {
type: "object",
properties: {
level3: {
type: "object",
required: %w[level4],
properties: {
level4: {
type: "string",
enum: %w[deep]
}
}
}
}
}
}
}
}
)
# Valid 4-level nesting
valid = { level1: { level2: { level3: { level4: "deep" } } } }
expect(RubyLLM::Contract::SchemaValidator.validate(valid, schema)).to be_empty
# Invalid value at level 4
invalid = { level1: { level2: { level3: { level4: "shallow" } } } }
errors = RubyLLM::Contract::SchemaValidator.validate(invalid, schema)
expect(errors.join).to match(/enum/)
# Missing required at level 4
missing = { level1: { level2: { level3: {} } } }
errors = RubyLLM::Contract::SchemaValidator.validate(missing, schema)
expect(errors.join).to match(/missing required field/)
end
end
# -------------------------------------------------------------------------
# Non-Hash output with object schema
# -------------------------------------------------------------------------
describe "non-Hash output handling" do
it "rejects nil when schema expects object" do
schema = make_schema(type: "object", properties: { name: { type: "string" } })
errors = RubyLLM::Contract::SchemaValidator.validate(nil, schema)
expect(errors).not_to be_empty
end
it "rejects Array when schema expects object" do
schema = make_schema(type: "object", properties: { name: { type: "string" } })
errors = RubyLLM::Contract::SchemaValidator.validate([1, 2], schema)
expect(errors).not_to be_empty
end
it "rejects String when schema expects object" do
schema = make_schema(type: "object", properties: { name: { type: "string" } })
errors = RubyLLM::Contract::SchemaValidator.validate("hello", schema)
expect(errors).not_to be_empty
end
end
end
# ===========================================================================
# 3. RETRY -- deterministic behavior
# ===========================================================================
describe "CERTIFICATION: Retry" do
describe "exactly N attempts when all fail" do
it "makes exactly 3 attempts when max_attempts is 3 and all fail" do
step = Class.new(RubyLLM::Contract::Step::Base) do
input_type String
output_type RubyLLM::Contract::Types::Hash
contract { parse :json }
prompt { |input| user "Process: #{input}" }
retry_policy attempts: 3, retry_on: %i[parse_error]
end
call_count = 0
adapter = Class.new(RubyLLM::Contract::Adapters::Base) do
define_method(:call) do |**_opts|
call_count += 1
RubyLLM::Contract::Adapters::Response.new(
content: "not json at all",
usage: { input_tokens: 10, output_tokens: 5 }
)
end
end.new
result = step.run("test", context: { adapter: adapter })
expect(result.status).to eq(:parse_error)
expect(call_count).to eq(3),
"Expected exactly 3 adapter calls, got #{call_count}"
end
it "makes exactly 1 attempt when max_attempts is 1" do
step = Class.new(RubyLLM::Contract::Step::Base) do
input_type String
output_type RubyLLM::Contract::Types::Hash
contract { parse :json }
prompt { |input| user "Process: #{input}" }
retry_policy attempts: 1, retry_on: %i[parse_error]
end
call_count = 0
adapter = Class.new(RubyLLM::Contract::Adapters::Base) do
define_method(:call) do |**_opts|
call_count += 1
RubyLLM::Contract::Adapters::Response.new(
content: "bad",
usage: { input_tokens: 10, output_tokens: 5 }
)
end
end.new
step.run("test", context: { adapter: adapter })
expect(call_count).to eq(1)
end
it "stops early on success (attempt 2 of 5)" do
step = Class.new(RubyLLM::Contract::Step::Base) do
input_type String
output_type RubyLLM::Contract::Types::Hash
contract { parse :json }
prompt { |input| user "Process: #{input}" }
retry_policy attempts: 5, retry_on: %i[parse_error]
end
call_count = 0
adapter = Class.new(RubyLLM::Contract::Adapters::Base) do
define_method(:call) do |**_opts|
call_count += 1
content = call_count >= 2 ? '{"ok": true}' : "bad"
RubyLLM::Contract::Adapters::Response.new(
content: content,
usage: { input_tokens: 10, output_tokens: 5 }
)
end
end.new
result = step.run("test", context: { adapter: adapter })
expect(result.status).to eq(:ok)
expect(call_count).to eq(2),
"Should stop after 2 calls (success on attempt 2)"
end
end
describe "model escalation uses correct model per attempt" do
it "passes the correct model to adapter on each attempt" do
step = Class.new(RubyLLM::Contract::Step::Base) do
input_type String
output_type RubyLLM::Contract::Types::Hash
contract { parse :json }
prompt { |input| user "Process: #{input}" }
retry_policy do
escalate "gpt-3.5-turbo", "gpt-4", "gpt-4-turbo"
retry_on :parse_error
end
end
models_seen = []
adapter = Class.new(RubyLLM::Contract::Adapters::Base) do
define_method(:call) do |messages:, **opts|
models_seen << opts[:model]
content = models_seen.length >= 3 ? '{"ok": true}' : "bad"
RubyLLM::Contract::Adapters::Response.new(
content: content,
usage: { input_tokens: 10, output_tokens: 5 }
)
end
end.new
result = step.run("test", context: { adapter: adapter })
expect(result.status).to eq(:ok)
expect(models_seen).to eq(["gpt-3.5-turbo", "gpt-4", "gpt-4-turbo"]),
"Models should escalate in order, got: #{models_seen}"
end
it "uses last model when attempts exceed model list length" do
policy = RubyLLM::Contract::Step::RetryPolicy.new do
escalate "model-a", "model-b"
attempts 4
end
expect(policy.model_for_attempt(0, "default")).to eq("model-a")
expect(policy.model_for_attempt(1, "default")).to eq("model-b")
expect(policy.model_for_attempt(2, "default")).to eq("model-b") # falls back to last
expect(policy.model_for_attempt(3, "default")).to eq("model-b") # falls back to last
end
it "uses default model when no escalation models set" do
policy = RubyLLM::Contract::Step::RetryPolicy.new(attempts: 3)
expect(policy.model_for_attempt(0, "default-model")).to eq("default-model")
expect(policy.model_for_attempt(1, "default-model")).to eq("default-model")
expect(policy.model_for_attempt(2, "default-model")).to eq("default-model")
end
end
describe "attempt log correctness" do
it "has exactly N entries with correct models and statuses" do
step = Class.new(RubyLLM::Contract::Step::Base) do
input_type String
output_type RubyLLM::Contract::Types::Hash
contract { parse :json }
prompt { |input| user "Process: #{input}" }
retry_policy do
escalate "model-a", "model-b", "model-c"
retry_on :parse_error
end
end
call_count = 0
adapter = Class.new(RubyLLM::Contract::Adapters::Base) do
define_method(:call) do |**_opts|
call_count += 1
content = call_count >= 3 ? '{"done": true}' : "bad"
RubyLLM::Contract::Adapters::Response.new(
content: content,
usage: { input_tokens: 50, output_tokens: 25 }
)
end
end.new
result = step.run("test", context: { adapter: adapter })
attempts = result.trace.attempts
expect(attempts.length).to eq(3), "Expected 3 attempt log entries"
expect(attempts[0][:attempt]).to eq(1)
expect(attempts[0][:model]).to eq("model-a")
expect(attempts[0][:status]).to eq(:parse_error)
expect(attempts[1][:attempt]).to eq(2)
expect(attempts[1][:model]).to eq("model-b")
expect(attempts[1][:status]).to eq(:parse_error)
expect(attempts[2][:attempt]).to eq(3)
expect(attempts[2][:model]).to eq("model-c")
expect(attempts[2][:status]).to eq(:ok)
end
end
describe "aggregated usage sums correctly" do
it "sums known values across all attempts" do
step = Class.new(RubyLLM::Contract::Step::Base) do
input_type String
output_type RubyLLM::Contract::Types::Hash
contract { parse :json }
prompt { |input| user "Process: #{input}" }
retry_policy attempts: 3, retry_on: %i[parse_error]
end
attempt_num = 0
adapter = Class.new(RubyLLM::Contract::Adapters::Base) do
define_method(:call) do |**_opts|
attempt_num += 1
content = attempt_num >= 3 ? '{"ok": true}' : "bad"
# Each attempt: input=100*attempt_num, output=50*attempt_num
RubyLLM::Contract::Adapters::Response.new(
content: content,
usage: { input_tokens: 100 * attempt_num, output_tokens: 50 * attempt_num }
)
end
end.new
result = step.run("test", context: { adapter: adapter })
# Total: 100+200+300 = 600 input, 50+100+150 = 300 output
expect(result.trace.usage[:input_tokens]).to eq(600),
"Expected 600 input tokens (100+200+300), got #{result.trace.usage[:input_tokens]}"
expect(result.trace.usage[:output_tokens]).to eq(300),
"Expected 300 output tokens (50+100+150), got #{result.trace.usage[:output_tokens]}"
end
end
describe "non-retryable status stops immediately" do
it "does not retry on :input_error even when retry_on includes parse_error" do
step = Class.new(RubyLLM::Contract::Step::Base) do
input_type String
output_type RubyLLM::Contract::Types::Hash
contract { parse :json }
prompt { |input| user "Process: #{input}" }
retry_policy attempts: 3, retry_on: %i[parse_error]
end
call_count = 0
adapter = Class.new(RubyLLM::Contract::Adapters::Base) do
define_method(:call) do |**_opts|
call_count += 1
RubyLLM::Contract::Adapters::Response.new(
content: '{"ok": true}',
usage: { input_tokens: 10, output_tokens: 5 }
)
end
end.new
# Integer input to a String input_type step causes :input_error
result = step.run(42, context: { adapter: adapter })
expect(result.status).to eq(:input_error)
expect(call_count).to eq(0),
"Should not call adapter at all for input_error"
end
end
end
# ===========================================================================
# 4. PIPELINE -- data integrity end-to-end
# ===========================================================================
describe "CERTIFICATION: Pipeline" do
# Helper step classes for pipeline tests
let(:step_a) do
Class.new(RubyLLM::Contract::Step::Base) do
input_type String
output_type RubyLLM::Contract::Types::Hash
contract { parse :json }
prompt { |input| user "step_a: #{input}" }
end
end
let(:step_b) do
Class.new(RubyLLM::Contract::Step::Base) do
input_type RubyLLM::Contract::Types::Hash
output_type RubyLLM::Contract::Types::Hash
contract { parse :json }
prompt { |input| user "step_b: #{input}" }
end
end
let(:step_c) do
Class.new(RubyLLM::Contract::Step::Base) do
input_type RubyLLM::Contract::Types::Hash
output_type RubyLLM::Contract::Types::Hash
contract { parse :json }
prompt { |input| user "step_c: #{input}" }
end
end
let(:step_d) do
Class.new(RubyLLM::Contract::Step::Base) do
input_type RubyLLM::Contract::Types::Hash
output_type RubyLLM::Contract::Types::Hash
contract { parse :json }
prompt { |input| user "step_d: #{input}" }
end
end
describe "4-step pipeline success" do
it "outputs_by_step has all 4 steps on success" do
sa = step_a
sb = step_b
sc = step_c
sd = step_d
pipeline = Class.new(RubyLLM::Contract::Pipeline::Base) do
step sa, as: :alpha
step sb, as: :beta
step sc, as: :gamma
step sd, as: :delta
end
result = pipeline.test("input", responses: {
alpha: '{"from": "alpha", "val": 1}',
beta: '{"from": "beta", "val": 2}',
gamma: '{"from": "gamma", "val": 3}',
delta: '{"from": "delta", "val": 4}'
})
expect(result.status).to eq(:ok)
expect(result.outputs_by_step.keys).to contain_exactly(:alpha, :beta, :gamma, :delta)
expect(result.outputs_by_step[:alpha]).to eq({ from: "alpha", val: 1 })
expect(result.outputs_by_step[:delta]).to eq({ from: "delta", val: 4 })
expect(result.failed_step).to be_nil
end
end
describe "4-step pipeline failure at step 3" do
it "outputs_by_step has only completed steps (1 and 2)" do
sa = step_a
sb = step_b
sd = step_d
step_fail = Class.new(RubyLLM::Contract::Step::Base) do
input_type RubyLLM::Contract::Types::Hash
output_type RubyLLM::Contract::Types::Hash
contract { parse :json }
prompt { |input| user "fail: #{input}" }
validate("intentional fail") { |_o| false }
end
pipeline = Class.new(RubyLLM::Contract::Pipeline::Base) do
step sa, as: :alpha
step sb, as: :beta
step step_fail, as: :gamma
step sd, as: :delta
end
result = pipeline.test("input", responses: {
alpha: '{"from": "alpha"}',
beta: '{"from": "beta"}',
gamma: '{"from": "gamma"}',
delta: '{"from": "delta"}'
})
expect(result.status).not_to eq(:ok)
expect(result.failed_step).to eq(:gamma)
expect(result.outputs_by_step.keys).to contain_exactly(:alpha, :beta)
expect(result.outputs_by_step).not_to have_key(:gamma)
expect(result.outputs_by_step).not_to have_key(:delta)
end
end
describe "no cross-step data leakage" do
it "each step receives only the previous step output as input" do
sa = step_a
step_spy = Class.new(RubyLLM::Contract::Step::Base) do
input_type RubyLLM::Contract::Types::Hash
output_type RubyLLM::Contract::Types::Hash
contract { parse :json }
prompt { |input| user "spy: #{input}" }
end
ss = step_spy
pipeline = Class.new(RubyLLM::Contract::Pipeline::Base) do
step sa, as: :first
step ss, as: :second
step ss, as: :third
end
# Each step transforms data independently
result = pipeline.test("hello", responses: {
first: '{"step": "first", "data": "A"}',
second: '{"step": "second", "data": "B"}',
third: '{"step": "third", "data": "C"}'
})
expect(result.status).to eq(:ok)
# Step 3 output should be from step 3 response, not step 1
expect(result.outputs_by_step[:third]).to eq({ step: "third", data: "C" })
# The pipeline passes step N's output as step N+1's input.
# Step 3 cannot see step 1's output directly -- it only receives step 2's output.
# This is enforced by the pipeline runner's current_input = result.parsed_output pattern.
# Verify the final output in outputs_by_step is from step 3, not step 1.
expect(result.outputs_by_step[:third][:step]).to eq("third")
expect(result.outputs_by_step[:third][:data]).to eq("C")
end
end
describe "pipeline trace completeness" do
it "trace has total_usage summed from all steps" do
sa = step_a
sb = step_b
pipeline = Class.new(RubyLLM::Contract::Pipeline::Base) do
step sa, as: :first
step sb, as: :second
end
result = pipeline.test("hello", responses: {
first: '{"ok": true}',
second: '{"ok": true}'
})
expect(result.trace).not_to be_nil
expect(result.trace.total_usage).to be_a(Hash)
expect(result.trace.total_usage).to have_key(:input_tokens)
expect(result.trace.total_usage).to have_key(:output_tokens)
expect(result.trace.trace_id).to match(/\A[0-9a-f-]+\z/)
expect(result.trace.total_latency_ms).to be_a(Integer)
end
end
end
# ===========================================================================
# 5. EVAL -- correctness
# ===========================================================================
describe "CERTIFICATION: Eval" do
describe "sample_response that passes everything" do
it "returns Report#passed? true and score 1.0" do
step = Class.new(RubyLLM::Contract::Step::Base) do
prompt { user "{input}" }
output_type RubyLLM::Contract::Types::Hash
contract { parse :json }
validate("has name") { |o| o[:name].is_a?(String) }
end
adapter = RubyLLM::Contract::Adapters::Test.new(response: '{"name": "Alice"}')
ds = RubyLLM::Contract::Eval::Dataset.define("passing") do
add_case("basic", input: "test", expected: { name: "Alice" })
end
report = RubyLLM::Contract::Eval::Runner.run(step: step, dataset: ds, context: { adapter: adapter })
expect(report.passed?).to be true
expect(report.score).to eq(1.0)
expect(report.results.first.passed?).to be true
end
end
describe "sample_response that fails schema" do
it "fails before verify (contract failure)" do
step = Class.new(RubyLLM::Contract::Step::Base) do
prompt { user "{input}" }
output_type RubyLLM::Contract::Types::Hash
contract { parse :json }
validate("has name") { |o| o[:name].is_a?(String) }
end
# Adapter returns non-JSON, causing parse error
adapter = RubyLLM::Contract::Adapters::Test.new(response: "not json at all")
ds = RubyLLM::Contract::Eval::Dataset.define("failing_schema") do
add_case("bad response", input: "test", expected: { name: "Alice" })
end
report = RubyLLM::Contract::Eval::Runner.run(step: step, dataset: ds, context: { adapter: adapter })
expect(report.passed?).to be false
expect(report.score).to eq(0.0)
expect(report.results.first.passed?).to be false