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
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
use super::*;
use crate::audio::whisper::{
options::DecodingOptions,
task_facts::{SpanKnowledge, TaskFacts},
};
// ---------------------------------------------------------------------
// merge_transcription_results
// ---------------------------------------------------------------------
#[test]
fn merge_transcription_results_concatenates_and_reids() {
// NOTE: the brief's literal snippet called `TranscriptionResult::new()`
// with no arguments; the shipped constructor requires all four fields
// (text, segments, language, timings) with no defaulted/zero-arg form
// (this module's own doc: "no honest default means no Default" applies
// equally to a bare `new()`). Built blank here, then mutated via the
// `set_*` calls the brief's snippet already used. Likewise `.into()` on
// the string literals is dropped: against `set_text`/`set_language`'s
// generic `impl Into<String>` parameter it is ambiguous (E0283 - `&str`
// implements `Into<T>` for several `T`), the same fix already applied
// to `WordTiming::new`'s call site above.
let mut first = TranscriptionResult::new("", Vec::new(), "", TranscriptionTimings::new());
let mut seg0 = TranscriptionSegment::new();
seg0.set_id(0).set_start(0.0).set_end(1.0);
first
.set_text("hello")
.set_segments(vec![seg0])
.set_language("en");
let mut second = TranscriptionResult::new("", Vec::new(), "", TranscriptionTimings::new());
let mut seg1 = TranscriptionSegment::new();
seg1.set_id(0).set_start(30.0).set_end(31.0);
second.set_text("world").set_segments(vec![seg1]);
let merged = merge_transcription_results(&[first, second]);
assert_eq!(merged.text(), "hello world");
assert_eq!(merged.segments_slice().len(), 2);
assert_eq!(merged.segments_slice()[1].id(), 1); // resultIndex + segmentIndex (:89-94)
assert_eq!(merged.language(), "en");
}
#[test]
fn merge_preserves_survivor_ids_when_dropping_blanks() {
// F4 (codex round 2). The VAD path ALWAYS routes chunk results through
// `merge_transcription_results_with_options` (transcribe::transcribe), and
// that merge reindexed every survivor to `result_index + segment_index` --
// silently collapsing the [0, 2] gap a blank-audio drop leaves back to
// [0, 1], so `drop_blank_audio`'s documented "survivors keep their decoded
// ids" promise held only on the unmerged single-chunk path.
//
// One chunk, speech-blank-speech, the blank already dropped in the task ->
// survivors carry decode ids 0 and 2. Match survivors by tokens, assert ids.
let mut speech0 = TranscriptionSegment::new();
speech0
.set_id(0)
.set_start(0.0)
.set_end(1.0)
.set_text(" Hello")
.set_tokens(vec![10]);
let mut speech2 = TranscriptionSegment::new();
speech2
.set_id(2)
.set_start(2.0)
.set_end(3.0)
.set_text(" World")
.set_tokens(vec![20]);
let chunk = TranscriptionResult::new(
"Hello World",
vec![speech0, speech2],
"en",
TranscriptionTimings::new(),
);
// Dropping ON (the default): ids preserved, the [0, 2] hole intact.
let dropped =
merge_transcription_results_with_options(std::slice::from_ref(&chunk), &DecodingOptions::new());
assert_eq!(
dropped
.segments_slice()
.iter()
.map(TranscriptionSegment::id)
.collect::<Vec<_>>(),
vec![0, 2],
"survivors keep their decode ids; the dropped segment's gap is preserved"
);
// Survivors matched by tokens, NOT id: the second is still " World".
assert_eq!(dropped.segments_slice()[1].tokens_slice(), &[20]);
assert_eq!(dropped.segments_slice()[1].start(), 2.0);
// Dropping OFF: EXACTLY Swift's `result_index + segment_index` reindexing
// -- the false path stays byte-for-byte Swift, so the same survivors come
// back densely renumbered [0, 1].
let swift = merge_transcription_results_with_options(
std::slice::from_ref(&chunk),
&DecodingOptions::new().maybe_drop_blank_audio(false),
);
assert_eq!(
swift
.segments_slice()
.iter()
.map(TranscriptionSegment::id)
.collect::<Vec<_>>(),
vec![0, 1],
"Swift-exact reindexing (result_index + segment_index) when dropping is off"
);
assert_eq!(
swift.segments_slice()[1].tokens_slice(),
&[20],
"still the same survivor, only its id differs"
);
// Multiple chunks, dropping ON: each VAD chunk is its own decode with its
// own id space, so both lone survivors carry decode id 0. The
// `result_index` offset is what keeps them from COLLIDING to [0, 0] -- the
// id preservation must still disambiguate across chunks, landing [0, 1].
let mut chunk_a_seg = TranscriptionSegment::new();
chunk_a_seg
.set_id(0)
.set_text(" Hello")
.set_tokens(vec![10]);
let mut chunk_b_seg = TranscriptionSegment::new();
chunk_b_seg
.set_id(0)
.set_text(" World")
.set_tokens(vec![20]);
let chunk_a = TranscriptionResult::new(
"Hello",
vec![chunk_a_seg],
"en",
TranscriptionTimings::new(),
);
let chunk_b = TranscriptionResult::new(
"World",
vec![chunk_b_seg],
"en",
TranscriptionTimings::new(),
);
let two_chunks =
merge_transcription_results_with_options(&[chunk_a, chunk_b], &DecodingOptions::new());
assert_eq!(
two_chunks
.segments_slice()
.iter()
.map(TranscriptionSegment::id)
.collect::<Vec<_>>(),
vec![0, 1],
"each chunk's lone `id() == 0` must be offset by result_index, not collapsed to [0, 0]"
);
assert_eq!(two_chunks.segments_slice()[1].tokens_slice(), &[20]);
}
#[test]
fn merge_drop_on_ids_stay_injective_across_multi_segment_chunks() {
// F4 (codex round 3). The round-2 test above uses ONE segment per chunk, so
// it never exercised `result_index + segment.id()`'s collision on
// MULTI-segment chunks: `[0,1] + [0,1]` renumbered to `[0,1,1,2]`, and a
// blank-dropped `[0,2] + [0,1]` to `[0,2,1,2]` -- duplicate ids either way.
// The running-base mapping must keep (chunk, original_id) injective while
// preserving each chunk's own local gaps.
let seg = |id: usize, token: u32| {
let mut s = TranscriptionSegment::new();
s.set_id(id).set_tokens(vec![token]);
s
};
// Chunk A carries an INTERNAL dropped-id gap -- ids [0, 2], its segment 1
// was a dropped blank. Chunk B is dense -- ids [0, 1].
let chunk_a = TranscriptionResult::new(
"A",
vec![seg(0, 10), seg(2, 12)],
"en",
TranscriptionTimings::new(),
);
let chunk_b = TranscriptionResult::new(
"B",
vec![seg(0, 20), seg(1, 21)],
"en",
TranscriptionTimings::new(),
);
let merged =
merge_transcription_results_with_options(&[chunk_a, chunk_b], &DecodingOptions::new());
let ids: Vec<usize> = merged
.segments_slice()
.iter()
.map(TranscriptionSegment::id)
.collect();
// Chunk A: base 0 -> [0, 2] (its local gap at 1 preserved). Span = 2 + 1 = 3.
// Chunk B: base 3 -> [3, 4]. The pre-fix formula produced
// [0+0, 0+2, 1+0, 1+1] = [0, 2, 1, 2] -- a duplicate 2.
assert_eq!(
ids,
vec![0, 2, 3, 4],
"injective across chunks, each chunk's local gap preserved"
);
let unique: std::collections::HashSet<usize> = ids.iter().copied().collect();
assert_eq!(
unique.len(),
ids.len(),
"(chunk, original_id) must map injectively -- no id collisions"
);
// Survivor identity travels through the re-id, matched by tokens not id.
assert_eq!(
merged
.segments_slice()
.iter()
.map(|s| s.tokens_slice()[0])
.collect::<Vec<_>>(),
vec![10, 12, 20, 21],
);
}
#[test]
fn merge_drop_on_advances_the_id_base_past_an_all_dropped_chunk() {
// F2 (codex round 5), hole (a). A blank-only VAD chunk decodes ONE segment
// (id 0), which the blank-audio drop then removes -- leaving the chunk with
// zero survivors but a DECODED span of 1. The merge must advance its running
// id base by that span, not by the (empty) survivors' extent: otherwise an
// all-dropped chunk is indistinguishable from a genuinely zero-window one,
// and the FOLLOWING speech chunk's survivor renumbers down onto the ordinal
// the blank consumed.
//
// The invariant the finding pins: the speech survivor keeps the SAME id under
// both drop settings. Under drop OFF the blank is present (id 0) and Swift's
// `result_index + segment_index` lands the speech at 1; under drop ON the
// blank is gone but its consumed ordinal still shifts the speech to 1.
let speech = || {
let mut s = TranscriptionSegment::new();
s.set_id(0).set_text(" World").set_tokens(vec![20]);
TranscriptionResult::new(" World", vec![s], "en", TranscriptionTimings::new())
.with_task_facts(TaskFacts::unknown().with_decoded_span(SpanKnowledge::Exact(1)))
};
let speech_id = |merged: &TranscriptionResult| {
merged
.segments_slice()
.iter()
.find(|s| s.tokens_slice() == [20])
.expect("the speech survivor is in the merge")
.id()
};
// Drop ON: the blank was dropped in the task, so the chunk has zero survivors
// but reports its decoded span of 1.
let all_dropped = TranscriptionResult::new("", Vec::new(), "en", TranscriptionTimings::new())
.with_task_facts(TaskFacts::unknown().with_decoded_span(SpanKnowledge::Exact(1)));
let dropped =
merge_transcription_results_with_options(&[all_dropped, speech()], &DecodingOptions::new());
assert!(
dropped.segments_slice().len() == 1 && speech_id(&dropped) == 1,
"the speech survivor sits past the all-dropped chunk's consumed ordinal, got id {}",
speech_id(&dropped)
);
// Drop OFF: the blank is present (id 0), and Swift's exact reindexing lands
// the speech at result_index 1.
let mut blank = TranscriptionSegment::new();
blank
.set_id(0)
.set_text(" [BLANK_AUDIO]")
.set_tokens(vec![99]);
let blank_kept = TranscriptionResult::new(
" [BLANK_AUDIO]",
vec![blank],
"en",
TranscriptionTimings::new(),
)
.with_task_facts(TaskFacts::unknown().with_decoded_span(SpanKnowledge::Exact(1)));
let emitted = merge_transcription_results_with_options(
&[blank_kept, speech()],
&DecodingOptions::new().maybe_drop_blank_audio(false),
);
assert_eq!(
speech_id(&emitted),
1,
"drop OFF is exact Swift: result_index + segment_index lands the speech at 1"
);
assert_eq!(
speech_id(&dropped),
speech_id(&emitted),
"the speech survivor keeps the same id under both drop settings"
);
}
/// A speech chunk decoding one segment carrying `token`, tracking a decoded
/// span of 1 (coremlit issue #14, codex round 6 regression fixtures).
fn span_one_speech(token: u32) -> TranscriptionResult {
let mut s = TranscriptionSegment::new();
s.set_id(0).set_text(" W").set_tokens(vec![token]);
TranscriptionResult::new(" W", vec![s], "en", TranscriptionTimings::new())
.with_task_facts(TaskFacts::unknown().with_decoded_span(SpanKnowledge::Exact(1)))
}
/// Segment ids of a result, in order.
fn segment_ids(result: &TranscriptionResult) -> Vec<usize> {
result.segments_slice().iter().map(|s| s.id()).collect()
}
#[test]
fn drop_on_merge_is_associative_over_the_id_span() {
// R6-F3 (codex round 6). A staged merge -- a VAD result re-merged at streaming
// finalize -- must renumber segments IDENTICALLY to a one-shot merge, which
// requires the merged result to STORE its aggregate id span rather than drop
// it. Script [speech(span 1), all-dropped(span 1), speech(span 1)] under drop
// ON: the dropped middle chunk still consumes an ordinal, so the second speech
// sits at id 2, and a staged re-merge must reach the same 2.
//
// Mutation proof: revert the merge to store no aggregate span (the merged
// result's `decoded_span` back to `None`) and the staged ids collapse to
// [0, 1], failing the associativity assertion below.
let opts = DecodingOptions::new(); // drop ON (the default)
let a = span_one_speech(20);
let b = TranscriptionResult::new("", Vec::new(), "en", TranscriptionTimings::new())
.with_task_facts(TaskFacts::unknown().with_decoded_span(SpanKnowledge::Exact(1)));
let c = span_one_speech(21);
// One-shot over all three.
let one_shot =
merge_transcription_results_with_options(&[a.clone(), b.clone(), c.clone()], &opts);
assert_eq!(
segment_ids(&one_shot),
vec![0, 2],
"the second speech sits past the dropped chunk's consumed ordinal"
);
assert_eq!(
one_shot.task_facts().decoded_span(),
SpanKnowledge::Exact(3),
"the aggregate span is the exact sum of the children's"
);
// Staged: merge [a, b] (the VAD result), then re-merge that with c (finalize).
let vad = merge_transcription_results_with_options(&[a, b], &opts);
assert_eq!(
vad.task_facts().decoded_span(),
SpanKnowledge::Exact(2),
"the VAD result STORES its aggregate span (the R6-F3 fix)"
);
let staged = merge_transcription_results_with_options(&[vad, c], &opts);
assert_eq!(
segment_ids(&staged),
segment_ids(&one_shot),
"a staged re-merge renumbers identically to a one-shot merge"
);
assert_eq!(staged.task_facts().decoded_span(), SpanKnowledge::Exact(3));
}
#[test]
fn drop_on_merge_preserves_known_empty_span_after_unknown_prefix() {
// THE round-12 regression. A reachable history the pre-round-12 absorbing-`None`
// span numbered differently by grouping:
// A -- a survivor at local id 0, span `AtLeast(1)`: the shape a VAD run leaves
// when it drops an errored chunk but keeps a survivor whose 1 ordinal is a
// KNOWN lower bound on the (now-unknown-exact) total;
// B -- NO survivors, span `Exact(1)`: a known-empty span (a blank-only chunk
// that allocated an ordinal then had it filtered);
// T -- a trailing survivor at local id 0, span `Exact(1)`.
// A one-shot `merge([A, B, T])` numbers the survivors `[0, 2]` (A's survivor at
// 0, B's known ordinal consumes 1, T's survivor at 2). The pre-round-12 fold let
// A's unknown span ABSORB B's `Exact(1)` to a bound-less `None`, so a staged
// `merge([merge([A, B]), T])` could recover only the intermediate's survivor
// extent (1) and renumbered T onto id 1 -- `[0, 1]`. The round-12 `SpanKnowledge`
// sum keeps B's known ordinal as the aggregate's lower bound (`AtLeast(1) +
// Exact(1) = AtLeast(2)`), so ALL THREE groupings store `AtLeast(3)` and number
// T identically at id 2.
//
// Mutation proof: revert `SpanKnowledge::merge`'s `AtLeast` arm to the absorbing
// `_ => Self::AtLeast(0)` and the staged groupings lose B's known ordinal,
// landing T on id 1 while the one-shot keeps `[0, 2]` -- the equalities below fail.
let a = || {
let mut seg = TranscriptionSegment::new();
seg.set_id(0).set_text(" A").set_tokens(vec![20]);
TranscriptionResult::new(" A", vec![seg], "en", TranscriptionTimings::new())
.with_task_facts(TaskFacts::unknown().with_decoded_span(SpanKnowledge::AtLeast(1)))
};
let b = || {
TranscriptionResult::new("", Vec::new(), "en", TranscriptionTimings::new())
.with_task_facts(TaskFacts::unknown().with_decoded_span(SpanKnowledge::Exact(1)))
};
let t = || span_one_speech(21); // trailing survivor at local id 0, Exact(1)
let opts = DecodingOptions::new(); // drop ON (the default)
let one_shot = merge_transcription_results_with_options(&[a(), b(), t()], &opts);
let left_staged = merge_transcription_results_with_options(
&[
merge_transcription_results_with_options(&[a(), b()], &opts),
t(),
],
&opts,
);
let right_staged = merge_transcription_results_with_options(
&[
a(),
merge_transcription_results_with_options(&[b(), t()], &opts),
],
&opts,
);
for (label, merged) in [
("one-shot", &one_shot),
("left-staged", &left_staged),
("right-staged", &right_staged),
] {
assert_eq!(
segment_ids(merged),
vec![0, 2],
"{label}: B's known empty span must keep T on id 2, never absorbed away to id 1",
);
assert_eq!(
merged.task_facts().decoded_span(),
SpanKnowledge::AtLeast(3),
"{label}: the stored aggregate is the grouping-independent lower bound",
);
}
}
#[test]
fn drop_on_merge_is_associative_with_mixed_tracked_and_untracked_spans() {
// F1 (codex round 6 post-consolidation), corrected under round 12. The invariant
// this test guards is unchanged: `[wholly-unknown-with-one-survivor, exact span
// 1, exact span 1]` must renumber IDENTICALLY one-shot vs. staged (the round-6 F1
// defect renumbered them differently).
//
// ORACLE CORRECTION (codex round 13, M1): the stored span now carries the SAME
// survivor floor the ids advanced by. `a` is a public `new` result — a survivor
// at local id 0 but a WHOLLY-UNKNOWN carried span (`AtLeast(0)`) — so its
// survivor proves >= 1 allocated ordinal that its raw `AtLeast(0)` does not state.
// The drop-ON fold folds `a`'s EFFECTIVE span (that raw bound floored at its own
// survivor extent, `AtLeast(0)` -> `AtLeast(1)`), the very value `a`'s id-base
// advance used, so the aggregate is `AtLeast(1) + Exact(1) + Exact(1) =
// AtLeast(3)` — the survivors' true lower bound, in EVERY grouping. The
// pre-round-13 raw-`SpanKnowledge` fold stored `AtLeast(2)` here (`AtLeast(0) +
// Exact(1) + Exact(1)`), discarding `a`'s survivor floor even as the ids committed
// to it; the round-12 read-time floor still kept THESE ids `[0, 1, 2]` (b/c's
// small exact spans let the intermediate's survivor extent recover the lost
// floor), but a sparser sibling span defeats that recovery — see
// `drop_on_merge_staging_materializes_unknown_survivor_floor_before_sparse_span`.
//
// Mutation proof: revert the drop-ON fold to fold the RAW carried spans (drop the
// `with_decoded_span(effective_span_knowledge(...))` substitution) and the stored
// spans read back `AtLeast(2)`/`AtLeast(1)`/`AtLeast(2)` — `a`'s survivor floor
// discarded from the stored fact (the ids stay `[0, 1, 2]` either way here).
let opts = DecodingOptions::new(); // drop ON (the default)
// A: a public `new` result — one surviving segment (local id 0), span
// WHOLLY UNKNOWN (`AtLeast(0)`), the documented contract of the public constructor.
let untracked = |token: u32| {
let mut seg = TranscriptionSegment::new();
seg.set_id(0).set_text(" A").set_tokens(vec![token]);
TranscriptionResult::new(" A", vec![seg], "en", TranscriptionTimings::new())
};
let a = untracked(20);
assert_eq!(
a.task_facts().decoded_span(),
SpanKnowledge::wholly_unknown(),
"the public constructor leaves the span wholly unknown, yet a segment survives"
);
let b = span_one_speech(21); // exact span 1, one segment
let c = span_one_speech(22); // exact span 1, one segment
let one_shot =
merge_transcription_results_with_options(&[a.clone(), b.clone(), c.clone()], &opts);
assert_eq!(
segment_ids(&one_shot),
vec![0, 1, 2],
"the wholly-unknown child's one survivor still consumes ordinal 0"
);
assert_eq!(
one_shot.task_facts().decoded_span(),
SpanKnowledge::AtLeast(3),
"the stored fact carries `a`'s survivor floor the ids advanced by (round 13, M1): \
`AtLeast(1) + Exact(1) + Exact(1)`, not the raw `AtLeast(2)`",
);
// Staged: merge [a, b], then re-merge that with c.
let ab = merge_transcription_results_with_options(&[a, b], &opts);
assert_eq!(
ab.task_facts().decoded_span(),
SpanKnowledge::AtLeast(2),
"the intermediate carries `a`'s survivor floor plus b's ordinal (round 13, M1): \
`AtLeast(1) + Exact(1)`, not the raw `AtLeast(1)`",
);
let staged = merge_transcription_results_with_options(&[ab, c], &opts);
assert_eq!(
segment_ids(&staged),
segment_ids(&one_shot),
"a staged re-merge renumbers identically to a one-shot merge — the invariant, \
now carried by the associative stored span plus the read-time extent floor",
);
assert_eq!(
segment_ids(&staged),
vec![0, 1, 2],
"and both groupings land the same ids",
);
assert_eq!(
staged.task_facts().decoded_span(),
SpanKnowledge::AtLeast(3),
"the staged store matches the one-shot's `AtLeast(3)` — associative, and now \
carrying the survivor floor in the stored fact (round 13, M1)",
);
}
#[test]
fn drop_on_merge_staging_materializes_unknown_survivor_floor_before_sparse_span() {
// THE round-13 M1 regression. A drop-ON merge derives each child's id
// contribution from its EFFECTIVE span — the carried span floored at its own
// survivor extent — but before round 13 it STORED only the raw carried sum,
// discarding the survivor floor the ids had already committed to. A staged
// re-merge then read that under-count back and, when a sibling's SPARSE span put
// the survivor extent out of the read-time floor's reach, renumbered a trailing
// chunk onto an id the one-shot merge had left free.
//
// The reachable history (public/hand-built, all with drop_blank_audio = true):
// A -- a survivor at local id 0, span `AtLeast(0)` (the public `new` default):
// its survivor proves >= 1 ordinal its wholly-unknown span does not state;
// B -- a survivor at local id 0, span `Exact(5)`: five ordinals allocated, only
// id 0 surviving a filter (a legitimate carried-span-exceeds-extent shape);
// T -- a trailing survivor at local id 0, span `Exact(1)`.
// A's effective span is `AtLeast(1)` (its `AtLeast(0)` floored at extent 1), so a
// one-shot `merge([A, B, T])` advances the id base 1 (A) then 5 (B) and lands T at
// id 6 -> `[0, 1, 6]`, storing `AtLeast(1) + Exact(5) + Exact(1) = AtLeast(7)`.
//
// Pre-round-13 the left-staged intermediate `merge([A, B])` stored the RAW
// `AtLeast(0) + Exact(5) = AtLeast(5)`, losing A's survivor floor; its own two
// survivors span only extent 2, so the read-time floor (`max(5, 2) = 5`) could NOT
// recover the lost ordinal, and re-merging with T landed it at id 5 -> `[0, 1, 5]`,
// diverging from the one-shot `[0, 1, 6]` and storing `AtLeast(6)`. Folding the
// EFFECTIVE span into the store makes the intermediate carry `AtLeast(6)`, so every
// grouping numbers T at 6 and stores `AtLeast(7)`.
//
// Mutation proof: revert the drop-ON fold to fold the RAW carried spans (drop the
// `with_decoded_span(effective_span_knowledge(...))` substitution) and the
// left-staged grouping's ids read back `[0, 1, 5]` and its stored span
// `AtLeast(6)`, failing the equalities below.
let opts = DecodingOptions::new(); // drop ON (the default)
let a = || {
let mut seg = TranscriptionSegment::new();
seg.set_id(0).set_text(" A").set_tokens(vec![20]);
// Public `new`: one survivor, span WHOLLY UNKNOWN (`AtLeast(0)`).
TranscriptionResult::new(" A", vec![seg], "en", TranscriptionTimings::new())
};
let b = || {
let mut seg = TranscriptionSegment::new();
seg.set_id(0).set_text(" B").set_tokens(vec![21]);
// Five ordinals allocated, four filtered away — a carried span that legitimately
// EXCEEDS its survivor extent of 1.
TranscriptionResult::new(" B", vec![seg], "en", TranscriptionTimings::new())
.with_task_facts(TaskFacts::unknown().with_decoded_span(SpanKnowledge::Exact(5)))
};
let t = || span_one_speech(22); // trailing survivor at local id 0, Exact(1)
let one_shot = merge_transcription_results_with_options(&[a(), b(), t()], &opts);
let left_staged = merge_transcription_results_with_options(
&[
merge_transcription_results_with_options(&[a(), b()], &opts),
t(),
],
&opts,
);
let right_staged = merge_transcription_results_with_options(
&[
a(),
merge_transcription_results_with_options(&[b(), t()], &opts),
],
&opts,
);
for (label, merged) in [
("one-shot", &one_shot),
("left-staged", &left_staged),
("right-staged", &right_staged),
] {
assert_eq!(
segment_ids(merged),
vec![0, 1, 6],
"{label}: the trailing chunk sits past A's survivor floor and B's five ordinals",
);
assert_eq!(
merged.task_facts().decoded_span(),
SpanKnowledge::AtLeast(7),
"{label}: the stored fact carries the survivor floor the ids materialized \
(`AtLeast(1) + Exact(5) + Exact(1)`), grouping-independent",
);
}
}
#[test]
fn local_agreement_over_a_premerged_vad_result_preserves_the_id_span() {
// The LocalAgreement finalize re-merges kept results through
// `merge_transcription_results_with_words`; when one is itself a VAD-merged
// result, its STORED aggregate span must drive the re-merge's id base (R6-F3),
// or the confirmed-word transcript's segments renumber onto the earlier
// chunk's ordinals. Same [speech, all-dropped] VAD result, re-merged with a
// trailing speech chunk through the word-aware door.
let opts = DecodingOptions::new();
let vad = merge_transcription_results_with_options(
&[
span_one_speech(20),
TranscriptionResult::new("", Vec::new(), "en", TranscriptionTimings::new())
.with_task_facts(TaskFacts::unknown().with_decoded_span(SpanKnowledge::Exact(1))),
],
&opts,
);
let confirmed = [WordTiming::new(" W W", Vec::<u32>::new(), 0.0, 1.0, 1.0)];
let finalized =
merge_transcription_results_with_words(&[vad, span_one_speech(21)], &confirmed, &opts);
assert_eq!(
segment_ids(&finalized),
vec![0, 2],
"the trailing chunk sits past the pre-merged VAD result's stored span, not on id 1"
);
}
#[test]
fn merge_concatenates_worker_schedules_not_just_the_first() {
// R6-F2 (codex round 6), at the merge boundary. A merge of worker coordinates
// [0] and [2] must be distinguishable from [0] and [1] -- the pre-fix merge
// kept only the FIRST child's coordinate, collapsing both to [0], so two
// seeded VAD runs at different chunk structures left indistinguishable records.
//
// Mutation proof: revert the merge to `results.first()`'s coordinate and both
// schedules collapse to [0], failing the inequality below.
let at = |worker: usize| {
TranscriptionResult::new("x", Vec::new(), "en", TranscriptionTimings::new())
.with_task_facts(TaskFacts::unknown().with_worker(worker))
};
let merged_02 = merge_transcription_results(&[at(0), at(2)]);
let merged_01 = merge_transcription_results(&[at(0), at(1)]);
assert_eq!(
merged_02.task_facts().worker_schedule(),
Some([0, 2].as_slice())
);
assert_eq!(
merged_01.task_facts().worker_schedule(),
Some([0, 1].as_slice())
);
assert_ne!(
merged_02.task_facts().worker_schedule(),
merged_01.task_facts().worker_schedule(),
"the collapsed pre-fix merge made these two indistinguishable"
);
}
#[test]
fn plain_merge_completes_on_a_usize_max_segment_id_without_panicking() {
// F4 (codex round 8), preserved under round 12. The drop-OFF (plain) merge
// outputs ids as Swift's `result_index + segment_index` and NEVER consults the
// decoded span for the id mapping, so a hand-built `usize::MAX` segment id whose
// `max + 1` extent overflows cannot panic here: the `SpanKnowledge` fold sums
// the RAW carried spans (this public-`new` child's wholly-unknown `AtLeast(0)`)
// and never touches the overflowing survivor extent. The merge completes and the
// output id is the exact Swift ordinal 0.
let mut seg = TranscriptionSegment::new();
seg.set_id(usize::MAX).set_text(" X").set_tokens(vec![20]);
let adversarial = TranscriptionResult::new(" X", vec![seg], "en", TranscriptionTimings::new());
// The plain door (drop OFF): completes, and the single segment reindexes to
// Swift's `result_index(0) + segment_index(0) == 0`.
let merged = merge_transcription_results(std::slice::from_ref(&adversarial));
assert_eq!(
segment_ids(&merged),
vec![0],
"Swift-exact drop-OFF id is 0"
);
assert_eq!(
merged.task_facts().decoded_span(),
SpanKnowledge::wholly_unknown(),
"the public child's wholly-unknown span folds through untouched, not panicked on",
);
// The same through the confirmed-words door with `drop_blank_audio = false` --
// the default streaming finalize path, which also reaches the drop-OFF merge.
let confirmed = [WordTiming::new(" X", Vec::<u32>::new(), 0.0, 1.0, 1.0)];
let via_words = merge_transcription_results_with_words(
&[adversarial],
&confirmed,
&DecodingOptions::new().maybe_drop_blank_audio(false),
);
assert_eq!(
segment_ids(&via_words),
vec![0],
"the confirmed-words drop-OFF door completes identically",
);
}
#[test]
#[should_panic(expected = "overflowed usize")]
fn drop_on_merge_still_panics_on_a_usize_max_segment_id() {
// The drop-ON id mapping DOES drive an injective renumber off the span, so a
// hand-built `usize::MAX` id remains the documented DELIBERATE panic (it beats
// a silent wraparound into a colliding id). F4 loosened ONLY the drop-OFF fold,
// never this: the id-base advance turns the checked `None` span back into the
// same overflow panic the pre-fix `effective_span_knowledge` raised.
let mut seg = TranscriptionSegment::new();
seg.set_id(usize::MAX).set_text(" X").set_tokens(vec![20]);
let adversarial = TranscriptionResult::new(" X", vec![seg], "en", TranscriptionTimings::new());
let _ = merge_transcription_results_with_options(&[adversarial], &DecodingOptions::new());
}
#[test]
fn a_merge_created_span_never_undercounts_its_own_survivors() {
// F2 (codex round 9), corrected under round 12. A plain (drop-OFF) merge
// renumbers segments by `result_index + segment_index`, and here both children
// are public-`new` results carrying the wholly-unknown span (`AtLeast(0)`), so
// `[A(usize::MAX id), B(id 0)]` stores `AtLeast(0)` — neither child carries a
// known ordinal to lower-bound the aggregate with.
//
// The "never under-count its survivors" GUARANTEE is unchanged: it lives in the
// read-time `effective_span_knowledge`, which floors the stored span's lower bound
// at the survivors' own extent (max id 1 + 1 = 2). So a staged drop-ON re-merge
// still advances its id base by 2 and renumbers `C` past the survivors — `[0, 1,
// 2]`, never `[0, 1, 1]`.
//
// Mutation proof: revert `effective_span_knowledge`'s `.max(extent)` (or its
// `checked_add(1)`) and the staged ids collapse to `[0, 1, 1]`.
let mut a_seg = TranscriptionSegment::new();
a_seg.set_id(usize::MAX).set_text(" A").set_tokens(vec![20]);
let a = TranscriptionResult::new(" A", vec![a_seg], "en", TranscriptionTimings::new());
let mut b_seg = TranscriptionSegment::new();
b_seg.set_id(0).set_text(" B").set_tokens(vec![21]);
let b = TranscriptionResult::new(" B", vec![b_seg], "en", TranscriptionTimings::new());
// Plain (drop-OFF) merge: Swift-exact `result_index + segment_index` -> [0, 1].
let ab = merge_transcription_results(&[a, b]);
assert_eq!(segment_ids(&ab), vec![0, 1], "drop-OFF reindex");
assert_eq!(
ab.task_facts().decoded_span(),
SpanKnowledge::wholly_unknown(),
"two wholly-unknown children carry no known ordinal, so the aggregate stays \
wholly unknown (round 12)",
);
// A staged drop-ON re-merge with a trailing chunk stays injective: the stored
// span's lower bound floors at the survivors' extent (2), so C lands at id 2, not id 1.
let mut c_seg = TranscriptionSegment::new();
c_seg.set_id(0).set_text(" C").set_tokens(vec![22]);
let c = TranscriptionResult::new(" C", vec![c_seg], "en", TranscriptionTimings::new());
let staged = merge_transcription_results_with_options(&[ab, c], &DecodingOptions::new());
assert_eq!(
segment_ids(&staged),
vec![0, 1, 2],
"the trailing chunk sits past the merged survivors, not on id 1",
);
}
#[test]
fn drop_on_merge_trailing_id_is_grouping_independent_across_an_overflow() {
// F3 (round 10), corrected under round 12. Three all-dropped chunks (no
// survivors, carried spans only) with spans MAX, 1, 2 -- the triple whose merge
// grouping the pre-fix identity-`None` made non-associative. Under the round-12
// `SpanKnowledge` sum the STORED span of the grouped intermediate is
// grouping-independent by construction:
// (A·B)·C -- `Exact(MAX)·Exact(1)` overflows to `AtLeast(MAX)`, then
// `·Exact(2)` saturates -> `AtLeast(MAX)`;
// A·(B·C) -- `Exact(1)·Exact(2) = Exact(3)`, then `Exact(MAX)·Exact(3)`
// overflows -> `AtLeast(MAX)`.
// Both groupings store `AtLeast(usize::MAX)` (the saturated lower bound of the
// true total `MAX + 3`) -- the associativity the pre-round-12 absorbing/identity
// `None` could not give. A trailing drop-ON merge over such a saturated span
// advances the id base by `usize::MAX` and hits the documented drop-ON overflow
// panic (see `drop_on_merge_still_panics_on_a_usize_max_segment_id`), so the
// grouping-independence is asserted directly on the STORED span here; the
// reachable-span trailing-id path is proved in the materialized-overflow variant
// below.
//
// Mutation proof: revert `SpanKnowledge::merge`'s `Exact + Exact` overflow arm to
// the identity/absorbing `None` and the two groupings diverge, failing the
// equality.
let all_dropped = |span: usize| {
TranscriptionResult::new("", Vec::new(), "en", TranscriptionTimings::new())
.with_task_facts(TaskFacts::unknown().with_decoded_span(SpanKnowledge::Exact(span)))
};
let a = || all_dropped(usize::MAX);
let b = || all_dropped(1);
let c = || all_dropped(2);
// (A·B)·C: the one-shot left fold over all three.
let left_grouped = merge_transcription_results(&[a(), b(), c()]);
// A·(B·C): pre-merge B and C, then fold A over that intermediate.
let bc = merge_transcription_results(&[b(), c()]);
let right_grouped = merge_transcription_results(&[a(), bc]);
assert_eq!(
left_grouped.task_facts().decoded_span(),
right_grouped.task_facts().decoded_span(),
"a documented-associative merge law must store the same span for both groupings",
);
assert_eq!(
left_grouped.task_facts().decoded_span(),
SpanKnowledge::AtLeast(usize::MAX),
"the overflowed total is the saturated lower bound, grouping-independent",
);
// Round 11 (L), corrected under round 12: the materialized-overflow variant with
// a real SURVIVOR. The overflowing child A carries a survivor at id `usize::MAX`
// (wholly-unknown span `AtLeast(0)`), and a drop-OFF prefix merge reindexes it to
// id 0. The pre-round-11 fold substituted an inferred extent into the stored fact
// and diverged the groupings; the round-12 fold sums the RAW `SpanKnowledge`, so
// `A(AtLeast(0)) · B(Exact(2)) = AtLeast(2)` in EVERY grouping -- B's KNOWN 2
// ordinals survive as the aggregate's lower bound (the round-12 fix: the
// pre-round-12 `None` erased them, landing the trailing chunk on id 1). The
// stored span AND the trailing drop-ON ids are then grouping-independent.
//
// Mutation proof: revert `SpanKnowledge::merge`'s `AtLeast` arm to the absorbing
// `_ => None` and the stored span reads back the wholly-unknown `AtLeast(0)`,
// dropping the trailing id from 2 back to 1 -- both the value assertions fail.
let a_overflow = || {
let mut seg = TranscriptionSegment::new();
seg.set_id(usize::MAX).set_text(" A").set_tokens(vec![20]);
// A public `new` result: one survivor, span WHOLLY UNKNOWN (`AtLeast(0)`).
TranscriptionResult::new(" A", vec![seg], "en", TranscriptionTimings::new())
};
let b_dropped = || all_dropped(2); // no survivors, carried span Exact(2)
let t = || span_one_speech(31); // one trailing survivor at local id 0
// One-shot `merge([A, B])` and staged `merge([merge([A]), B])` — both drop-OFF,
// since a drop-ON merge over A's `usize::MAX` survivor is the documented panic.
let one_shot_ab = merge_transcription_results(&[a_overflow(), b_dropped()]);
let staged_ab =
merge_transcription_results(&[merge_transcription_results(&[a_overflow()]), b_dropped()]);
assert_eq!(
one_shot_ab.task_facts().decoded_span(),
staged_ab.task_facts().decoded_span(),
"the overflowing prefix must not diverge the stored span across groupings",
);
assert_eq!(
one_shot_ab.task_facts().decoded_span(),
SpanKnowledge::AtLeast(2),
"B's KNOWN 2 ordinals survive as the aggregate's lower bound (round 12), never erased",
);
// A trailing drop-ON merge must number both groupings identically.
let opts = DecodingOptions::new(); // drop ON
let one_shot_trailing = segment_ids(&merge_transcription_results_with_options(
&[one_shot_ab, t()],
&opts,
));
let staged_trailing = segment_ids(&merge_transcription_results_with_options(
&[staged_ab, t()],
&opts,
));
assert_eq!(
one_shot_trailing, staged_trailing,
"the trailing id is grouping-independent across the materialized overflow",
);
assert_eq!(
one_shot_trailing,
vec![0, 2],
"B's preserved lower bound of 2 lands the trailing segment past it -> id 2 (round 12; \
the pre-round-12 `None` erased B's ordinal and landed it on id 1)",
);
}
#[test]
fn a_public_results_too_small_span_is_distrusted_at_merge_input() {
// F2 sibling (codex round 9), preserved under round 12. A PUBLIC result whose
// carried span is below its survivor extent — a hand-built or deserialized
// inconsistency — must not be trusted at merge INPUT: two survivors `[0, 1]`
// (extent 2) carrying `Exact(1)` would, if believed, advance the drop-ON id base
// by only 1 and renumber a trailing chunk onto id 1. `effective_span_knowledge`
// floors the carried span's lower bound at the survivor extent, keeping the
// merge injective.
//
// Mutation proof: revert `effective_span_knowledge` to trust the carried lower
// bound verbatim (drop the `.max(extent)`) and the staged ids collapse to
// `[0, 1, 1]`.
let mut s0 = TranscriptionSegment::new();
s0.set_id(0).set_text(" R0").set_tokens(vec![20]);
let mut s1 = TranscriptionSegment::new();
s1.set_id(1).set_text(" R1").set_tokens(vec![21]);
let r = TranscriptionResult::new(" R0 R1", vec![s0, s1], "en", TranscriptionTimings::new())
.with_task_facts(TaskFacts::unknown().with_decoded_span(SpanKnowledge::Exact(1)));
let mut c_seg = TranscriptionSegment::new();
c_seg.set_id(0).set_text(" C").set_tokens(vec![22]);
let c = TranscriptionResult::new(" C", vec![c_seg], "en", TranscriptionTimings::new());
let staged = merge_transcription_results_with_options(&[r, c], &DecodingOptions::new());
assert_eq!(
segment_ids(&staged),
vec![0, 1, 2],
"a too-small carried span is clamped up to the survivor extent at merge input",
);
}
#[test]
fn merging_an_unknown_facts_contributor_poisons_a_known_clean_result() {
// F2 (codex round 8), at the merge boundary. `None` is the epistemic unknown,
// NOT the OR identity: merging a contributor with genuinely-unknown
// draw/early-stop facts into a known-clean result must not read back
// observed-clean-and-reproducible. The pre-fix free monoid (`None` as
// identity) let `or_unknown(Some(false), None) = Some(false)`, so an unknown
// contributor vanished and the merge promised a byte-reproducibility neither
// result earned. Two mutations are caught here:
// - seed the fold at `TaskFacts::unknown()` instead of the Accumulator, and
// the LONE known-clean result nulls to `None` (the `solo` block fails);
// - revert `kleene_or` to the free monoid, and the UNKNOWN contributor stops
// poisoning, reading back `Some(false)`/reproducible (the `poisoned` block
// fails).
let compute = crate::audio::whisper::options::ComputeOptions::new();
let clean = TranscriptionResult::new(
"Hi",
vec![TranscriptionSegment::new()],
"en",
TranscriptionTimings::new(),
)
.with_task_facts(TaskFacts::observed_clean());
let unknown_contrib = TranscriptionResult::new("", Vec::new(), "en", TranscriptionTimings::new())
.with_task_facts(TaskFacts::unknown());
// A lone known-clean result stays observed-clean: the Accumulator takes it
// verbatim, NOT nulled by an `unknown()` fold seed.
let solo =
merge_transcription_results_with_options(std::slice::from_ref(&clean), &DecodingOptions::new());
assert_eq!(solo.task_facts().drew_from_rng(), Some(false));
assert_eq!(solo.task_facts().early_stopped(), Some(false));
assert!(
crate::audio::whisper::provenance::Provenance::for_result(
&DecodingOptions::new(),
&compute,
&solo
)
.is_reproducible(),
"a lone observed-clean result is reproducible",
);
// Merge an UNKNOWN-facts contributor in: its `None` poisons the draw and
// early-stop to unknown, and the transcript is no longer promised reproducible.
let poisoned =
merge_transcription_results_with_options(&[clean, unknown_contrib], &DecodingOptions::new());
assert_eq!(
poisoned.task_facts().drew_from_rng(),
None,
"an unknown contributor's None poisons the known-clean draw (was wrongly Some(false))",
);
assert_eq!(poisoned.task_facts().early_stopped(), None);
assert!(
!crate::audio::whisper::provenance::Provenance::for_result(
&DecodingOptions::new(),
&compute,
&poisoned
)
.is_reproducible(),
"the merge must not promise reproducibility once an unknown contributor joined",
);
}
/// A result carrying nothing but text — the shape `transcribe_all` returns
/// for a chunk/clip whose segments were all emptied (or, independently of
/// the blank-audio drop, for any clip shorter than `window_clip_time`).
fn spoken(text: &str) -> TranscriptionResult {
TranscriptionResult::new(text, Vec::new(), "en", TranscriptionTimings::new())
}
#[test]
fn merge_joins_an_empty_text_as_a_bare_separator() {
// PARITY PIN (issue #14). The options-BLIND merge deliberately does NOT
// skip empty-text results: Swift's `validResults` `compactMap`s away
// only *nil* elements, never empty-text ones, so
// `["a", "", "b"].joined(separator: " ")` is `"a b"` there and must be
// `"a b"` here.
//
// It is tempting to "fix" this here, because
// `DecodingOptions::drop_blank_audio` (default `true`) makes an emptied
// chunk common. DON'T — an empty-text result is reachable with NO
// involvement from that option (any audio shorter than
// `window_clip_time` runs no window and returns one; see
// `transcribe::tests::audio_shorter_than_window_clip_time_yields_no_windows`,
// which predates the option), so filtering unconditionally here would
// silently change the `drop_blank_audio == false` path — the path whose
// whole purpose is to be byte-for-byte Swift. The skip belongs to the
// option, and therefore to `merge_transcription_results_with_options`
// (below); this test is what keeps it from creeping down here.
assert_eq!(
merge_transcription_results(&[spoken("a"), spoken(""), spoken("b")]).text(),
"a b",
"interior empty stays a bare separator (Swift parity)"
);
assert_eq!(
merge_transcription_results(&[spoken("a"), spoken("")]).text(),
"a ",
"trailing empty stays a bare separator (Swift parity)"
);
}
#[test]
fn merge_with_options_skips_empty_texts_when_blank_audio_is_dropped() {
// THE REGRESSION, at the public door a consumer actually uses: fold a
// `transcribe_all` batch through the merge under the DEFAULT options
// (`drop_blank_audio == true`). An emptied result must contribute no
// separator at all — the merge's own `["a", "", "b"].join(" ")` would
// make it `"a b"`.
let options = DecodingOptions::new();
assert!(options.drop_blank_audio(), "this is the default path");
let text = |results: &[TranscriptionResult]| {
merge_transcription_results_with_options(results, &options)
.text()
.to_string()
};
// Interior: an emptied chunk BETWEEN two speech runs -> no doubled space.
assert_eq!(
text(&[spoken("Hello world."), spoken(""), spoken("Goodbye.")]),
"Hello world. Goodbye."
);
// Trailing: emptied chunks after the speech -> no trailing space(s).
assert_eq!(
text(&[spoken("Hello world."), spoken(""), spoken("")]),
"Hello world."
);
// Leading: an emptied chunk before the speech -> no leading space.
assert_eq!(text(&[spoken(""), spoken("Hello world.")]), "Hello world.");
// Wholly emptied: nothing at all, not a string of bare separators.
assert_eq!(text(&[spoken(""), spoken(""), spoken("")]), "");
// Speech only: the join is untouched — one separator per gap.
assert_eq!(text(&[spoken("Hello"), spoken("world.")]), "Hello world.");
// Empty input: still the empty string (`[].join(" ")`).
assert_eq!(text(&[]), "");
}
#[test]
fn merge_with_options_joins_empty_texts_verbatim_when_the_drop_is_cleared() {
// The `false` TWIN of the test above, and the parity pin on this entry
// point: cleared, it must reproduce `merge_transcription_results` — bare
// separators and all — byte for byte. This is what makes the skip above
// provably attributable to the option rather than to the new function.
let options = DecodingOptions::new().maybe_drop_blank_audio(false);
let results = [spoken("Hello world."), spoken(""), spoken("Goodbye.")];
let merged = merge_transcription_results_with_options(&results, &options);
assert_eq!(
merged.text(),
"Hello world. Goodbye.",
"the bare separator must SURVIVE when the drop is cleared (Swift parity)"
);
assert_eq!(
merged.text(),
merge_transcription_results(&results).text(),
"cleared, this entry point IS the options-blind merge"
);
assert_eq!(
merge_transcription_results_with_options(&[spoken("a"), spoken("")], &options).text(),
"a ",
"trailing bare separator survives too"
);
}
#[test]
fn merge_with_options_keeps_every_result_in_the_timing_sums() {
// The skip is a JOIN rule, not a merge-input filter. Dropping an emptied
// result from the merge instead would take its `input_audio_seconds` /
// `audio_processing` / every other summed timing out with it — silently
// corrupting the merged metrics, and the RTF derived from them, to fix a
// spacing bug. Every field except `text` must therefore be INVARIANT
// under the option.
let timed = |text: &str, audio_seconds: f64| {
let mut timings = TranscriptionTimings::new();
timings
.set_input_audio_seconds(audio_seconds)
.set_audio_processing(audio_seconds / 10.0)
.set_total_audio_processing_runs(1.0)
.set_full_pipeline(audio_seconds / 4.0);
TranscriptionResult::new(text, Vec::new(), "en", timings)
};
// The middle chunk is 30 s of silence the blank-audio drop emptied: no
// text, but 30 s of audio that really was processed.
let results = [
timed("Hello world.", 30.0),
timed("", 30.0),
timed("Goodbye.", 20.0),
];
let dropped = merge_transcription_results_with_options(
&results,
&DecodingOptions::new().with_drop_blank_audio(),
);
let kept = merge_transcription_results_with_options(
&results,
&DecodingOptions::new().maybe_drop_blank_audio(false),
);
let blind = merge_transcription_results(&results);
// Only the text moves.
assert_eq!(dropped.text(), "Hello world. Goodbye.");
assert_eq!(kept.text(), "Hello world. Goodbye.");
// Everything else is byte-identical across all three doors — including
// the EMPTIED chunk's 30 s, which must still be in the sums.
for other in [&kept, &blind] {
assert_eq!(
dropped.timings().input_audio_seconds(),
other.timings().input_audio_seconds()
);
assert_eq!(
dropped.timings().audio_processing(),
other.timings().audio_processing()
);
assert_eq!(
dropped.timings().total_audio_processing_runs(),
other.timings().total_audio_processing_runs()
);
assert_eq!(
dropped.timings().full_pipeline(),
other.timings().full_pipeline()
);
assert_eq!(
dropped.timings().real_time_factor(),
other.timings().real_time_factor()
);
assert_eq!(dropped.segments_slice().len(), other.segments_slice().len());
assert_eq!(dropped.language(), other.language());
}
// ...and the sums are the REAL ones, not the ones a skipped result leaves
// behind: 30 + 30 + 20, not 30 + 20.
assert_eq!(dropped.timings().input_audio_seconds(), 80.0);
assert_eq!(dropped.timings().total_audio_processing_runs(), 3.0);
assert_eq!(dropped.timings().full_pipeline(), 20.0);
assert_eq!(dropped.timings().real_time_factor(), 20.0 / 80.0);
}
#[test]
fn merge_full_pipeline_sums_when_pipeline_start_is_never_stamped() {
// Regression (task-12 review): with every pipeline_start at the
// "never stamped" sentinel (f64::MAX) — which is what every result this
// sync port produces looks like — the merged full_pipeline must be the
// sum of the per-result full_pipelines. The naive Swift formula
// degenerates here: f64::MAX + full_pipeline ABSORBS (the ULP at that
// magnitude is ~2e292, so the sum rounds back to exactly f64::MAX, it
// does NOT overflow to infinity), making user_pipeline_duration
// f64::MAX - f64::MAX == 0.0 and min() zero out the real sum.
let mut timings_a = TranscriptionTimings::new();
timings_a
.set_full_pipeline(2.0)
.set_total_decoding_loops(10.0);
let a = TranscriptionResult::new("a", Vec::new(), "en", timings_a);
let mut timings_b = TranscriptionTimings::new();
timings_b
.set_full_pipeline(3.0)
.set_total_decoding_loops(20.0);
let b = TranscriptionResult::new("b", Vec::new(), "en", timings_b);
let merged = merge_transcription_results(&[a, b]);
assert_eq!(merged.timings().full_pipeline(), 5.0);
// The derived projections must therefore be live, not zeroed.
assert_eq!(merged.timings().tokens_per_second(), 30.0 / 5.0);
// The sentinel itself survives the merge (min of sentinels), matching
// Swift's own formula on the same input.
assert_eq!(merged.timings().pipeline_start(), f64::MAX);
assert_eq!(merged.timings().first_token_time(), f64::MAX);
}
#[test]
fn merge_full_pipeline_takes_wall_clock_span_when_starts_are_real() {
// The general Swift formula (TranscriptionUtilities.swift:110-114) on
// results that DO carry real pipeline_start stamps: two overlapping
// concurrent pipelines, user span = (101 + 3) - 100 = 4, system sum =
// 2 + 3 = 5, merged full_pipeline = min(4, 5) = 4.
let mut timings_a = TranscriptionTimings::new();
timings_a.set_pipeline_start(100.0).set_full_pipeline(2.0);
let a = TranscriptionResult::new("a", Vec::new(), "en", timings_a);
let mut timings_b = TranscriptionTimings::new();
timings_b.set_pipeline_start(101.0).set_full_pipeline(3.0);
let b = TranscriptionResult::new("b", Vec::new(), "en", timings_b);
let merged = merge_transcription_results(&[a, b]);
assert_eq!(merged.timings().full_pipeline(), 4.0);
assert_eq!(merged.timings().pipeline_start(), 100.0);
}
// ---------------------------------------------------------------------
// FallbackReason / needs_fallback
// ---------------------------------------------------------------------
/// Builds a `DecodingResult` with the four fields `needs_fallback` reads.
/// `first_token_lp` becomes the sole `token_log_probs` entry: Swift has no
/// separate stored "first token logprob" field either — `TextDecoder.
/// swift:788-791` builds `tokenLogProbs` as one `[token: logprob]` dict per
/// decode step, so its first entry already *is* the first sampled token's
/// logprob, and `needs_fallback` reads it the same way.
fn result_with(
avg_logprob: f32,
no_speech: f32,
compression: f32,
first_token_lp: f32,
) -> DecodingResult {
DecodingResult::new()
.with_avg_logprob(avg_logprob)
.with_no_speech_prob(no_speech)
.with_compression_ratio(compression)
.with_token_log_probs(vec![(0u32, first_token_lp)])
}
#[test]
fn fallback_decision_order_matches_swift() {
// Models.swift:357-381 `DecodingFallback.init?` — order matters (the
// source's own comment, line 365); every comparison is strict (`<`/`>`,
// never `<=`/`>=`).
let opts = DecodingOptions::new();
// 1. first-token logprob below threshold wins outright, before any other
// check runs (TextDecoder.swift:662-667; Models.swift:366-367).
// first_token_lp=-2.0 < threshold=-1.5, so flag=true.
let r = result_with(-0.5, 0.1, 1.0, -2.0);
assert_eq!(
needs_fallback(true, &r, &opts),
Some(FallbackReason::FirstTokenLogProbThreshold)
);
// 2. silence: `no_speech_prob > threshold` alone -> None. NOTE: this
// task's brief encoded an exploration reading that silence *also*
// required `avg_logprob < threshold`; Models.swift:368-370 has no
// such condition (`else if let threshold = options.noSpeechThreshold,
// noSpeechProb > threshold`) — avg_logprob is never consulted by this
// branch. This particular case's *outcome* happens to match either
// reading; see `fallback_silence_short_circuits_regardless_of_avg_logprob`
// below for a case that actually discriminates between them.
// first_token_lp=0.0 >= threshold=-1.5, so flag=false.
let r = result_with(-1.5, 0.9, 1.0, 0.0);
assert_eq!(needs_fallback(false, &r, &opts), None);
// 3. compression ratio over threshold -> repetition fallback.
// first_token_lp=0.0 >= threshold=-1.5, so flag=false.
let r = result_with(-0.5, 0.1, 3.0, 0.0);
assert_eq!(
needs_fallback(false, &r, &opts),
Some(FallbackReason::CompressionRatioThreshold)
);
// 4. avg logprob under threshold -> quality fallback.
// first_token_lp=0.0 >= threshold=-1.5, so flag=false.
let r = result_with(-1.5, 0.1, 1.0, 0.0);
assert_eq!(
needs_fallback(false, &r, &opts),
Some(FallbackReason::LogProbThreshold)
);
// 5. clean result -> no fallback.
// first_token_lp=0.0 >= threshold=-1.5, so flag=false.
let r = result_with(-0.2, 0.1, 1.0, 0.0);
assert_eq!(needs_fallback(false, &r, &opts), None);
// disabled thresholds (None) disable their own checks; nothing else
// objects to a compression ratio of 3.0 here.
let opts = DecodingOptions::new().maybe_compression_ratio_threshold(None);
let r = result_with(-0.5, 0.1, 3.0, 0.0);
assert_eq!(needs_fallback(false, &r, &opts), None);
}
#[test]
fn fallback_silence_short_circuits_regardless_of_avg_logprob() {
// Discriminates the corrected reading from the brief's original one.
// avg_logprob = -0.2 would NOT itself trigger LogProbThreshold, and
// compression = 3.0 WOULD trigger CompressionRatioThreshold on its own —
// but no_speech_prob (0.9) exceeds its threshold (0.6, default), and per
// Models.swift:368-370 that alone short-circuits to "silence" (None)
// *before* the compression-ratio check ever runs. Under the brief's
// original (avg_logprob-gated) reading of "silence", this case would
// have fallen through to the compression check instead and returned
// `Some(CompressionRatioThreshold)`.
// first_token_lp=0.0 >= threshold=-1.5, so flag=false.
let opts = DecodingOptions::new();
let r = result_with(-0.2, 0.9, 3.0, 0.0);
assert_eq!(needs_fallback(false, &r, &opts), None);
}
#[test]
fn fallback_thresholds_use_strict_inequality() {
// Exactly-at-threshold never triggers (Models.swift uses `<`/`>`, never
// `<=`/`>=`, at every step).
let opts = DecodingOptions::new();
// first_token_logprob_threshold default is Some(-1.5); exactly -1.5 must
// not trigger. first_token_lp=-1.5 == threshold, so flag=false.
let r = result_with(-0.2, 0.1, 1.0, -1.5);
assert_eq!(needs_fallback(false, &r, &opts), None);
// no_speech_threshold default is Some(0.6); exactly 0.6 must not trigger
// silence. first_token_lp=0.0 >= threshold=-1.5, so flag=false.
let r = result_with(-0.2, 0.6, 1.0, 0.0);
assert_eq!(needs_fallback(false, &r, &opts), None);
// compression_ratio_threshold default is Some(2.4); exactly 2.4 must not
// trigger. first_token_lp=0.0 >= threshold=-1.5, so flag=false.
let r = result_with(-0.2, 0.1, 2.4, 0.0);
assert_eq!(needs_fallback(false, &r, &opts), None);
// logprob_threshold default is Some(-1.0); exactly -1.0 must not trigger.
// first_token_lp=0.0 >= threshold=-1.5, so flag=false.
let r = result_with(-1.0, 0.1, 1.0, 0.0);
assert_eq!(needs_fallback(false, &r, &opts), None);
}
#[test]
fn empty_word_tokens_do_not_trigger_compression_fallback() {
// PARITY (coremlit issue #9), decision level. An empty word-token window
// (decode/mod.rs feeds `compression_ratio_of_tokens(&word_tokens)`, and
// `word_tokens` can be empty) yields a compression ratio of 0.0 — Swift's
// value, since its tokens overload has no empty guard (see
// `text::tests::compression_ratio_of_tokens_empty_is_zero_matching_swift`).
// Threaded through `needs_fallback` at the DEFAULT threshold (Some(2.4)),
// `0.0 > 2.4` is false, so the compression check does not fire and no
// repetition fallback is requested — matching Swift. Before this fix the
// ratio was f32::INFINITY, `INFINITY > 2.4` was true, and this same empty
// window would have (wrongly) forced a fallback: the exact parity bug this
// guards against.
let empty_ratio = crate::audio::whisper::text::compression_ratio_of_tokens(&[]);
assert_eq!(empty_ratio, 0.0);
// Other signals kept clean so the compression branch is the one under
// test: no_speech below its 0.6 default, avg_logprob above its -1.0
// default, first-token flag false.
let opts = DecodingOptions::new();
let r = result_with(-0.2, 0.1, empty_ratio, 0.0);
assert_ne!(
needs_fallback(false, &r, &opts),
Some(FallbackReason::CompressionRatioThreshold)
);
assert_eq!(needs_fallback(false, &r, &opts), None);
}
#[test]
fn fallback_first_token_check_ignores_empty_token_log_probs() {
// A `DecodingResult` with no token_log_probs at all still requires the
// caller to compute first_token_log_prob_too_low from the loop-local
// first token; this test passes false (no first-token fallback) and
// verifies the function continues to check other thresholds.
let opts = DecodingOptions::new();
let r = DecodingResult::new().with_avg_logprob(-1.5); // logprob-threshold-worthy
assert!(r.token_log_probs_slice().is_empty());
assert_eq!(
needs_fallback(false, &r, &opts),
Some(FallbackReason::LogProbThreshold)
);
}
#[test]
fn fallback_all_thresholds_disabled_never_triggers() {
let opts = DecodingOptions::new()
.maybe_first_token_logprob_threshold(None)
.maybe_no_speech_threshold(None)
.maybe_compression_ratio_threshold(None)
.maybe_logprob_threshold(None);
// Values that would trip every single check if thresholds were active.
// Pass false for the first_token flag since thresholds are disabled anyway.
let r = result_with(-9.0, 1.0, 9.0, -9.0);
assert_eq!(needs_fallback(false, &r, &opts), None);
}
#[test]
fn fallback_reason_as_str_matches_swift_strings() {
// Models.swift:367,373,376 fallbackReason string literals.
assert_eq!(
FallbackReason::FirstTokenLogProbThreshold.as_str(),
"firstTokenLogProbThreshold"
);
assert_eq!(
FallbackReason::CompressionRatioThreshold.as_str(),
"compressionRatioThreshold"
);
assert_eq!(
FallbackReason::LogProbThreshold.as_str(),
"logProbThreshold"
);
assert_eq!(
FallbackReason::FirstTokenLogProbThreshold.to_string(),
"firstTokenLogProbThreshold"
);
assert!(FallbackReason::LogProbThreshold.is_log_prob_threshold());
assert!(!FallbackReason::LogProbThreshold.is_compression_ratio_threshold());
}
// ---------------------------------------------------------------------
// WordTiming
// ---------------------------------------------------------------------
#[test]
fn segment_duration_and_word_duration() {
// NOTE: the brief's literal snippet called `.into()` on "hi"; against
// `WordTiming::new`'s generic `impl Into<String>` parameter that is
// ambiguous (E0283 - `&str` implements `Into<T>` for several `T`), and
// `.into()` is redundant besides (`&str: Into<String>` already holds).
let w = WordTiming::new("hi", vec![1], 1.0, 1.5, 0.9);
assert_eq!(w.duration(), 0.5);
}
#[test]
fn word_timing_accessors_match_constructor() {
// Binary-exact fractions (quarters/eighths) so `duration()`'s
// subtraction can be compared with `==` without float rounding noise.
let w = WordTiming::new("hello", vec![15339u32], 0.25, 0.75, 0.875);
assert_eq!(w.word(), "hello");
assert_eq!(w.tokens_slice(), &[15339u32]);
assert_eq!(w.start(), 0.25);
assert_eq!(w.end(), 0.75);
assert_eq!(w.probability(), 0.875);
assert_eq!(w.duration(), 0.5);
}
// ---------------------------------------------------------------------
// TranscriptionSegment
// ---------------------------------------------------------------------
#[test]
fn transcription_segment_defaults_match_swift() {
// Models.swift:593-606 `TranscriptionSegment.init` defaults.
let s = TranscriptionSegment::new();
assert_eq!(s.id(), 0);
assert_eq!(s.seek(), 0);
assert_eq!(s.start(), 0.0);
assert_eq!(s.end(), 0.0);
assert!(s.text().is_empty());
assert!(s.tokens_slice().is_empty());
assert!(s.token_log_probs_slice().is_empty());
assert_eq!(s.temperature(), 1.0); // NOT 0.0 - Swift default, Models.swift:601
assert_eq!(s.avg_logprob(), 0.0);
assert_eq!(s.compression_ratio(), 1.0); // NOT 0.0 - Swift default, Models.swift:603
assert_eq!(s.no_speech_prob(), 0.0);
assert!(s.words_slice().is_empty());
assert_eq!(s.duration(), 0.0);
assert_eq!(TranscriptionSegment::default(), TranscriptionSegment::new());
}
#[test]
fn transcription_segment_builder_vocabulary() {
let s = TranscriptionSegment::new()
.with_id(3)
.with_seek(48_000)
.with_start(1.0)
.with_end(2.5)
.with_text("hello world")
.with_tokens(vec![50364u32, 15339])
.with_token_log_probs(vec![(50364u32, -0.1), (15339, -0.2)])
.with_temperature(0.2)
.with_avg_logprob(-0.3)
.with_compression_ratio(1.8)
.with_no_speech_prob(0.01)
.with_words(vec![WordTiming::new(
"hello",
vec![15339u32],
1.0,
1.5,
0.9,
)]);
assert_eq!(s.id(), 3);
assert_eq!(s.seek(), 48_000);
assert_eq!(s.duration(), 1.5); // end(2.5) - start(1.0)
assert_eq!(s.text(), "hello world");
assert_eq!(s.tokens_slice(), &[50364u32, 15339]);
assert_eq!(
s.token_log_probs_slice(),
&[(50364u32, -0.1), (15339, -0.2)]
);
assert_eq!(s.temperature(), 0.2);
assert_eq!(s.avg_logprob(), -0.3);
assert_eq!(s.compression_ratio(), 1.8);
assert_eq!(s.no_speech_prob(), 0.01);
assert_eq!(s.words_slice().len(), 1);
let mut m = TranscriptionSegment::new();
m.set_id(7).set_text("mutated");
assert_eq!(m.id(), 7);
assert_eq!(m.text(), "mutated");
}
// ---------------------------------------------------------------------
// TranscriptionTimings
// ---------------------------------------------------------------------
#[test]
fn timings_defaults_match_swift() {
// Models.swift:778-843 `TranscriptionTimings.init` defaults: every
// duration/count is zero except the two "not yet reached" sentinels and
// the audio-seconds floor.
let t = TranscriptionTimings::new();
assert_eq!(t.pipeline_start(), f64::MAX);
assert_eq!(t.first_token_time(), f64::MAX);
assert_eq!(t.input_audio_seconds(), 0.001);
assert_eq!(t.model_loading(), 0.0);
assert_eq!(t.prewarm_load_time(), 0.0);
assert_eq!(t.encoder_load_time(), 0.0);
assert_eq!(t.decoder_load_time(), 0.0);
assert_eq!(t.encoder_specialization_time(), 0.0);
assert_eq!(t.decoder_specialization_time(), 0.0);
assert_eq!(t.tokenizer_load_time(), 0.0);
assert_eq!(t.audio_loading(), 0.0);
assert_eq!(t.audio_processing(), 0.0);
assert_eq!(t.logmels(), 0.0);
assert_eq!(t.encoding(), 0.0);
assert_eq!(t.decoding_init(), 0.0);
assert_eq!(t.decoding_loop(), 0.0);
assert_eq!(t.decoding_predictions(), 0.0);
assert_eq!(t.decoding_filtering(), 0.0);
assert_eq!(t.decoding_sampling(), 0.0);
assert_eq!(t.decoding_fallback(), 0.0);
assert_eq!(t.decoding_windowing(), 0.0);
assert_eq!(t.decoding_kv_caching(), 0.0);
assert_eq!(t.decoding_word_timestamps(), 0.0);
assert_eq!(t.decoding_non_prediction(), 0.0);
assert_eq!(t.total_audio_processing_runs(), 0.0);
assert_eq!(t.total_logmel_runs(), 0.0);
assert_eq!(t.total_encoding_runs(), 0.0);
assert_eq!(t.total_decoding_loops(), 0.0);
assert_eq!(t.total_kv_update_runs(), 0.0);
assert_eq!(t.total_timestamp_alignment_runs(), 0.0);
assert_eq!(t.total_decoding_fallbacks(), 0.0);
assert_eq!(t.total_decoding_windows(), 0.0);
assert_eq!(t.full_pipeline(), 0.0);
assert_eq!(TranscriptionTimings::default(), TranscriptionTimings::new());
}
#[test]
fn timings_projections() {
let mut t = TranscriptionTimings::new();
t.set_full_pipeline(2.0)
.set_total_decoding_loops(100.0)
.set_input_audio_seconds(10.0);
assert_eq!(t.tokens_per_second(), 50.0);
assert_eq!(t.real_time_factor(), 0.2);
assert_eq!(t.speed_factor(), 5.0);
}
#[test]
fn timings_projections_guard_division_by_zero() {
let mut t = TranscriptionTimings::new();
t.set_full_pipeline(0.0);
assert_eq!(t.tokens_per_second(), 0.0); // would be NaN/inf unguarded
assert_eq!(t.speed_factor(), 0.0);
t.set_full_pipeline(5.0).set_input_audio_seconds(0.0);
assert_eq!(t.real_time_factor(), 0.0);
}
#[test]
fn timings_setters_mutate_in_place_and_chain() {
let mut t = TranscriptionTimings::new();
t.set_model_loading(1.2)
.set_encoder_load_time(0.4)
.set_decoder_load_time(0.6)
.set_total_decoding_windows(3.0);
assert_eq!(t.model_loading(), 1.2);
assert_eq!(t.encoder_load_time(), 0.4);
assert_eq!(t.decoder_load_time(), 0.6);
assert_eq!(t.total_decoding_windows(), 3.0);
}
// ---------------------------------------------------------------------
// TranscriptionResult
// ---------------------------------------------------------------------
#[test]
fn transcription_result_requires_core_fields_and_defaults_seek_time() {
let timings = TranscriptionTimings::new();
let r = TranscriptionResult::new("hello world", Vec::new(), "en", timings.clone());
assert_eq!(r.text(), "hello world");
assert!(r.segments_slice().is_empty());
assert_eq!(r.language(), "en");
assert_eq!(r.timings(), &timings);
assert_eq!(r.seek_time(), None);
}
#[test]
fn transcription_result_seek_time_option_vocabulary() {
let r =
TranscriptionResult::new("", Vec::new(), "", TranscriptionTimings::new()).with_seek_time(12.5);
assert_eq!(r.seek_time(), Some(12.5));
let mut r = r;
r.clear_seek_time();
assert_eq!(r.seek_time(), None);
r.update_seek_time(Some(3.0));
assert_eq!(r.seek_time(), Some(3.0));
let r = r.maybe_seek_time(None);
assert_eq!(r.seek_time(), None);
}
// ---------------------------------------------------------------------
// DecodingResult
// ---------------------------------------------------------------------
#[test]
fn decoding_result_defaults_match_swift_empty_results() {
// Models.swift:397-410 `DecodingResult.emptyResults`.
let r = DecodingResult::new();
assert!(r.language().is_empty());
assert!(r.language_probs_slice().is_empty());
assert!(r.tokens_slice().is_empty());
assert!(r.token_log_probs_slice().is_empty());
assert!(r.text().is_empty());
assert_eq!(r.avg_logprob(), 0.0);
assert_eq!(r.no_speech_prob(), 0.0);
assert_eq!(r.temperature(), 0.0); // unlike TranscriptionSegment's 1.0 default
assert_eq!(r.compression_ratio(), 0.0); // unlike TranscriptionSegment's 1.0 default
// Rust-only addition beyond Swift's field set (T5/decode loop assumption
// (b), see `needs_fallback`'s doc): the raw first-sampled-token logprob,
// threaded out of the loop so a fallback-ladder caller can recompute
// `first_token_log_prob_too_low` without decode_text changing its return
// type.
assert_eq!(r.first_token_log_prob(), 0.0);
// F3 (codex round 3): a fresh result observed no `<|lang|>` token.
assert_eq!(r.observed_language(), None);
assert_eq!(DecodingResult::default(), DecodingResult::new());
}
#[test]
fn decoding_result_builder_vocabulary() {
let r = DecodingResult::new()
.with_language("en")
.with_language_probs(vec![("en".to_string(), 0.98)])
.maybe_observed_language(Some("en".to_string()))
.with_tokens(vec![50364u32, 15339])
.with_token_log_probs(vec![(50364u32, -0.05)])
.with_text("hello")
.with_avg_logprob(-0.4)
.with_no_speech_prob(0.02)
.with_temperature(0.2)
.with_compression_ratio(1.6)
.with_first_token_log_prob(-0.8);
assert_eq!(r.language(), "en");
assert_eq!(r.observed_language(), Some("en"));
assert_eq!(r.language_probs_slice(), &[("en".to_string(), 0.98)]);
assert_eq!(r.tokens_slice(), &[50364u32, 15339]);
assert_eq!(r.token_log_probs_slice(), &[(50364u32, -0.05)]);
assert_eq!(r.text(), "hello");
assert_eq!(r.avg_logprob(), -0.4);
assert_eq!(r.no_speech_prob(), 0.02);
assert_eq!(r.temperature(), 0.2);
assert_eq!(r.compression_ratio(), 1.6);
assert_eq!(r.first_token_log_prob(), -0.8);
let mut m = DecodingResult::new();
m.set_text("mutated").set_avg_logprob(-1.0);
assert_eq!(m.text(), "mutated");
assert_eq!(m.avg_logprob(), -1.0);
}
// ---------------------------------------------------------------------
// TranscriptionProgress
// ---------------------------------------------------------------------
#[test]
fn transcription_progress_defaults_match_swift() {
// Models.swift:643-660 `TranscriptionProgress.init` defaults: the
// optional trio starts `nil`, `windowId` starts `0`.
let timings = TranscriptionTimings::new();
let p = TranscriptionProgress::new(timings.clone(), "hello", vec![50364u32, 15339]);
assert_eq!(p.timings(), &timings);
assert_eq!(p.text(), "hello");
assert_eq!(p.tokens_slice(), &[50364u32, 15339]);
assert_eq!(p.temperature(), None);
assert_eq!(p.avg_logprob(), None);
assert_eq!(p.compression_ratio(), None);
assert_eq!(p.window_id(), 0);
}
#[test]
fn transcription_progress_builder_vocabulary() {
let p = TranscriptionProgress::new(TranscriptionTimings::new(), "hi", Vec::new())
.with_temperature(0.2)
.with_avg_logprob(-0.3)
.with_compression_ratio(1.4)
.with_window_id(2);
assert_eq!(p.temperature(), Some(0.2));
assert_eq!(p.avg_logprob(), Some(-0.3));
assert_eq!(p.compression_ratio(), Some(1.4));
assert_eq!(p.window_id(), 2);
let mut m = p.clone();
m.clear_temperature();
assert_eq!(m.temperature(), None);
m.update_avg_logprob(Some(-0.9));
assert_eq!(m.avg_logprob(), Some(-0.9));
m.set_text("mutated").set_tokens(vec![1u32]);
assert_eq!(m.text(), "mutated");
assert_eq!(m.tokens_slice(), &[1u32]);
}
// ---------------------------------------------------------------------
// serde
// ---------------------------------------------------------------------
#[cfg(feature = "serde")]
#[test]
fn word_timing_serde_round_trips_and_requires_every_field() {
let w = WordTiming::new("hi", vec![1u32], 1.0, 1.5, 0.9);
let json = serde_json::to_string(&w).unwrap();
assert_eq!(serde_json::from_str::<WordTiming>(&json).unwrap(), w);
// No defaults: a payload missing a field is an error (matches Swift
// Codable's synthesis, which has no init-default fallback either).
assert!(serde_json::from_str::<WordTiming>(r#"{"word":"hi"}"#).is_err());
}
#[cfg(feature = "serde")]
#[test]
fn transcription_segment_serde_skips_empty_words_and_fills_defaults() {
let s = TranscriptionSegment::new().with_text("hi");
let json = serde_json::to_string(&s).unwrap();
let value: serde_json::Value = serde_json::from_str(&json).unwrap();
assert!(!value.as_object().unwrap().contains_key("words"));
assert!(!value.as_object().unwrap().contains_key("tokens"));
assert_eq!(
serde_json::from_str::<TranscriptionSegment>(&json).unwrap(),
s
);
// Partial config still resolves temperature/compression_ratio to
// Swift's non-zero defaults, not f32::default().
let partial: TranscriptionSegment = serde_json::from_str("{}").unwrap();
assert_eq!(partial, TranscriptionSegment::new());
assert_eq!(partial.temperature(), 1.0);
assert_eq!(partial.compression_ratio(), 1.0);
}
#[cfg(feature = "serde")]
#[test]
fn transcription_timings_serde_round_trips_and_fills_sentinel_defaults() {
let t = TranscriptionTimings::new();
let json = serde_json::to_string(&t).unwrap();
assert_eq!(
serde_json::from_str::<TranscriptionTimings>(&json).unwrap(),
t
);
let partial: TranscriptionTimings = serde_json::from_str("{}").unwrap();
assert_eq!(partial.pipeline_start(), f64::MAX);
assert_eq!(partial.input_audio_seconds(), 0.001);
}
#[cfg(feature = "serde")]
#[test]
fn transcription_result_serde_skips_absent_seek_time() {
let r = TranscriptionResult::new("hi", Vec::new(), "en", TranscriptionTimings::new());
let json = serde_json::to_string(&r).unwrap();
assert!(!json.contains("seek_time"));
assert_eq!(
serde_json::from_str::<TranscriptionResult>(&json).unwrap(),
r
);
let with_seek = r.with_seek_time(1.5);
let json = serde_json::to_string(&with_seek).unwrap();
assert!(json.contains("seek_time"));
assert_eq!(
serde_json::from_str::<TranscriptionResult>(&json).unwrap(),
with_seek
);
}
#[cfg(feature = "serde")]
#[test]
fn task_facts_draw_flag_is_required_on_deserialize() {
// F1 (codex round 2), now carried in the embedded `task_facts`. The draw flag
// must never silently default to `false` ("never sampled", the optimistic
// answer) when a persisted record drops it: a blank-dropped result whose
// sampled window was filtered away carries the fact ONLY here, and a `false`
// default would hand `Provenance::is_reproducible` a guarantee the run never
// earned. Mirrors the same requirement on the record itself
// (`task_facts::tests::the_reproducibility_and_coordinate_facts_are_required_on_deserialize`).
let sampled_empty = TranscriptionResult::new("", Vec::new(), "en", TranscriptionTimings::new())
.with_task_facts(TaskFacts::unknown().with_drew_from_rng(true));
let value: serde_json::Value = serde_json::to_value(&sampled_empty).unwrap();
// The intact record round-trips, or the removals below prove nothing.
assert_eq!(
serde_json::from_value::<TranscriptionResult>(value.clone()).unwrap(),
sampled_empty
);
// Drop the nested draw flag: it must FAIL, not default to `false`.
let mut without_flag = value.clone();
assert!(
without_flag
.as_object_mut()
.unwrap()
.get_mut("task_facts")
.unwrap()
.as_object_mut()
.unwrap()
.remove("drew_from_rng")
.is_some(),
"the flag is always serialized, so the key must have been present"
);
assert!(
serde_json::from_value::<TranscriptionResult>(without_flag).is_err(),
"a dropped `task_facts.drew_from_rng` must be rejected, not read back false"
);
// Drop the whole `task_facts` block: also rejected — the record is required.
let mut without_facts = value;
without_facts
.as_object_mut()
.unwrap()
.remove("task_facts")
.unwrap();
assert!(
serde_json::from_value::<TranscriptionResult>(without_facts).is_err(),
"a result missing its whole `task_facts` block must be rejected, not defaulted"
);
}
#[cfg(feature = "serde")]
#[test]
fn decoding_result_serde_round_trips_and_skips_empty_collections() {
let r = DecodingResult::new().with_text("hi");
let json = serde_json::to_string(&r).unwrap();
let value: serde_json::Value = serde_json::from_str(&json).unwrap();
let object = value.as_object().unwrap();
assert!(!object.contains_key("language"));
assert!(!object.contains_key("tokens"));
assert!(!object.contains_key("token_log_probs"));
assert!(!object.contains_key("language_probs"));
assert_eq!(serde_json::from_str::<DecodingResult>(&json).unwrap(), r);
assert_eq!(
serde_json::from_str::<DecodingResult>("{}").unwrap(),
DecodingResult::new()
);
}
#[cfg(feature = "serde")]
#[test]
fn transcription_progress_serde_round_trips_and_skips_absent_optionals() {
let p = TranscriptionProgress::new(TranscriptionTimings::new(), "hi", Vec::new());
let json = serde_json::to_string(&p).unwrap();
let value: serde_json::Value = serde_json::from_str(&json).unwrap();
let object = value.as_object().unwrap();
assert!(!object.contains_key("temperature"));
assert!(!object.contains_key("avg_logprob"));
assert!(!object.contains_key("compression_ratio"));
assert!(!object.contains_key("tokens"));
assert_eq!(
serde_json::from_str::<TranscriptionProgress>(&json).unwrap(),
p
);
}
#[cfg(feature = "serde")]
#[test]
fn fallback_reason_serde_uses_swift_strings() {
assert_eq!(
serde_json::to_string(&FallbackReason::FirstTokenLogProbThreshold).unwrap(),
"\"firstTokenLogProbThreshold\""
);
assert_eq!(
serde_json::from_str::<FallbackReason>("\"logProbThreshold\"").unwrap(),
FallbackReason::LogProbThreshold
);
}
// ---------------------------------------------------------------------
// all_words / format_segments / merge_transcription_results_with_words
// ---------------------------------------------------------------------
fn timed_word(text: &str, start: f32, end: f32) -> WordTiming {
// See the analogous NOTE on `word()` in `text/tests.rs`: `.into()` on
// `text` is dropped here for the same E0283 ambiguity reason already
// documented earlier in this file's own `WordTiming::new` call sites.
WordTiming::new(text, vec![1], start, end, 0.9)
}
fn segment_with_words(
start: f32,
end: f32,
text: &str,
words: Vec<WordTiming>,
) -> TranscriptionSegment {
let mut segment = TranscriptionSegment::new();
segment
.set_start(start)
.set_end(end)
.set_text(text)
.set_words(words);
segment
}
#[test]
fn all_words_flattens_segments_in_order() {
// Models.swift:566-570
let mut result = TranscriptionResult::new("", Vec::new(), "", TranscriptionTimings::new());
result.set_segments(vec![
segment_with_words(0.0, 1.0, " Hi", vec![timed_word(" Hi", 0.0, 0.5)]),
segment_with_words(
1.0,
2.0,
" there now",
vec![timed_word(" there", 1.0, 1.4), timed_word(" now", 1.4, 1.9)],
),
]);
let words = result.all_words();
assert_eq!(words.len(), 3);
assert_eq!(words[1].word(), " there");
// Segments without words contribute nothing (empty-means-absent).
let mut bare = TranscriptionResult::new("", Vec::new(), "", TranscriptionTimings::new());
bare.set_segments(vec![segment_with_words(0.0, 1.0, " Hi", vec![])]);
assert!(bare.all_words().is_empty());
}
#[test]
fn format_segments_renders_timestamps_and_raw_text() {
// TranscriptionUtilities.swift:16-27 + Logging.formatTimestamp ("%.2f").
let segments = [segment_with_words(0.0, 2.5, " Hello", vec![])];
assert_eq!(
format_segments(&segments, true),
vec!["[0.00 --> 2.50] Hello".to_string()]
);
assert_eq!(
format_segments(&segments, false),
vec![" Hello".to_string()]
);
}
#[test]
fn merge_with_confirmed_words_overrides_text_only() {
// TranscriptionUtilities.swift:76-82 — confirmed words joined with NO
// separator; segments/language/timings identical to the SAME-options merge.
let mut first = TranscriptionResult::new("", Vec::new(), "", TranscriptionTimings::new());
first
.set_text("hello")
.set_language("en")
.set_segments(vec![segment_with_words(0.0, 1.0, "hello", vec![])]);
let mut second = TranscriptionResult::new("", Vec::new(), "", TranscriptionTimings::new());
second
.set_text("world")
.set_segments(vec![segment_with_words(30.0, 31.0, "world", vec![])]);
let results = [first, second];
let confirmed = [timed_word(" And", 0.0, 0.4), timed_word(" so", 0.4, 0.7)];
let options = DecodingOptions::new();
let with_words = merge_transcription_results_with_words(&results, &confirmed, &options);
// Compared against the SAME-options merge, not the options-blind one:
// everything but the text must match what the confirmed-words path builds.
let plain = merge_transcription_results_with_options(&results, &options);
assert_eq!(with_words.text(), " And so");
assert_eq!(plain.text(), "hello world");
assert_eq!(with_words.segments_slice(), plain.segments_slice());
assert_eq!(with_words.language(), plain.language());
}
#[test]
fn merge_with_confirmed_words_honors_drop_blank_id_mapping() {
// F5 (codex round 3). The confirmed-words merge delegated to the plain
// (drop-OFF) merge, so a survivor id gap [0, 2] came back densely
// renumbered [0, 1] -- the confirmed TEXT override is options-blind, but the
// merged SEGMENT ids are not (drop now controls the id mapping, coremlit
// #14 / F4). LocalAgreement::finalize (the default streaming path) inherited
// that loss; see `stream::agreement::tests` for the finalize half.
let seg = |id: usize, token: u32| {
let mut s = TranscriptionSegment::new();
s.set_id(id).set_tokens(vec![token]);
s
};
let chunk = TranscriptionResult::new(
"A B",
vec![seg(0, 10), seg(2, 12)],
"en",
TranscriptionTimings::new(),
);
let confirmed = [timed_word(" X", 0.0, 0.4)];
// drop-ON (the default): the [0, 2] gap survives, text still overridden.
let dropped = merge_transcription_results_with_words(
std::slice::from_ref(&chunk),
&confirmed,
&DecodingOptions::new(),
);
assert_eq!(
dropped
.segments_slice()
.iter()
.map(TranscriptionSegment::id)
.collect::<Vec<_>>(),
vec![0, 2],
"confirmed-words merge must preserve the dropped-id gap, not renumber to [0, 1]"
);
assert_eq!(
dropped.text(),
" X",
"text is still the confirmed-words override"
);
// drop-OFF: EXACTLY Swift's dense reindex [0, 1].
let dense = merge_transcription_results_with_words(
std::slice::from_ref(&chunk),
&confirmed,
&DecodingOptions::new().maybe_drop_blank_audio(false),
);
assert_eq!(
dense
.segments_slice()
.iter()
.map(TranscriptionSegment::id)
.collect::<Vec<_>>(),
vec![0, 1],
"drop-OFF stays Swift-exact result_index + segment_index"
);
}
#[test]
fn merge_ors_the_sampling_fact_across_results() {
// The VAD-chunk instance of finding 2: a chunk the blank-audio drop
// emptied contributes NO segments, so its accepted temperature is nowhere
// in the merged segment list. The merge has to carry the fact out of it
// anyway, or the merged transcript looks greedy and claims a
// byte-reproducibility it cannot honor.
// A genuinely greedy chunk POSITIVELY records `drew_from_rng = Some(false)` —
// the shape a real decode carries — not the bare `unknown()` a segment alone
// would leave (which the merge could not tell from "never observed").
let greedy = TranscriptionResult::new(
"Hello",
vec![TranscriptionSegment::new().with_temperature(0.0)],
"en",
TranscriptionTimings::new(),
)
.with_task_facts(TaskFacts::unknown().with_drew_from_rng(false));
// The emptied chunk: zero segments, and the only witness to its own
// sampling is the carried flag itself.
let emptied = TranscriptionResult::new("", Vec::new(), "en", TranscriptionTimings::new())
.with_task_facts(TaskFacts::unknown().with_drew_from_rng(true));
assert!(emptied.segments_slice().is_empty());
let merged = merge_transcription_results(&[greedy.clone(), emptied.clone()]);
assert!(
merged
.segments_slice()
.iter()
.all(|segment| segment.temperature() == 0.0),
"no surviving segment carries the evidence"
);
assert_eq!(
merged.task_facts().drew_from_rng(),
Some(true),
"and yet the merge must still know"
);
// Same through the options-aware door `WhisperKit::transcribe` actually uses.
assert_eq!(
merge_transcription_results_with_options(&[greedy.clone(), emptied], &DecodingOptions::new())
.task_facts()
.drew_from_rng(),
Some(true),
);
// All-greedy merges stay honest in the other direction: two observed
// `Some(false)` stay `Some(false)`, never OR-ing up to a phantom draw.
assert_eq!(
merge_transcription_results(&[greedy.clone(), greedy])
.task_facts()
.drew_from_rng(),
Some(false),
);
// An empty merge observed nothing at all — explicit unknown, not `Some(false)`.
assert_eq!(
merge_transcription_results(&[])
.task_facts()
.drew_from_rng(),
None,
);
}
#[test]
fn merge_carries_the_first_observed_language() {
// F3 (codex round 3). The merged observation is the FIRST result that
// WITNESSED a language, scanning ALL results -- not `results.first()`, which
// dropped `[None, Some("es")]` to `None`, losing an observation the batch
// plainly made. It is deliberately independent of the merged DISPLAY
// language (the first result's, keeping its Swift-compat fallback).
let observed = |lang: Option<&str>| {
TranscriptionResult::new("x", Vec::new(), "en", TranscriptionTimings::new())
.with_task_facts(TaskFacts::unknown().with_observed_language(lang.map(str::to_string)))
};
// [None, Some("es")] -> Some("es"): the pre-fix first-only read returned None.
let merged = merge_transcription_results(&[observed(None), observed(Some("es"))]);
assert_eq!(
merged.task_facts().observed_language(),
Some("es"),
"an observation in a later chunk must survive the merge"
);
assert_eq!(
merged.language(),
"en",
"the DISPLAY language stays the first result's, independent of the observation"
);
// Conflicting observations: first observed wins (the documented scalar rule).
assert_eq!(
merge_transcription_results(&[observed(Some("es")), observed(Some("fr"))])
.task_facts()
.observed_language(),
Some("es"),
);
// No result observed anything -> None, not the display fallback.
assert_eq!(
merge_transcription_results(&[observed(None), observed(None)])
.task_facts()
.observed_language(),
None,
);
// Through the options-aware door too.
assert_eq!(
merge_transcription_results_with_options(
&[observed(None), observed(Some("es"))],
&DecodingOptions::new(),
)
.task_facts()
.observed_language(),
Some("es"),
);
}
#[test]
fn new_does_not_infer_observed_language_from_the_display_language() {
// F3 (codex round 3). The display language is not an observation, so `new`
// must NOT seed the task facts' observed language from it -- a configured or
// fallback code was never *detected*. Only an explicit record carries one.
let r = TranscriptionResult::new("hi", Vec::new(), "es", TranscriptionTimings::new());
assert_eq!(r.language(), "es", "the display language is still set");
assert_eq!(
r.task_facts().observed_language(),
None,
"but no observation is inferred from the display language"
);
assert_eq!(
r.with_task_facts(TaskFacts::unknown().with_observed_language(Some("es".to_string())))
.task_facts()
.observed_language(),
Some("es"),
"an explicit observation is still recorded"
);
}
#[cfg(feature = "serde")]
#[test]
fn segment_non_finite_temperature_is_rejected_by_serde() {
// Codex round 3, F6. `temperature` is the one `TranscriptionSegment` float
// bridged through the finite-float guard, because `provenance` reads it
// (`unanimous_temperature`, `sampled_at_nonzero_temperature`) to decide
// reproducibility — a non-finite value silently changing across a round trip
// would corrupt that record. It is refused on serialize rather than written
// as the lossy `null` serde_json emits; a finite segment still round-trips.
// The descriptive telemetry floats beside it (`avg_logprob`,
// `compression_ratio`, `no_speech_prob`) are deliberately left unguarded.
for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
let segment = TranscriptionSegment::new().with_temperature(bad);
assert!(serde_json::to_string(&segment).is_err());
}
let finite = TranscriptionSegment::new()
.with_id(2)
.with_text("hola")
.with_temperature(0.2);
let json = serde_json::to_string(&finite).unwrap();
assert_eq!(
serde_json::from_str::<TranscriptionSegment>(&json).unwrap(),
finite
);
}