File size: 78,676 Bytes
2155bf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75d0c53
2155bf9
ba2d582
 
75d0c53
2155bf9
 
 
 
 
 
 
5e4829a
2155bf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba2d582
 
 
 
 
2155bf9
 
 
ba2d582
2155bf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adad9b6
 
 
 
 
 
 
 
 
 
 
444bc2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2155bf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e4829a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2155bf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be9c1db
 
 
 
 
 
 
 
 
 
 
 
 
 
2155bf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aeab028
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2155bf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aeab028
 
 
 
2155bf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75d0c53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f851454
 
 
 
 
 
75d0c53
 
f851454
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75d0c53
 
 
 
 
 
 
 
 
f851454
75d0c53
 
 
 
 
 
 
 
 
 
 
 
f851454
 
 
 
 
 
 
 
75d0c53
 
2155bf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c712e7e
 
 
 
2155bf9
c712e7e
 
 
2155bf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e4829a
2155bf9
 
 
 
5e4829a
2155bf9
 
 
 
 
 
 
444bc2b
 
 
 
 
 
 
 
 
 
2155bf9
444bc2b
 
2155bf9
 
 
5e4829a
 
 
 
 
444bc2b
5e4829a
 
 
 
444bc2b
5e4829a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2155bf9
 
 
444bc2b
2155bf9
 
444bc2b
2155bf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e4829a
 
2155bf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75d0c53
2155bf9
 
75d0c53
 
 
 
2155bf9
 
 
 
 
 
 
75d0c53
 
2155bf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b12415f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2155bf9
5e4829a
2155bf9
 
 
 
 
5e4829a
 
 
 
 
 
 
af26f09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75d0c53
 
af26f09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adad9b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af26f09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75d0c53
 
85405e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12a7ca3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f851454
12a7ca3
f851454
 
 
 
12a7ca3
f851454
12a7ca3
 
 
 
f851454
12a7ca3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9da392
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12a7ca3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f851454
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c712e7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a7fa0c
419e0a5
c712e7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a7fa0c
c712e7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba2d582
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Spec: the local (mps/cpu) runner — staged residency, GGUF transformer, RoPE, CRF.

Issue F21. Every behavioural test here runs the REAL diffusers classes on the
tiny random-weight LTX-2.5 checkpoint already in the HF cache, through the same
seam the app uses: ``generate()`` with the runner injected as its pipeline
factory. Nothing is downloaded and nothing larger than the tiny checkpoint is
ever loaded.

The central claim: a staged run (text encoder loaded, used and freed before the
transformer is loaded) produces exactly what a resident run (everything loaded,
the pipeline encoding its own prompt) produces.
"""

from __future__ import annotations

import gc
import itertools
import json
import re
import sys
from pathlib import Path

import pytest
from local_fakes import (
    RecordingEncoder,
    as_array,
    install_tiny_audio_encode_shim,
    tiny_snapshot,
    transformer_inputs,
    write_faithful_gguf,
)

from ltx25_studio import local_runtime, memory
from ltx25_studio.errors import ConstraintError, LTXStudioError, ModelLoadError

SIZE = 64
FRAMES = 9
SEED = 1234
PROMPT = "a red ball bouncing on a wooden floor"


@pytest.fixture(autouse=True)
def _fresh_runtime():
    local_runtime.clear_local_cache()
    yield
    local_runtime.clear_local_cache()
    gc.collect()


@pytest.fixture(autouse=True)
def _no_limit_surprises(monkeypatch):
    """The tiny runs need well under a GB; the gauge itself stays live.

    Settling and reading again are off (0 s) except where a test scripts the
    gauge and the clock: on this live gauge they would really sleep.
    """
    monkeypatch.delenv("LTX25_MEMORY_LIMIT_GB", raising=False)
    monkeypatch.delenv("LTX25_LOAD_SPIKE_FACTOR", raising=False)
    monkeypatch.delenv("LTX25_ACTIVATION_CALIBRATION", raising=False)
    monkeypatch.setenv("LTX25_MEMORY_SETTLE_SECONDS", "0")


def _torch():
    return pytest.importorskip("torch")


def _runner(kind, residency, *, device="cpu", dtype="float32", log=None, **extra):
    _torch()
    pytest.importorskip("diffusers")
    return local_runtime.build_local_runner(
        kind=kind,
        device=device,
        dtype=dtype,
        snapshot_dir=tiny_snapshot(),
        residency=residency,
        log=log,
        **extra,
    )


def _factory(residency, *, device="cpu", dtype="float32", log=None, shim_audio=False):
    def factory(*, pipeline, **_):
        runner = _runner(pipeline, residency, device=device, dtype=dtype, log=log)
        if shim_audio:
            install_tiny_audio_encode_shim(runner.pipeline.audio_vae)
        return runner

    return factory


def _inputs(tmp_path):
    """A real image, a real 9-frame mp4 and a real WAV, written to tmp_path."""
    from fractions import Fraction

    import av
    import numpy as np
    from PIL import Image

    rng = np.random.default_rng(0)
    image = Image.fromarray(rng.integers(0, 255, (SIZE, SIZE, 3), dtype=np.uint8))
    video = tmp_path / "in.mp4"
    with av.open(str(video), "w") as container:
        stream = container.add_stream("h264", rate=24)
        stream.width = stream.height = SIZE
        stream.pix_fmt = "yuv420p"
        for index in range(FRAMES):
            frame = av.VideoFrame.from_ndarray(
                rng.integers(0, 255, (SIZE, SIZE, 3), dtype=np.uint8), format="rgb24"
            )
            frame.pts, frame.time_base = index, Fraction(1, 24)
            for packet in stream.encode(frame):
                container.mux(packet)
        for packet in stream.encode():
            container.mux(packet)
    wav = tmp_path / "in.wav"
    rate = 16000
    samples = int(rate * FRAMES / 24.0) + 1
    tone = (np.sin(np.linspace(0, 200 * np.pi, samples)) * 8000).astype(np.int16)
    with av.open(str(wav), "w", format="wav") as container:
        stream = container.add_stream("pcm_s16le", rate=rate, layout="stereo")
        frame = av.AudioFrame.from_ndarray(
            np.stack([tone, tone], axis=1).reshape(1, -1), format="s16", layout="stereo"
        )
        frame.sample_rate = rate
        for packet in stream.encode(frame):
            container.mux(packet)
        for packet in stream.encode():
            container.mux(packet)
    return {"image": image, "video": str(video), "audio": str(wav)}


def _generate(residency, mode, tmp_path, *, progress=None, shim_audio=False, **fields):
    from ltx25_studio import generate as generate_module

    encoder = RecordingEncoder()
    out = tmp_path / f"out-{residency}-{mode}"
    result = generate_module.generate(
        mode=mode,
        seed=SEED,
        width=SIZE,
        height=SIZE,
        num_frames=FRAMES,
        pipeline_factory=_factory(residency, shim_audio=shim_audio),
        encoder=encoder,
        output_root=out,
        retention_bytes=10**12,
        progress=progress,
        **fields,
    )
    assert result.output_path.is_file()
    (output,) = encoder.outputs
    return output


def _assert_same(staged, resident):
    import numpy as np

    for field in ("frames", "audio"):
        a = as_array(getattr(staged, field, None))
        b = as_array(getattr(resident, field, None))
        assert (a is None) == (b is None), field
        if a is None:
            continue
        assert a.shape == b.shape, field
        assert np.max(np.abs(a - b)) <= 1e-6, f"{field} differs by {np.max(np.abs(a - b))}"


# --------------------------------------------------------------------------
# refusals that need no weights
# --------------------------------------------------------------------------


def test_cuda_is_refused_the_space_keeps_its_own_runner(tmp_path):
    with pytest.raises(local_runtime.UnsupportedLocalDeviceError) as caught:
        local_runtime.build_local_runner(
            kind="condition", device="cuda", dtype="bfloat16", snapshot_dir=tmp_path
        )
    assert isinstance(caught.value, LTXStudioError)
    assert "cuda" in str(caught.value).lower()


def test_an_mps_runner_refuses_a_watermark_setting_that_breaks_freeing_memory(
    tmp_path, monkeypatch
):
    monkeypatch.setenv("PYTORCH_MPS_HIGH_WATERMARK_RATIO", "0.5")
    monkeypatch.delenv("PYTORCH_MPS_LOW_WATERMARK_RATIO", raising=False)
    with pytest.raises(memory.MpsWatermarkError):
        local_runtime.build_local_runner(
            kind="condition", device="mps", dtype="bfloat16", snapshot_dir=tmp_path
        )


@pytest.mark.parametrize("mode", ["enforce", "warn"])
def test_an_mps_runner_is_gated_on_the_numerics_self_test(tmp_path, monkeypatch, mode):
    """The app's gate on the runner itself, so every entry that builds one is covered.

    ``scripts/local_generate.py --device mps`` builds through here alone.
    """
    torch = _torch()
    from ltx25_studio import device

    class Built(Exception):
        """The build got past the gate to its weights."""

    def weights(**_kwargs):
        raise Built

    for name in (memory.HIGH_WATERMARK_ENV, memory.LOW_WATERMARK_ENV):
        monkeypatch.delenv(name, raising=False)
    monkeypatch.setattr(torch.backends.mps, "is_available", lambda: True)
    failed = device.SelfTestCheck("sdpa_scale", False, "relative error 5.19")
    monkeypatch.setattr(device, "_MPS_SELF_TEST", device.MpsSelfTest("2.11.0", (failed,)))
    monkeypatch.setenv("LTX25_MPS_SELF_TEST", mode)
    monkeypatch.setattr(local_runtime, "missing_files", lambda *a, **k: [])
    monkeypatch.setattr(local_runtime, "_LocalWeights", weights)

    # warn: the operator's own choice to run unverified.
    with pytest.raises(device.MpsNumericsError if mode == "enforce" else Built):
        local_runtime.build_local_runner(
            kind="text2video", device="mps", dtype="bfloat16", snapshot_dir=tmp_path
        )


def test_an_unknown_residency_is_refused(tmp_path):
    with pytest.raises(ConstraintError, match="residency"):
        local_runtime.build_local_runner(
            kind="condition",
            device="cpu",
            dtype="float32",
            snapshot_dir=tmp_path,
            residency="sometimes",
        )


def test_the_rename_covers_both_prompt_adaln_families():
    state = {
        "prompt_adaln_single.linear.weight": 1,
        "prompt_adaln_single.emb.timestep_embedder.linear_1.bias": 2,
        "audio_prompt_adaln_single.linear.weight": 3,
        "adaln_single.linear.weight": 4,
        "transformer_blocks.0.attn1.to_q.weight": 5,
    }
    renamed, count = local_runtime.rename_prompt_adaln_keys(state)
    assert count == 3
    assert set(renamed) == {
        "prompt_adaln.linear.weight",
        "prompt_adaln.emb.timestep_embedder.linear_1.bias",
        "audio_prompt_adaln.linear.weight",
        "adaln_single.linear.weight",
        "transformer_blocks.0.attn1.to_q.weight",
    }
    assert renamed["audio_prompt_adaln.linear.weight"] == 3


def test_a_missing_file_names_the_exact_download_command(tmp_path):
    snapshot = tmp_path / "hub" / "models--Lightricks--LTX-2.5-Diffusers" / "snapshots" / "871165de"
    (snapshot / "text_encoder").mkdir(parents=True)
    (snapshot / "text_encoder" / "model.safetensors.index.json").write_text(
        json.dumps({"metadata": {"total_size": 10}, "weight_map": {"a": "model-1.safetensors"}})
    )
    gguf = (
        tmp_path
        / "hub"
        / "models--unsloth--LTX-2.5-GGUF"
        / "snapshots"
        / "ac3c540c"
        / "distilled"
        / "x-Q8_0.gguf"
    )
    missing = dict(local_runtime.missing_files(snapshot, transformer_gguf=gguf))
    assert missing[gguf] == (
        "hf download unsloth/LTX-2.5-GGUF distilled/x-Q8_0.gguf --revision ac3c540c"
    )
    shard = snapshot / "text_encoder" / "model-1.safetensors"
    assert missing[shard] == (
        'hf download Lightricks/LTX-2.5-Diffusers --revision 871165de --include "text_encoder/*"'
    )


def test_weight_files_are_found_on_disk_whatever_they_are_called(tmp_path):
    """No checkpoint file name is assumed: the shard index, else any weight file."""
    snapshot = tmp_path / "snapshot"
    configs = {"scheduler": "scheduler_config.json", "tokenizer": "tokenizer_config.json"}
    for component in (*local_runtime.SMALL_SET, "text_encoder", "transformer"):
        (snapshot / component).mkdir(parents=True)
        (snapshot / component / configs.get(component, "config.json")).write_text("{}")
    (snapshot / "model_index.json").write_text("{}")
    (snapshot / "tokenizer" / "tokenizer.json").write_text("{}")
    oddly_named = {
        "vae": "vae-weights.safetensors",
        "audio_vae": "a.safetensors",
        "vocoder": "model.safetensors",
        "duration_head": "head.safetensors",
        "text_encoder": "encoder.safetensors",
        "transformer": "dit.safetensors",
    }
    for component, name in oddly_named.items():
        (snapshot / component / name).write_bytes(b"x" * 100)
    (snapshot / "connectors" / "x.safetensors.index.json").write_text(
        json.dumps({"weight_map": {"a": "part-1.safetensors", "b": "part-2.safetensors"}})
    )
    for part in ("part-1", "part-2"):
        (snapshot / "connectors" / f"{part}.safetensors").write_bytes(b"y" * 50)

    assert local_runtime.missing_files(snapshot) == []
    sizes = local_runtime.weight_sizes(snapshot)
    assert sizes["vae"] == (100, "files") and sizes["connectors"] == (100, "files")
    assert local_runtime.component_files(snapshot, "vae") == [
        snapshot / "vae" / "vae-weights.safetensors"
    ]
    assert snapshot / "transformer" / "dit.safetensors" in local_runtime.run_files(snapshot)

    (snapshot / "vocoder" / "model.safetensors").unlink()
    (snapshot / "connectors" / "part-2.safetensors").unlink()
    missing = [path for path, _ in local_runtime.missing_files(snapshot)]
    assert missing == [snapshot / "connectors" / "part-2.safetensors", snapshot / "vocoder"]
    assert not any("diffusion_pytorch_model" in str(path) for path in missing)


# --------------------------------------------------------------------------
# staged == resident, through generate()
# --------------------------------------------------------------------------

EQUIVALENCE_CASES = {
    "text": ("text_to_video", lambda i: {"prompt": PROMPT}),
    "image": ("image_text_to_video", lambda i: {"prompt": PROMPT, "image": i["image"]}),
    "video": ("video_to_video", lambda i: {"prompt": PROMPT, "video": i["video"]}),
    "audio_latents": ("audio_to_video", lambda i: {"prompt": PROMPT, "audio": i["audio"]}),
    "text_audio": ("text_to_audio_video", lambda i: {"prompt": PROMPT}),
}


@pytest.mark.parametrize("case", sorted(EQUIVALENCE_CASES))
def test_staged_and_resident_runs_are_identical(case, tmp_path):
    mode, fields_for = EQUIVALENCE_CASES[case]
    fields = fields_for(_inputs(tmp_path))
    shim = case == "audio_latents"
    staged = _generate("staged", mode, tmp_path, shim_audio=shim, **fields)
    local_runtime.clear_local_cache()
    resident = _generate("resident", mode, tmp_path, shim_audio=shim, **fields)
    _assert_same(staged, resident)


def test_the_audio_pipeline_does_not_keep_a_released_transformer_alive(tmp_path):
    """The audio-conditioned derivative shares the staged pair; a release must reach it."""
    fields = {"prompt": PROMPT, "audio": _inputs(tmp_path)["audio"]}
    local_runtime.clear_local_cache()
    _generate("staged", "audio_to_video", tmp_path, shim_audio=True, **fields)
    runner = _runner("condition", "staged")
    derived = runner._audio_pipeline
    assert derived is not None and derived.transformer is not None

    runner._weights.release_transformer()

    assert derived.transformer is None, "the audio pipeline still holds the released transformer"


def test_the_duration_head_chooses_the_same_length_staged_and_resident(tmp_path):
    fields = {"prompt": PROMPT, "auto_duration": True, "min_seconds": 0.3, "max_seconds": 0.7}
    staged = _generate("staged", "text_to_audio_video", tmp_path, **fields)
    local_runtime.clear_local_cache()
    resident = _generate("resident", "text_to_audio_video", tmp_path, **fields)
    _assert_same(staged, resident)


def test_progress_sees_the_same_steps_staged_and_resident(tmp_path):
    counts = {}
    for residency in ("staged", "resident"):
        calls = []
        local_runtime.clear_local_cache()
        _generate(
            residency,
            "text_to_video",
            tmp_path,
            prompt=PROMPT,
            progress=lambda *a, sink=calls, **k: sink.append((a, tuple(sorted(k.items())))),
        )
        counts[residency] = [c for c in calls if "sampling" in repr(c).lower()]
    assert counts["staged"], "no sampling progress reached the handle"
    assert len(counts["staged"]) == len(counts["resident"])


# --------------------------------------------------------------------------
# what the bar says while a staged run loads (F65)
#
# Measured on real weights: "sampling - 12%" for the first 60 s of a staged run,
# while the text encoder and the transformer loaded inside the denoise stage, and
# "sampling - 82%" while the frames decoded. The bar's labels and the runner's own
# phase lines go on one timeline (an entry repeated in a row is kept once).
# --------------------------------------------------------------------------


def _labelled_run(residency, tmp_path, name):
    from ltx25_studio import generate as generate_module

    timeline, positions = [], []

    def mark(entry):
        if not timeline or timeline[-1] != entry:
            timeline.append(entry)

    def handle(position, desc=None):
        positions.append((position, desc))
        mark(desc)

    def log(line):
        if line.startswith("phase["):
            mark(line.split(":", 1)[0])

    generate_module.generate(
        mode="text_to_video",
        prompt=PROMPT,
        seed=SEED,
        width=SIZE,
        height=SIZE,
        num_frames=FRAMES,
        pipeline_factory=_factory(residency, log=log),
        encoder=RecordingEncoder(),
        output_root=tmp_path / name,
        retention_bytes=10**12,
        progress=handle,
    )
    return timeline, positions


def test_a_staged_run_says_loading_while_it_loads_and_sampling_once_the_denoise_starts(tmp_path):
    first, positions = _labelled_run("staged", tmp_path, "first")

    assert first == [
        "loading the model",
        "phase[load small set]",
        "preparing the inputs",
        "loading the model",
        "phase[load text encoder]",
        "phase[encode prompt]",
        "phase[load transformer]",
        "sampling",
        "decoding the frames",
        "phase[denoise and decode]",
        "writing the file",
    ]
    fractions = [p for p, _ in positions if isinstance(p, (int, float))]
    assert fractions == sorted(fractions), positions
    # Named at the bar's current position: the load's own band is behind it by then.
    preparing = next(p for p, d in positions if d == "preparing the inputs")
    assert [p for p, d in positions if d == "loading the model"][1:] == [preparing], positions

    again, _ = _labelled_run("staged", tmp_path, "again")  # the same prompt: nothing loads

    assert again == [
        "loading the model",
        "preparing the inputs",
        "sampling",
        "decoding the frames",
        "phase[denoise and decode]",
        "writing the file",
    ]


# --------------------------------------------------------------------------
# the residency rule itself
# --------------------------------------------------------------------------


class _Watch:
    """A progress object (generate.ProgressReporter's shape) that inspects the pipeline."""

    def __init__(self):
        self.text_encoder_present_during_steps = []
        self.phases = []

    def phase(self, label):
        self.phases.append(label)

    def loading(self):
        self.phases.append("loading the model")

    def sampling(self, *, index=1, passes=1, decodes=False):
        def callback(pipeline, step, timestep, callback_kwargs):
            self.text_encoder_present_during_steps.append(pipeline.text_encoder is not None)
            return callback_kwargs

        return callback


def _watched_encode(runner):
    seen = []
    pipeline = runner.pipeline
    original = pipeline.encode_prompt

    def encode_prompt(*args, **kwargs):
        if kwargs.get("prompt_embeds") is not None:
            # The pipeline's own pass-through of precomputed embeddings: no encoding.
            return original(*args, **kwargs)
        seen.append(
            {
                "transformer_present": pipeline.transformer is not None,
                "text_encoder_present": pipeline.text_encoder is not None,
            }
        )
        return original(*args, **kwargs)

    pipeline.encode_prompt = encode_prompt
    return seen


def test_the_text_encoder_and_the_transformer_are_never_resident_together():
    torch = _torch()
    runner = _runner("text2video", "staged")
    encodes = _watched_encode(runner)
    watch = _Watch()
    for prompt in (PROMPT, "a second, different prompt"):
        runner(
            progress=watch,
            prompt=prompt,
            width=SIZE,
            height=SIZE,
            num_frames=FRAMES,
            generator=torch.Generator().manual_seed(SEED),
            output_type="np",
        )
    assert encodes == [
        {"transformer_present": False, "text_encoder_present": True},
        {"transformer_present": False, "text_encoder_present": True},
    ]
    assert watch.text_encoder_present_during_steps
    assert not any(watch.text_encoder_present_during_steps)
    assert runner.pipeline.text_encoder is None and runner.pipeline.transformer is not None


def test_a_repeated_prompt_skips_the_text_encoder_and_says_so():
    torch = _torch()
    lines = []
    runner = _runner("text2video", "staged", log=lines.append)
    encodes = _watched_encode(runner)
    for _ in range(2):
        runner(
            prompt=PROMPT,
            width=SIZE,
            height=SIZE,
            num_frames=FRAMES,
            generator=torch.Generator().manual_seed(SEED),
            output_type="np",
        )
    assert len(encodes) == 1
    assert any("cache hit" in line for line in lines)
    assert sum("load transformer" in line and "preflight" in line for line in lines) == 1


def test_a_preflight_runs_before_every_heavy_load_and_before_the_denoise():
    torch = _torch()
    lines = []
    runner = _runner("text2video", "staged", log=lines.append)
    runner(
        prompt=PROMPT,
        width=SIZE,
        height=SIZE,
        num_frames=FRAMES,
        generator=torch.Generator().manual_seed(SEED),
        output_type="np",
    )
    preflights = [line for line in lines if line.startswith("preflight[")]
    order = [line.split("]")[0].removeprefix("preflight[") for line in preflights]
    assert order[0] == "load small set"
    assert order[1:] == ["load text encoder", "load transformer", f"denoise {SIZE}x{SIZE}x{FRAMES}"]


def test_a_failing_preflight_refuses_before_loading_anything(monkeypatch):
    _torch()
    runner = _runner("text2video", "staged")
    monkeypatch.setenv("LTX25_MEMORY_LIMIT_GB", "1")
    with pytest.raises(memory.MemoryPreflightError):
        runner(prompt=PROMPT, width=SIZE, height=SIZE, num_frames=FRAMES, output_type="np")
    assert runner.pipeline.text_encoder is None
    assert runner.pipeline.transformer is None


def test_both_kinds_share_one_set_of_weights():
    a = _runner("text2video", "staged")
    b = _runner("condition", "staged")
    assert a is _runner("text2video", "staged")
    assert a.pipeline.vae is b.pipeline.vae
    assert a.pipeline.connectors is b.pipeline.connectors


# --------------------------------------------------------------------------
# file-cache pages: bounded moves and releases
# --------------------------------------------------------------------------


def _local_device():
    return "mps" if _mps_available() else "cpu"


@pytest.mark.parametrize("component", ["transformer", "text_encoder"])
def test_the_bounded_move_is_value_identical_to_a_plain_move(component, monkeypatch):
    torch = _torch()
    pytest.importorskip("diffusers")
    snapshot = tiny_snapshot()
    device = _local_device()
    releases = []
    monkeypatch.setattr(
        memory, "release_file_cache", lambda paths, **_: releases.append(list(paths)) or 0
    )

    def fresh():
        if component == "transformer":
            from diffusers import LTX2VideoTransformer3DModel

            return LTX2VideoTransformer3DModel.from_pretrained(
                snapshot, subfolder="transformer", torch_dtype=torch.float32
            )
        import transformers

        cls = getattr(
            transformers, json.loads((snapshot / "model_index.json").read_text())["text_encoder"][1]
        )
        return cls.from_pretrained(snapshot / "text_encoder", dtype=torch.float32)

    plain = fresh().to(device)
    lines = []
    files = sorted((snapshot / component).glob("*.safetensors"))
    bounded = local_runtime.move_to_device(
        fresh(), device, files=files, label=component, log=lines.append, chunk_bytes=4096
    )
    expected = dict(itertools.chain(plain.named_parameters(), plain.named_buffers()))
    got = dict(itertools.chain(bounded.named_parameters(), bounded.named_buffers()))
    assert set(got) == set(expected)
    for name, tensor in got.items():
        assert tensor.device.type == device, name
        assert tensor.dtype == expected[name].dtype, name
        assert torch.equal(tensor.cpu(), expected[name].cpu()), name
    if device != "cpu":
        assert len(releases) > 1, "a multi-chunk move releases file pages as it goes"
        assert releases[-1] == files
        assert lines[-1] == f"released 0.0 GB of file cache ({component})"
    else:
        # On the CPU at the file's own dtype the weights are its pages (local-runtime-9).
        assert releases == [], "the live weights' pages were released"
        assert lines[-1] == f"kept {component}'s file pages: they are the weights on cpu"


def test_a_converting_cpu_load_still_gives_the_read_pages_back(monkeypatch):
    """Converted copies are not the file: its pages are released as before."""
    torch = _torch()
    pytest.importorskip("diffusers")
    from diffusers import LTX2VideoTransformer3DModel

    releases = []
    monkeypatch.setattr(
        memory, "release_file_cache", lambda paths, **_: releases.append(list(paths)) or 0
    )
    model = LTX2VideoTransformer3DModel.from_pretrained(
        tiny_snapshot(), subfolder="transformer", torch_dtype=torch.bfloat16
    )
    files = sorted((tiny_snapshot() / "transformer").glob("*.safetensors"))
    local_runtime.move_to_device(model, "cpu", files=files, label="transformer")

    assert releases == [files]


@pytest.mark.parametrize("dtype", ["bfloat16", "float32"])
def test_every_staged_component_gives_its_file_pages_back(monkeypatch, dtype):
    """Each converting load and each unload releases its file's pages.

    At the checkpoint's own dtype (the tiny one is fp32) a CPU load keeps them:
    they are the weights (local-runtime-9). The unloads still release.
    """
    torch = _torch()
    released = []

    def spy(paths, **_):
        released.append({Path(p).parent.name for p in paths})
        return 0

    monkeypatch.setattr(memory, "release_file_cache", spy)
    lines = []
    runner = _runner("text2video", "staged", dtype=dtype, log=lines.append)
    for prompt in (PROMPT, "a second, different prompt"):
        runner(
            prompt=prompt,
            width=SIZE,
            height=SIZE,
            num_frames=FRAMES,
            generator=torch.Generator().manual_seed(SEED),
            output_type="np",
        )
    touched = set().union(*released)
    assert {"text_encoder", "transformer"} <= touched
    assert "released 0.0 GB of file cache (text_encoder)" in lines
    if dtype == "bfloat16":
        assert {"connectors", "vae", "audio_vae", "vocoder", "duration_head"} <= touched
        # each text-encoder load is followed by a release, and so is each unload
        assert sum(s == {"text_encoder"} for s in released) >= 4
        assert sum(s == {"transformer"} for s in released) >= 2
    else:
        assert sum(s == {"text_encoder"} for s in released) >= 2
        assert "kept text_encoder's file pages: they are the weights on cpu" in lines


# --------------------------------------------------------------------------
# image-conditioning CRF (recon K H7)
# --------------------------------------------------------------------------


def test_staged_and_resident_runs_recompress_the_image_at_the_same_crf(tmp_path, monkeypatch):
    _torch()
    pytest.importorskip("diffusers")
    from diffusers.pipelines.ltx2 import pipeline_ltx2_condition as condition_module
    from diffusers.pipelines.ltx2.utils import resolve_default_image_crf
    from transformers import AutoConfig

    used = []
    original = condition_module.apply_image_conditioning_crf

    def recording(image, crf):
        used.append(crf)
        return original(image, crf)

    monkeypatch.setattr(condition_module, "apply_image_conditioning_crf", recording)
    image = _inputs(tmp_path)["image"]
    by_residency = {}
    for residency in ("staged", "resident"):
        used.clear()
        local_runtime.clear_local_cache()
        _generate(residency, "image_text_to_video", tmp_path, prompt=PROMPT, image=image)
        by_residency[residency] = list(used)

    text_encoder_config = AutoConfig.from_pretrained(tiny_snapshot() / "text_encoder")
    expected = resolve_default_image_crf(type("TE", (), {"config": text_encoder_config})())
    assert expected == 18, "the tiny checkpoint carries the LTX-2.5 Gemma-4 encoder"
    assert resolve_default_image_crf(None) == 33, "what a staged run would silently fall to"
    assert by_residency["staged"] == by_residency["resident"] == [expected]


# --------------------------------------------------------------------------
# stage 2 and LoRA
# --------------------------------------------------------------------------


def test_a_real_size_stage_2_is_refused_before_anything_loads():
    """Off CUDA the stage-2 decoder runs on the CPU, at very small sizes only."""
    from ltx25_studio.device import StageTwoNeedsCudaError

    runner = _runner("text2video", "staged")
    with pytest.raises(StageTwoNeedsCudaError) as caught:
        runner(enable_stage_2=True, prompt=PROMPT, width=704, height=480, num_frames=121)
    assert "CUDA" in str(caught.value)
    assert runner.pipeline.text_encoder is None and runner.pipeline.transformer is None


def _adapter_config():
    from peft import LoraConfig

    return LoraConfig(r=4, lora_alpha=8, target_modules=["to_q", "to_v"], init_lora_weights=False)


def test_an_attached_adapter_survives_the_transformer_being_released():
    torch = _torch()
    pytest.importorskip("peft")

    def run(runner, prompt):
        return runner(
            prompt=prompt,
            width=SIZE,
            height=SIZE,
            num_frames=FRAMES,
            generator=torch.Generator().manual_seed(SEED),
            output_type="np",
        )

    outputs = {}
    for residency in ("staged", "resident"):
        local_runtime.clear_local_cache()
        runner = _runner("text2video", residency)
        run(runner, "warm up")  # leaves the transformer resident
        torch.manual_seed(0)
        runner.pipeline.transformer.add_adapter(_adapter_config(), adapter_name="user_lora_0")
        runner.pipeline.set_adapters("user_lora_0", 0.7)
        outputs[residency] = run(runner, PROMPT)  # staged: release, encode, reload
        assert "user_lora_0" in runner.pipeline.transformer.peft_config
        runner.pipeline.delete_adapters("user_lora_0")
    _assert_same(outputs["staged"], outputs["resident"])


def test_attaching_an_adapter_needs_the_transformer_loaded_first():
    """A staged runner holds no transformer between loads. Attaching then is refused
    in plain language (a LoRAError, so ``lora/apply.py`` passes it through untouched)
    instead of failing deep in peft; after ``ensure_transformer()`` it attaches."""
    pytest.importorskip("peft")
    torch = _torch()
    from peft.utils import get_peft_model_state_dict

    from ltx25_studio.errors import LoRAError

    donor = _runner("text2video", "resident").pipeline.transformer
    torch.manual_seed(0)
    donor.add_adapter(_adapter_config(), adapter_name="donor")
    weights = {
        f"transformer.{key}": value
        for key, value in get_peft_model_state_dict(donor, adapter_name="donor").items()
    }
    local_runtime.clear_local_cache()
    runner = _runner("text2video", "staged")
    assert runner.pipeline.transformer is None
    with pytest.raises(local_runtime.AdapterNeedsTransformerError) as caught:
        runner.pipeline.load_lora_weights(dict(weights), adapter_name="user_lora_0")
    assert isinstance(caught.value, LoRAError)
    runner.ensure_transformer()
    runner.pipeline.load_lora_weights(dict(weights), adapter_name="user_lora_0")
    assert "user_lora_0" in runner.pipeline.transformer.peft_config


# --------------------------------------------------------------------------
# RoPE precision
# --------------------------------------------------------------------------

SIX_ROPE_MODULES = {
    "connectors.video_connector.rope",
    "connectors.audio_connector.rope",
    "transformer.rope",
    "transformer.audio_rope",
    "transformer.cross_attn_rope",
    "transformer.cross_attn_audio_rope",
}


def test_cpu_keeps_the_checkpoints_double_precision_rope_untouched():
    runner = _runner("text2video", "resident")
    flags = local_runtime.rope_flags(runner.pipeline)
    assert set(flags) == SIX_ROPE_MODULES
    assert all(flags.values())
    assert not any(local_runtime.rope_on_cpu(runner.pipeline).values())


def _mps_available():
    torch = _torch()
    return bool(getattr(torch.backends, "mps", None) and torch.backends.mps.is_available())


def _past_a_failing_self_test(monkeypatch):
    """These tests are about the runner, not the numerics: on a PyTorch that fails the
    MPS self-test (2.11 does), they run unverified, as ``LTX25_MPS_SELF_TEST=warn``
    lets an operator. On one that passes, the default gate applies."""
    from ltx25_studio import device

    if not device.mps_self_test().ok:
        monkeypatch.setenv("LTX25_MPS_SELF_TEST", "warn")


@pytest.mark.skipif("not _mps_available()", reason="MPS is not available on this host")
def test_mps_keeps_float64_rope_by_computing_all_six_modules_on_the_cpu(monkeypatch):
    _past_a_failing_self_test(monkeypatch)
    runner = _runner("text2video", "resident", device="mps", dtype="bfloat16")
    flags = local_runtime.rope_flags(runner.pipeline)
    assert set(flags) == SIX_ROPE_MODULES
    assert all(flags.values()), "the checkpoint's double precision is kept, not switched off"
    assert local_runtime.rope_on_cpu(runner.pipeline) == dict.fromkeys(SIX_ROPE_MODULES, True)


@pytest.mark.skipif("not _mps_available()", reason="MPS is not available on this host")
def test_after_a_staged_reload_the_transformer_still_computes_rope_on_the_cpu(monkeypatch):
    """The staged runner reloads the transformer between prompts; the CPU-RoPE
    hooks live on module instances, so the fresh instance must get them again —
    and a forward on MPS must then match the CPU."""
    torch = _torch()
    _past_a_failing_self_test(monkeypatch)
    runner = _runner("text2video", "staged", device="mps", dtype="float32")
    loaded = []
    for prompt in (PROMPT, "a second, different prompt"):
        runner(
            prompt=prompt,
            width=SIZE,
            height=SIZE,
            num_frames=FRAMES,
            generator=torch.Generator().manual_seed(SEED),
            output_type="np",
        )
        loaded.append(runner.pipeline.transformer)
    assert loaded[0] is not loaded[1], "the second prompt released and reloaded the transformer"
    assert local_runtime.rope_on_cpu(runner.pipeline) == dict.fromkeys(SIX_ROPE_MODULES, True)

    reference = local_runtime.load_transformer(tiny_snapshot(), dtype=torch.float32, device="cpu")
    with torch.no_grad():
        on_cpu = reference(**transformer_inputs(reference.config, "cpu", torch.float32))[0]
        on_mps = loaded[1](**transformer_inputs(loaded[1].config, "mps", torch.float32))[0]
    error = float((on_mps.cpu() - on_cpu).abs().max() / on_cpu.abs().max())
    assert error <= 1e-3, f"MPS forward differs from the CPU by {error:.2e} (relative)"


@pytest.mark.skipif("not _mps_available()", reason="MPS is not available on this host")
def test_a_staged_tiny_text_to_video_completes_on_mps_in_bf16(tmp_path, monkeypatch):
    from ltx25_studio import generate as generate_module

    _past_a_failing_self_test(monkeypatch)
    result = generate_module.generate(
        mode="text_to_video",
        prompt=PROMPT,
        seed=SEED,
        width=SIZE,
        height=SIZE,
        num_frames=FRAMES,
        pipeline_factory=_factory("staged", device="mps", dtype="bfloat16"),
        output_root=tmp_path / "out",
        retention_bytes=10**12,
    )
    assert result.output_path.is_file()
    runner = local_runtime.build_local_runner(
        kind="text2video", device="mps", dtype="bfloat16", snapshot_dir=tiny_snapshot()
    )
    assert runner.pipeline.device.type == "mps"
    flags = local_runtime.rope_flags(runner.pipeline)
    assert set(flags) == SIX_ROPE_MODULES and all(flags.values())
    assert all(local_runtime.rope_on_cpu(runner.pipeline).values())


# --------------------------------------------------------------------------
# the GGUF transformer (needs the `gguf` package)
# --------------------------------------------------------------------------


@pytest.fixture(scope="module")
def faithful_gguf(tmp_path_factory):
    pytest.importorskip("gguf", reason="the GGUF route needs the `gguf` package")
    target = tmp_path_factory.mktemp("gguf") / "tiny-real-names-Q8_0.gguf"
    reference = write_faithful_gguf(tiny_snapshot(), target)
    return target, reference


def test_the_tiny_gguf_really_uses_the_original_key_names(faithful_gguf):
    from diffusers.models.model_loading_utils import load_gguf_checkpoint

    path, _ = faithful_gguf
    keys = set(load_gguf_checkpoint(str(path)))
    assert any(k.startswith("prompt_adaln_single.") for k in keys)
    assert any(k.startswith("audio_prompt_adaln_single.") for k in keys)
    assert any(k.startswith("adaln_single.") for k in keys)
    assert not any(k.startswith("time_embed.") for k in keys)


def test_without_the_rename_the_gguf_load_is_refused_naming_the_key(faithful_gguf):
    torch = _torch()
    path, _ = faithful_gguf
    with pytest.raises(local_runtime.TransformerLoadError) as caught:
        local_runtime.load_transformer(
            tiny_snapshot(), dtype=torch.bfloat16, device="cpu", gguf=path, rename=False
        )
    assert isinstance(caught.value, ModelLoadError)
    assert "prompt_adaln" in str(caught.value)


def test_with_the_rename_the_gguf_loads_completely_and_runs(faithful_gguf, monkeypatch):
    torch = _torch()
    path, _ = faithful_gguf
    released = []
    monkeypatch.setattr(
        memory, "release_file_cache", lambda paths, **_: released.append(list(paths)) or 0
    )
    lines = []
    model = local_runtime.load_transformer(
        tiny_snapshot(), dtype=torch.bfloat16, device="cpu", gguf=path, log=lines.append
    )
    assert not [n for n, p in model.named_parameters() if p.device.type == "meta"]
    assert any("0 missing, 0 unexpected" in line for line in lines)
    assert any("Q8_0" in line for line in lines), lines
    # once after the read (the loader has copied everything), once after the move
    assert sum(paths == [path] for paths in released) >= 2


def test_a_staged_run_with_the_gguf_transformer_completes(faithful_gguf, tmp_path):
    from ltx25_studio import generate as generate_module

    path, _ = faithful_gguf

    def factory(*, pipeline, **_):
        return local_runtime.build_local_runner(
            kind=pipeline,
            device="cpu",
            dtype="bfloat16",
            snapshot_dir=tiny_snapshot(),
            transformer_gguf=path,
        )

    result = generate_module.generate(
        mode="text_to_video",
        prompt=PROMPT,
        seed=SEED,
        width=SIZE,
        height=SIZE,
        num_frames=FRAMES,
        pipeline_factory=factory,
        output_root=tmp_path / "out",
        retention_bytes=10**12,
    )
    assert result.output_path.is_file()


def _quantized_cases():
    from ltx25_studio import audio_conditioning, modes

    cases = [(mode_id, {}) for mode_id in modes.MODES if mode_id != "audio_to_audio"]
    cases += [
        ("audio_to_audio", {"noise_scale": level}) for level in audio_conditioning.VARIATION_LEVELS
    ]
    return cases


@pytest.mark.parametrize("mode_id,extra", _quantized_cases())
def test_every_mode_runs_on_the_quantized_runner(
    faithful_gguf, tmp_path, monkeypatch, mode_id, extra
):
    """The real-weights failure: deriving the audio pipeline cast the GGUF transformer.

    ``from_pipe(base, dtype=...)`` calls ``.to(dtype)`` on every module, and a
    GGUF-quantized model refuses it ("Casting a quantized model to a new dtype is
    unsupported"). Every mode once on the quantized runner, so the next
    quantization-only failure cannot hide.
    """
    from ltx25_studio import generate as generate_module
    from ltx25_studio import modes

    monkeypatch.setattr(modes, "MIN_RESOLUTION", SIZE)
    path, _ = faithful_gguf
    media = _inputs(tmp_path)
    fields = {"prompt": PROMPT}
    for kind in modes.get_mode(mode_id).inputs:
        if kind in media:
            fields[kind] = media[kind]

    def factory(*, pipeline, **_):
        runner = local_runtime.build_local_runner(
            kind=pipeline,
            device="cpu",
            dtype="bfloat16",
            snapshot_dir=tiny_snapshot(),
            transformer_gguf=path,
        )
        install_tiny_audio_encode_shim(runner.pipeline.audio_vae)
        return runner

    result = generate_module.generate(
        mode=mode_id,
        seed=SEED,
        width=SIZE,
        height=SIZE,
        num_frames=FRAMES,
        **{**fields, **extra},
        pipeline_factory=factory,
        output_root=tmp_path / "out",
        retention_bytes=10**12,
    )
    assert result.output_path.is_file()
    if "noise_scale" in extra:
        assert result.record.audio_level == extra["noise_scale"]


@pytest.mark.skipif("not _mps_available()", reason="MPS is not available on this host")
def test_the_gguf_transformer_on_mps_computes_its_float64_rope_on_the_cpu(faithful_gguf):
    torch = _torch()
    path, _ = faithful_gguf
    model = local_runtime.load_transformer(
        tiny_snapshot(), dtype=torch.bfloat16, device="mps", gguf=path
    )
    rope = [m for m in model.modules() if hasattr(m, "double_precision")]
    assert len(rope) == 4
    assert all(m.double_precision for m in rope)
    assert all(getattr(m, "_ltx25_rope_cpu", False) for m in rope)
    with torch.no_grad():
        out = model(**transformer_inputs(model.config, "mps", torch.bfloat16))[0]
    assert bool(torch.isfinite(out).all())


# --------------------------------------------------------------------------
# scripts/local_generate.py: exit codes and the dry run
# --------------------------------------------------------------------------


def _script(*args, tmp_path):
    import os
    import subprocess
    import sys

    from conftest import REPO_ROOT

    report = tmp_path / "report.json"
    done = subprocess.run(
        [
            sys.executable,
            str(REPO_ROOT / "scripts" / "local_generate.py"),
            *args,
            "--json",
            str(report),
        ],
        cwd=str(tmp_path),
        capture_output=True,
        text=True,
        timeout=300,
        env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"},
    )
    data = json.loads(report.read_text()) if report.is_file() else {}
    return done, data


TINY_ARGS = (
    "--mode",
    "text_to_video",
    "--prompt",
    PROMPT,
    "--width",
    "64",
    "--height",
    "64",
    "--num-frames",
    "9",
    "--device",
    "cpu",
    "--dtype",
    "float32",
)


def test_the_dry_run_prints_the_plan_and_the_arithmetic_and_loads_nothing(tmp_path):
    done, data = _script(
        *TINY_ARGS, "--snapshot-dir", str(tiny_snapshot()), "--dry-run", tmp_path=tmp_path
    )
    assert done.returncode == 0, done.stdout[-2000:] + done.stderr[-2000:]
    assert "nothing was loaded" in done.stdout
    phases = [line.split("]")[0].split("[")[1] for line in data["projected_preflight"]]
    assert phases == ["load small set", "load text encoder", "load transformer", "denoise 64x64x9"]
    assert "phases" not in data and "artifacts" not in data
    assert "file_cache" not in data, "a dry run touches nothing, not even the page cache"
    assert "left alone (dry run)" in done.stdout


def test_a_missing_gguf_exits_2_with_the_download_command(tmp_path):
    gguf = (
        tmp_path
        / "hub"
        / "models--unsloth--LTX-2.5-GGUF"
        / "snapshots"
        / "ac3c540c"
        / "distilled"
        / "x-Q8_0.gguf"
    )
    done, data = _script(
        *TINY_ARGS,
        "--snapshot-dir",
        str(tiny_snapshot()),
        "--transformer-gguf",
        str(gguf),
        tmp_path=tmp_path,
    )
    assert done.returncode == 2, done.stdout[-2000:] + done.stderr[-2000:]
    command = "hf download unsloth/LTX-2.5-GGUF distilled/x-Q8_0.gguf --revision ac3c540c"
    assert command in done.stdout
    assert data["missing"] == [{"path": str(gguf), "command": command}]


def test_the_plan_shows_the_mps_watermarks_and_a_bad_pair_exits_2(tmp_path, monkeypatch):
    monkeypatch.setenv("PYTORCH_MPS_HIGH_WATERMARK_RATIO", "0.5")
    monkeypatch.setenv("PYTORCH_MPS_LOW_WATERMARK_RATIO", "0.4")
    done, data = _script(
        *TINY_ARGS, "--snapshot-dir", str(tiny_snapshot()), "--dry-run", tmp_path=tmp_path
    )
    assert done.returncode == 0, done.stdout[-2000:] + done.stderr[-2000:]
    assert data["plan"]["mps_watermarks"] == {"high": 0.5, "low": 0.4}
    assert "recommended_max_gb" in data["plan"]

    monkeypatch.delenv("PYTORCH_MPS_LOW_WATERMARK_RATIO")
    for extra in (("--dry-run",), ()):
        done, data = _script(
            *TINY_ARGS, "--snapshot-dir", str(tiny_snapshot()), *extra, tmp_path=tmp_path
        )
        assert done.returncode == 2, done.stdout[-2000:] + done.stderr[-2000:]
        assert data["error"]["type"] == "MpsWatermarkError"
        assert "PYTORCH_MPS_LOW_WATERMARK_RATIO" in data["error"]["message"]
        assert not data.get("phases") and "file_cache" not in data


def test_a_memory_refusal_exits_2_before_anything_loads(tmp_path):
    _torch()
    pytest.importorskip("diffusers")
    done, data = _script(
        *TINY_ARGS,
        "--snapshot-dir",
        str(tiny_snapshot()),
        "--memory-limit-gb",
        "1",
        tmp_path=tmp_path,
    )
    assert done.returncode == 2, done.stdout[-2000:] + done.stderr[-2000:]
    assert data["error"]["type"] in ("MemoryPreflightError", "ModelLoadError")
    assert "Not enough memory for 'load small set'" in data["error"]["message"]
    assert not data.get("phases")
    assert [entry["when"] for entry in data["file_cache"]] == ["before the run", "at exit"]
    assert all(entry["files"] > 0 for entry in data["file_cache"])


# --------------------------------------------------------------------------
# video_to_video's clip variation on the local runner (F66)
# --------------------------------------------------------------------------


@pytest.mark.parametrize("residency", ["staged", "resident"])
@pytest.mark.parametrize("level", [0.421875, 0.725, 0.909375])
def test_a_clip_variation_runs_on_the_local_runner(residency, level, tmp_path, monkeypatch):
    torch = _torch()
    from diffusers import LTX2ConditionPipeline, LTX2VideoTransformer3DModel

    from ltx25_studio import audio_conditioning
    from ltx25_studio import generate as generate_module

    sigmas, sent = [], []
    forward = LTX2VideoTransformer3DModel.forward

    def spy_forward(self, *args, **kwargs):
        sigmas.append(float(kwargs["sigma"].flatten()[0]) / 1000.0)
        return forward(self, *args, **kwargs)

    call = LTX2ConditionPipeline.__call__

    def spy_call(self, *args, **kwargs):
        sent.append(kwargs)
        return call(self, *args, **kwargs)

    monkeypatch.setattr(LTX2VideoTransformer3DModel, "forward", spy_forward)
    monkeypatch.setattr(LTX2ConditionPipeline, "__call__", spy_call)
    lines = []

    def factory(*, pipeline, **_):
        return local_runtime.build_local_runner(
            kind=pipeline,
            device="cpu",
            dtype="float32",
            snapshot_dir=tiny_snapshot(),
            residency=residency,
            log=lines.append,
        )

    result = generate_module.generate(
        mode="video_to_video",
        prompt=PROMPT,
        seed=SEED,
        width=SIZE,
        height=SIZE,
        video=_inputs(tmp_path)["video"],
        noise_scale=level,
        pipeline_factory=factory,
        output_root=tmp_path / "out",
        retention_bytes=10**12,
    )

    ((kwargs),) = sent
    tail = audio_conditioning.sigma_tail(level)
    assert not kwargs.get("conditions")
    assert kwargs["sigmas"] == tail and kwargs["noise_scale"] == level
    assert (
        tuple(kwargs["latents"].shape)[:3] == (1, 8, 2) and kwargs["latents"].dtype == torch.float32
    )
    assert sigmas == pytest.approx(tail)
    assert result.record.video_level == level and result.record.frames == FRAMES
    if residency == "staged":
        order = [
            line.split("]")[0].removeprefix("preflight[")
            for line in lines
            if line.startswith("preflight[")
        ]
        assert order.index(f"encode clip {SIZE}x{SIZE}x{FRAMES}") < order.index("load text encoder")


# --------------------------------------------------------------------------
# review findings: adapters across a staged release, the first LoRA run, and
# the load preflight's dtype (local-runtime-2 = lora-1, -6 = lora-2, -3)
# --------------------------------------------------------------------------


def _tiny_adapter(tmp_path):
    torch = _torch()
    from test_real_pipeline_tiny import load_smoke

    adapter = tmp_path / "look.safetensors"
    donor = local_runtime.load_transformer(tiny_snapshot(), dtype=torch.float32, device="cpu")
    load_smoke().make_lora(adapter, donor)
    return {"source": str(adapter), "path": str(adapter), "weight": 1.0, "report": object()}


def _run(runner, tmp_path, name, **fields):
    from ltx25_studio import generate as generate_module

    return generate_module.generate(
        mode="text_to_video",
        seed=SEED,
        width=SIZE,
        height=SIZE,
        num_frames=FRAMES,
        pipeline_factory=lambda **_: runner,
        output_root=tmp_path / name,
        retention_bytes=10**12,
        **fields,
    )


def test_an_adapter_from_a_failed_staged_run_is_not_restored_into_the_next(tmp_path, monkeypatch):
    pytest.importorskip("peft")
    lora = _tiny_adapter(tmp_path)
    runner = _runner("text2video", "staged")
    real_preflight = runner._weights._preflight

    def text_encoder_refuses(phase, need_gb):
        if phase == "load text encoder":  # after the adapter attached
            raise memory.MemoryPreflightError(reason="the text encoder does not fit (stand-in)")
        return real_preflight(phase, need_gb)

    monkeypatch.setattr(runner._weights, "_preflight", text_encoder_refuses)
    with pytest.raises(memory.MemoryPreflightError):
        _run(runner, tmp_path, "a", prompt="a first prompt", loras=(lora,))
    assert runner.pipeline.transformer is None, "the failed run released the transformer"

    monkeypatch.setattr(runner._weights, "_preflight", real_preflight)
    result = _run(runner, tmp_path, "b", prompt="a second prompt")

    assert not getattr(runner.pipeline.transformer, "peft_config", None), (
        "the failed run's adapter was re-attached to a run that asked for none"
    )
    assert result.record.adapters == ()


def test_the_first_lora_run_on_a_fresh_staged_runner_attaches(tmp_path):
    pytest.importorskip("peft")
    lora = _tiny_adapter(tmp_path)
    runner = _runner("text2video", "staged")
    assert runner.pipeline.transformer is None

    result = _run(runner, tmp_path, "a", prompt=PROMPT, loras=(lora,))

    ((_label, weight, attached),) = result.record.adapters
    assert weight == 1.0 and attached > 0


# --------------------------------------------------------------------------
# F57: an adapter a failed detach left behind never reaches the next run
# --------------------------------------------------------------------------


def _adapters_seen_by_the_denoise(monkeypatch):
    """Every transformer forward records the adapters peft holds on that transformer."""
    from diffusers import LTX2VideoTransformer3DModel

    seen = []
    forward = LTX2VideoTransformer3DModel.forward

    def watched(self, *args, **kwargs):
        held = set(getattr(self, "peft_config", None) or ())
        for _name, module in self.named_modules():
            layers = getattr(module, "lora_A", None)
            if layers is not None:
                held.update(layers.keys())
        seen.append(held)
        return forward(self, *args, **kwargs)

    monkeypatch.setattr(LTX2VideoTransformer3DModel, "forward", watched)
    return seen


def _detach_fails(runner, monkeypatch, *, times):
    """The runner's ``delete_adapters`` raises ``times`` times, then works."""
    guarded = runner.pipeline.delete_adapters
    attempts = []

    def delete_adapters(names):
        attempts.append(names)
        if len(attempts) <= times:
            raise RuntimeError("peft refused (stand-in)")
        return guarded(names)

    monkeypatch.setattr(runner.pipeline, "delete_adapters", delete_adapters)


@pytest.mark.parametrize("residency", ["staged", "resident"])
def test_an_adapter_whose_detach_failed_is_gone_before_the_next_run_samples(
    tmp_path, monkeypatch, residency
):
    pytest.importorskip("peft")
    from ltx25_studio.errors import GenerationError

    lora = _tiny_adapter(tmp_path)
    runner = _runner("text2video", residency)
    seen = _adapters_seen_by_the_denoise(monkeypatch)
    _detach_fails(runner, monkeypatch, times=1)
    with pytest.raises(GenerationError):
        _run(runner, tmp_path, "a", prompt="a first prompt", loras=(lora,))
    assert seen and all(names == {"user_lora_0"} for names in seen), seen

    seen.clear()
    result = _run(runner, tmp_path, "b", prompt="a second prompt")

    assert seen and not any(seen), f"the run was sampled through the earlier adapter: {seen}"
    assert result.record.adapters == ()


def test_an_adapter_kept_for_a_released_transformer_is_not_put_back_into_the_next_run(
    tmp_path, monkeypatch
):
    """The staged runner keeps a released transformer's adapters to put them back."""
    pytest.importorskip("peft")
    from ltx25_studio.errors import GenerationError

    lora = _tiny_adapter(tmp_path)
    runner = _runner("text2video", "staged")
    seen = _adapters_seen_by_the_denoise(monkeypatch)
    _detach_fails(runner, monkeypatch, times=1)
    with pytest.raises(GenerationError):
        _run(runner, tmp_path, "a", prompt="a first prompt", loras=(lora,))
    runner._weights.ensure_text_encoder()  # releases the transformer, keeping its adapter
    kept = runner._weights._adapters
    assert kept and [name for name, _config, _state in kept["adapters"]] == ["user_lora_0"]

    seen.clear()
    _run(runner, tmp_path, "b", prompt="a second prompt")

    assert seen and not any(seen), f"the kept adapter was put back into the run: {seen}"
    assert runner.held_adapters() == ()


def test_a_run_after_an_adapter_that_cannot_be_removed_is_refused_unsampled(
    tmp_path, monkeypatch
):
    pytest.importorskip("peft")
    from ltx25_studio.errors import GenerationError, LoRAError

    lora = _tiny_adapter(tmp_path)
    runner = _runner("text2video", "staged")
    seen = _adapters_seen_by_the_denoise(monkeypatch)
    _detach_fails(runner, monkeypatch, times=10**6)
    with pytest.raises(GenerationError):
        _run(runner, tmp_path, "a", prompt="a first prompt", loras=(lora,))
    seen.clear()

    with pytest.raises(LoRAError) as caught:
        _run(runner, tmp_path, "b", prompt="a second prompt")
    assert seen == [], "the refused run was sampled"
    assert type(caught.value).__name__ == "LoRALeftoverError", caught.value


def test_a_converting_load_promises_the_converted_copy_and_the_read_pages():
    from local_fakes import tiny_snapshot as tiny

    assert local_runtime._load_need_gb(10.0, 1.15, 2, 2) == pytest.approx(11.5)
    assert local_runtime._load_need_gb(10.0, 1.15, 4, 2) == pytest.approx(10 * 1.15 * 2 + 10)
    stored = local_runtime._stored_dtype_bytes(tiny(), "vae")
    assert stored in (2, 4)
    other = 4 if stored == 2 else 2
    native = local_runtime.preflight_plan(
        tiny(), width=SIZE, height=SIZE, num_frames=FRAMES, dtype_bytes=stored
    )
    converting = local_runtime.preflight_plan(
        tiny(), width=SIZE, height=SIZE, num_frames=FRAMES, dtype_bytes=other
    )
    by_phase = {step.phase: step for step in native}
    assert converting[0].need_gb > by_phase["load small set"].need_gb


# --------------------------------------------------------------------------
# review minors: local-runtime-7 (adapter bytes), -8 (freed on failure),
# -10 (the duration head's longest clip)
# --------------------------------------------------------------------------


@pytest.mark.parametrize("seconds, frames", [(3.7, 89), (2.7, 65), (4.36, 105), (5.0, 113)])
def test_the_auto_duration_estimate_is_the_longest_clip_the_head_can_return(seconds, frames):
    from ltx25_studio import constraints

    got = local_runtime.frames_for_estimate({"max_seconds": seconds}, {"frame_rate": 24.0})

    assert got == frames
    assert (
        got
        == constraints.duration_head_frame_range(
            min_seconds=1.0, max_seconds=seconds, frame_rate=24.0
        )[1]
    )


def _phases(monkeypatch):
    seen = []
    real = local_runtime._LocalWeights._preflight

    def spy(self, phase, need_gb):
        seen.append((phase, need_gb))
        return real(self, phase, need_gb)

    monkeypatch.setattr(local_runtime._LocalWeights, "_preflight", spy)
    return seen


@pytest.mark.parametrize("residency", ["staged", "resident"])
def test_attaching_an_adapter_is_preflighted_like_any_load(tmp_path, monkeypatch, residency):
    pytest.importorskip("peft")
    lora = _tiny_adapter(tmp_path)
    runner = _runner("text2video", residency)
    seen = _phases(monkeypatch)

    _run(runner, tmp_path, "a", prompt=PROMPT, loras=(lora,))

    phases = [phase for phase, _ in seen]
    ((phase, need),) = [entry for entry in seen if entry[0].startswith("attach LoRA")]
    assert phase == "attach LoRA look.safetensors"
    assert need >= Path(lora["path"]).stat().st_size / memory.GB
    assert phases.index(phase) < next(i for i, p in enumerate(phases) if p.startswith("denoise"))


def test_an_adapter_that_does_not_fit_is_refused_as_memory_not_as_a_bad_file(tmp_path, monkeypatch):
    pytest.importorskip("peft")
    lora = _tiny_adapter(tmp_path)
    runner = _runner("text2video", "staged")
    runner.ensure_transformer()
    monkeypatch.setenv("LTX25_MEMORY_LIMIT_GB", "1")

    with pytest.raises(memory.MemoryPreflightError) as caught:
        _run(runner, tmp_path, "a", prompt=PROMPT, loras=(lora,))
    assert "attach LoRA look.safetensors" in str(caught.value)


def test_reloading_the_transformer_promises_the_adapter_it_puts_back(tmp_path, monkeypatch):
    pytest.importorskip("peft")
    lora = _tiny_adapter(tmp_path)
    runner = _runner("text2video", "staged")
    runner.ensure_transformer()
    runner.pipeline.load_lora_weights(lora["path"], adapter_name="look")
    weights = runner._weights
    weights.ensure_text_encoder()  # releases the transformer, capturing the adapter
    adapter_gb = local_runtime._adapter_bytes(weights._adapters) / memory.GB
    assert adapter_gb > 0
    seen = _phases(monkeypatch)

    weights.ensure_transformer()

    ((_, need),) = [entry for entry in seen if entry[0] == "load transformer"]
    bare = local_runtime._load_need_gb(
        weights._gb["transformer"],
        memory.load_spike_factor("safetensors"),
        weights.dtype_bytes,
        local_runtime._stored_dtype_bytes(weights.snapshot_dir, "transformer"),
    )
    assert need == pytest.approx(bare + adapter_gb)


def _frees(monkeypatch):
    calls = []
    real = local_runtime._LocalWeights._free

    def spy(self):
        calls.append(self)
        return real(self)

    monkeypatch.setattr(local_runtime._LocalWeights, "_free", spy)
    return calls


def test_a_failed_load_empties_the_device_cache(monkeypatch):
    runner = _runner("text2video", "staged")
    frees = _frees(monkeypatch)

    def fail(*args, **kwargs):
        raise RuntimeError("MPS backend out of memory (stand-in)")

    monkeypatch.setattr(local_runtime, "load_transformer", fail)
    with pytest.raises(RuntimeError):
        runner.ensure_transformer()

    assert frees, "the failed load left the device cache as it was"


def test_a_failed_denoise_empties_the_device_cache(monkeypatch):
    torch = _torch()
    runner = _runner("text2video", "staged")
    frees = _frees(monkeypatch)
    reached = []
    real = runner._weights.preflight_denoise

    def preflight_then_watch(pipeline, call):
        real(pipeline, call)
        reached.append(True)
        frees.clear()  # only what happens from the denoise on counts

    monkeypatch.setattr(runner._weights, "preflight_denoise", preflight_then_watch)
    with pytest.raises(ValueError):
        runner(
            prompt=PROMPT,
            width=SIZE + 1,
            height=SIZE,
            num_frames=FRAMES,
            generator=torch.Generator().manual_seed(SEED),
            output_type="np",
        )

    assert reached, "the run failed before the denoise"
    assert frees, "the failed denoise left the device cache as it was"


def test_a_failed_resident_build_releases_what_it_loaded(monkeypatch):
    """The designed refusal: the transformer fits, the text encoder does not."""
    import weakref

    _torch()
    pytest.importorskip("diffusers")
    local_runtime.clear_local_cache()
    built = []
    real = local_runtime.load_transformer

    def load(*args, **kwargs):
        model = real(*args, **kwargs)
        built.append(weakref.ref(model))
        return model

    def refuse(*args, **kwargs):
        raise RuntimeError("the text encoder does not fit (stand-in)")

    monkeypatch.setattr(local_runtime, "load_transformer", load)
    monkeypatch.setattr(local_runtime, "load_text_encoder", refuse)
    frees = _frees(monkeypatch)
    try:
        with pytest.raises(RuntimeError, match="does not fit"):
            _runner("text2video", "resident")
    finally:
        local_runtime.clear_local_cache()
    gc.collect()

    assert frees
    assert built and built[0]() is None, "the failed build kept the transformer alive"


# --------------------------------------------------------------------------
# one stage graph: the SAME tests against the Space runner and the local runner
#
# The local runner is a pipelines.StageRunner that supplies residency through
# its one seam, so the decode policy (F07), stage 2 and its refusal (F08), the
# audio conditioning (F09), the clip variation (mode 04) and the run record (R)
# are one piece of code. Each behaviour runs through generate() on the tiny
# checkpoint, on the CPU, for the Space runner and the local runner staged and
# resident.
# --------------------------------------------------------------------------

RUNNERS = ("space", "staged", "resident")


@pytest.fixture(scope="module")
def composite(tmp_path_factory):
    """The tiny checkpoint plus tiny stage-2 models, as one snapshot directory."""
    _torch()
    pytest.importorskip("diffusers")
    from test_real_pipeline_tiny import load_smoke

    path, missing = load_smoke().composite_snapshot(
        tiny_snapshot(), tmp_path_factory.mktemp("composite") / "snapshot", fetch=False
    )
    if missing:
        pytest.skip(missing)
    return path


def _factory_for(kind, composite, monkeypatch):
    if kind == "space":
        from test_real_pipeline_tiny import load_smoke

        stack = load_smoke().tiny_stack(device="cpu")
        # The pre-dispatch decoder checks read the decoder's config from here.
        monkeypatch.setenv("LTX25_MODEL_SNAPSHOT_DIR", str(stack["snapshot"]))
        return lambda *, pipeline, **_: stack[pipeline]
    # The stage-2 parts resolve through preflight.component_dir.
    monkeypatch.setenv("LTX25_MODEL_SNAPSHOT_DIR", str(composite))

    def factory(*, pipeline, **_):
        runner = local_runtime.build_local_runner(
            kind=pipeline, device="cpu", dtype="float32", snapshot_dir=composite, residency=kind
        )
        install_tiny_audio_encode_shim(runner.pipeline.audio_vae)
        return runner

    return factory


def _through_generate(kind, composite, monkeypatch, tmp_path, mode, **fields):
    from test_real_pipeline_tiny import load_smoke

    from ltx25_studio import generate as generate_module

    media = tmp_path / "media"
    media.mkdir(exist_ok=True)
    request = dict(mode=mode, seed=SEED, width=SIZE, height=SIZE, num_frames=FRAMES)
    request.update(
        load_smoke()._media_for(
            mode, media, fields.get("width", SIZE), fields.get("num_frames", FRAMES)
        )
    )
    request.update(fields)
    return generate_module.generate(
        **request,
        pipeline_factory=_factory_for(kind, composite, monkeypatch),
        output_root=tmp_path / "out",
        retention_bytes=10**12,
    )


@pytest.fixture
def sigmas_seen(monkeypatch):
    """Per transformer call, on every runner: the video and the audio sigma."""
    _torch()
    pytest.importorskip("diffusers")
    from diffusers import LTX2VideoTransformer3DModel

    seen = []
    forward = LTX2VideoTransformer3DModel.forward

    def spy(self, *args, **kwargs):
        seen.append(
            (
                float(kwargs["sigma"].flatten()[0]) / 1000.0,
                float(kwargs["audio_sigma"].flatten()[0]) / 1000.0,
            )
        )
        return forward(self, *args, **kwargs)

    monkeypatch.setattr(LTX2VideoTransformer3DModel, "forward", spy)
    return seen


@pytest.mark.parametrize("kind", RUNNERS)
def test_auto_decodes_with_conv_off_cuda_on_every_runner(kind, composite, monkeypatch, tmp_path):
    result = _through_generate(
        kind, composite, monkeypatch, tmp_path, "text_to_video", prompt=PROMPT
    )

    record = result.record
    assert (record.decoder, record.stage_2) == ("conv", False)
    assert (record.width, record.height, record.frames) == (SIZE, SIZE, FRAMES)
    assert any("NVIDIA" in line for line in result.record.diagnostics), result.record.diagnostics
    assert record.device == "cpu", "the run's time is labelled by the device that ran it"


@pytest.mark.parametrize("kind", RUNNERS)
def test_an_explicit_diffusion_decode_runs_at_the_cpu_decoders_size_on_every_runner(
    kind, composite, monkeypatch, tmp_path
):
    result = _through_generate(
        kind,
        composite,
        monkeypatch,
        tmp_path,
        "text_to_audio_video",
        prompt=PROMPT,
        width=128,
        height=128,
        decoder="diffusion",
    )

    assert result.record.decoder == "diffusion"
    assert (result.record.width, result.record.height) == (128, 128)


@pytest.mark.parametrize("kind", RUNNERS)
def test_stage_2_runs_at_tiny_size_and_doubles_it_on_every_runner(
    kind, composite, monkeypatch, tmp_path, sigmas_seen
):
    from ltx25_studio import pipelines

    result = _through_generate(
        kind, composite, monkeypatch, tmp_path, "image_to_video", enable_stage_2=True
    )

    record = result.record
    assert (record.stage_2, record.decoder) == (True, "diffusion")
    assert (record.width, record.height) == (2 * SIZE, 2 * SIZE)
    video = [video for video, _audio in sigmas_seen]
    assert video == pytest.approx(
        list(pipelines.DISTILLED_SIGMA_VALUES) + list(pipelines.STAGE_2_DISTILLED_SIGMA_VALUES)
    )


@pytest.mark.parametrize("kind", RUNNERS)
def test_stage_2_at_a_real_size_is_refused_on_every_runner(kind, composite, monkeypatch):
    from ltx25_studio.device import StageTwoNeedsCudaError

    runner = _factory_for(kind, composite, monkeypatch)(pipeline="text2video")
    with pytest.raises(StageTwoNeedsCudaError):
        runner(enable_stage_2=True, prompt=PROMPT, width=704, height=480, num_frames=121)


@pytest.mark.parametrize("kind", RUNNERS)
def test_audio_to_video_holds_the_audio_frozen_on_every_runner(
    kind, composite, monkeypatch, tmp_path, sigmas_seen
):
    from ltx25_studio import pipelines

    result = _through_generate(kind, composite, monkeypatch, tmp_path, "audio_to_video")

    assert [audio for _video, audio in sigmas_seen] == [0.0] * len(sigmas_seen)
    assert [video for video, _audio in sigmas_seen] == pytest.approx(
        list(pipelines.DISTILLED_SIGMA_VALUES)
    )
    assert result.record.audio_level == 0.0


@pytest.mark.parametrize("kind", RUNNERS)
def test_audio_to_audio_varies_the_audio_at_its_level_on_every_runner(
    kind, composite, monkeypatch, tmp_path, sigmas_seen
):
    from ltx25_studio import audio_conditioning, pipelines

    result = _through_generate(
        kind, composite, monkeypatch, tmp_path, "audio_to_audio", noise_scale=0.8
    )

    level = 0.725
    assert [audio for _video, audio in sigmas_seen] == pytest.approx(
        audio_conditioning.audio_sigmas(pipelines.DISTILLED_SIGMA_VALUES, level)
    )
    record = result.record
    assert (record.audio_level, record.decoder, record.stage_2) == (level, "conv", False)
    assert "your audio was changed moderately." in result.warnings, result.warnings


@pytest.mark.parametrize("kind", RUNNERS)
def test_a_clip_variation_denoises_the_tail_from_its_level_on_every_runner(
    kind, composite, monkeypatch, tmp_path, sigmas_seen
):
    from ltx25_studio import audio_conditioning

    level = 0.725
    result = _through_generate(
        kind, composite, monkeypatch, tmp_path, "video_to_video", prompt=PROMPT, noise_scale=level
    )

    assert [video for video, _audio in sigmas_seen] == pytest.approx(
        audio_conditioning.sigma_tail(level)
    )
    assert result.record.video_level == level
    assert result.record.frames == FRAMES


def test_a_staged_stage_2_run_encodes_the_prompt_once_and_keeps_the_transformer(
    composite, monkeypatch, tmp_path
):
    """The seam swaps the prompt for embeddings per call; stage 2 is a cache hit."""
    factory = _factory_for("staged", composite, monkeypatch)
    loads = []
    for name in ("load_text_encoder", "load_transformer"):
        real = getattr(local_runtime, name)
        monkeypatch.setattr(
            local_runtime,
            name,
            lambda *a, _real=real, _name=name, **k: loads.append(_name) or _real(*a, **k),
        )
    from ltx25_studio import generate as generate_module

    runner = factory(pipeline="text2video")
    result = generate_module.generate(
        mode="text_to_video",
        prompt="a prompt only this test encodes",
        seed=SEED,
        width=SIZE,
        height=SIZE,
        num_frames=FRAMES,
        enable_stage_2=True,
        pipeline_factory=lambda **_: runner,
        output_root=tmp_path / "out",
        retention_bytes=10**12,
    )

    assert result.record.stage_2
    assert loads.count("load_text_encoder") == 1, loads
    assert loads.count("load_transformer") <= 1, loads
    phases = [entry["phase"] for entry in runner.timings]
    assert "denoise (stage 1)" in phases and "denoise (stage 2)" in phases


# --------------------------------------------------------------------------
# F73: after a release, the preflight judges a settled gauge
#
# The session's first run was refused at "load transformer" on a gauge read
# 10-400 ms after the text encoder was released (67.3 GB; 38.8 GB eight seconds
# later): the kernel un-wires freed MPS pages over 0.1-0.35 s. These run the
# real staged runner on the tiny checkpoint with the gauge scripted around the
# runner's own releases; the clock moves only when the preflight sleeps.
# --------------------------------------------------------------------------


class ScriptedGauge:
    """The committed gauge as the runner reads it.

    ``before`` until the runner frees memory; from each release on, ``after`` in
    order (the last one repeats). The limit is the Mac's 90 GB unless a test
    sets another, so the judgements are the same on every platform.
    """

    def __init__(self, monkeypatch, *, before, after):
        self.before = before
        self.after = list(after)
        self.since_release = None
        self.reads = 0
        self.frees = 0
        self.now = 0.0
        self.slept: list[float] = []
        real_free = local_runtime._LocalWeights._free

        def free(weights):
            real_free(weights)
            self.frees += 1
            self.since_release = 0

        monkeypatch.setattr(local_runtime._LocalWeights, "_free", free)
        monkeypatch.setattr(memory, "committed_gb", self.read)
        monkeypatch.setattr(memory, "_clock", lambda: self.now, raising=False)
        monkeypatch.setattr(memory, "_sleep", self.sleep, raising=False)
        # Earlier tests' clean-up released memory; nothing this test did has.
        monkeypatch.setattr(local_runtime, "_freed_since_reading", False, raising=False)
        monkeypatch.delenv("LTX25_MEMORY_SETTLE_SECONDS")
        monkeypatch.setenv("LTX25_MEMORY_LIMIT_GB", "90")

    def read(self, **_):
        self.reads += 1
        if self.since_release is None:
            return self.before
        value = self.after[min(self.since_release, len(self.after) - 1)]
        self.since_release += 1
        return value

    def sleep(self, seconds):
        self.slept.append(seconds)
        self.now += seconds

    def log(self, lines: list, taken: list):
        """A runner log that records, per preflight line, the readings and sleeps so far."""

        def log(line):
            lines.append(line)
            if line.startswith("preflight["):
                phase = line.split("]")[0].removeprefix("preflight[")
                taken.append((phase, self.reads, len(self.slept)))

        return log


def _per_judgement(taken):
    """``[(phase, readings, sleeps)]`` each judgement took."""
    out, reads, sleeps = [], 0, 0
    for phase, total_reads, total_sleeps in taken:
        out.append((phase, total_reads - reads, total_sleeps - sleeps))
        reads, sleeps = total_reads, total_sleeps
    return out


def _run_once(runner, prompt=PROMPT):
    torch = _torch()
    return runner(
        prompt=prompt,
        width=SIZE,
        height=SIZE,
        num_frames=FRAMES,
        generator=torch.Generator().manual_seed(SEED),
        output_type="np",
    )


def _line_index(lines, prefix):
    return next(i for i, line in enumerate(lines) if line.startswith(prefix))


def test_the_transformer_is_judged_on_the_settled_gauge_after_the_text_encoder_is_released(
    monkeypatch,
):
    """The session's refused run: over a 66 GB limit at the first reading, not once settled."""
    ScriptedGauge(monkeypatch, before=35.2, after=[67.3, 64.1, 51.2, 40.1, 38.8, 38.8])
    monkeypatch.setenv("LTX25_MEMORY_LIMIT_GB", "66")
    lines = []
    runner = _runner("text2video", "staged", log=lines.append)

    _run_once(runner)

    judged = _line_index(lines, "preflight[load transformer]")
    assert lines.index("released the text encoder") < judged - 1
    assert lines[judged - 1] == "memory settled in 0.25 s: 67.3 → 38.8 GB"
    assert lines[judged].startswith("preflight[load transformer]: committed 38.8 + need ")
    assert " <= 66.0 GB OK (headroom " in lines[judged]
    assert runner.pipeline.transformer is not None


@pytest.mark.parametrize("residency", ["staged", "resident"])
def test_only_a_judgement_after_a_release_reads_more_than_once_or_waits(monkeypatch, residency):
    gauge = ScriptedGauge(monkeypatch, before=35.2, after=[52.0, 40.0, 39.9])
    lines, taken = [], []
    runner = _runner("text2video", residency, log=gauge.log(lines, taken))

    _run_once(runner)

    denoise = f"denoise {SIZE}x{SIZE}x{FRAMES}"
    if residency == "resident":
        assert _per_judgement(taken) == [
            ("load small set", 1, 0),
            ("load transformer", 1, 0),
            ("load text encoder", 1, 0),
            (denoise, 1, 0),
        ]
        assert not any(line.startswith("memory settled") for line in lines)
    else:
        assert _per_judgement(taken) == [
            ("load small set", 1, 0),
            ("load text encoder", 1, 0),
            ("load transformer", 3, 2),  # after the text encoder's release
            (denoise, 1, 0),
        ]


def test_a_failed_step_settles_the_gauge_before_the_next_runs_first_reading(monkeypatch):
    ScriptedGauge(monkeypatch, before=35.2, after=[61.0, 48.0, 39.0, 38.9])
    lines = []
    runner = _runner("text2video", "staged", log=lines.append)
    real_load = local_runtime.load_transformer

    def fails(*args, **kwargs):
        raise RuntimeError("MPS backend out of memory (stand-in)")

    monkeypatch.setattr(local_runtime, "load_transformer", fails)
    with pytest.raises(RuntimeError, match="stand-in"):
        _run_once(runner)
    monkeypatch.setattr(local_runtime, "load_transformer", real_load)
    monkeypatch.setenv("LTX25_MEMORY_LIMIT_GB", "60")  # over it only before the gauge settles
    lines.clear()

    _run_once(runner)  # the prompt is cached, so the transformer's is the first reading

    judged = _line_index(lines, "preflight[")
    assert lines[judged].startswith("preflight[load transformer]: committed 38.9 + need ")
    assert lines[judged - 1] == "memory settled in 0.15 s: 61.0 → 38.9 GB"


def test_removing_an_adapter_frees_it_and_the_next_judgement_settles(tmp_path, monkeypatch):
    pytest.importorskip("peft")
    lora = _tiny_adapter(tmp_path)
    gauge = ScriptedGauge(monkeypatch, before=35.2, after=[44.0, 40.2, 40.1])
    lines = []
    runner = _runner("text2video", "staged", log=lines.append)
    _run(runner, tmp_path, "a", prompt=PROMPT, loras=(lora,))
    assert not getattr(runner.pipeline.transformer, "peft_config", None), "the adapter stayed"
    frees = gauge.frees
    lines.clear()

    _run(runner, tmp_path, "b", prompt=PROMPT)  # cached prompt, resident transformer

    judged = _line_index(lines, "preflight[")
    assert lines[judged].startswith(f"preflight[denoise {SIZE}x{SIZE}x{FRAMES}]")
    assert lines[judged - 1] == "memory settled in 0.10 s: 44.0 → 40.1 GB"
    assert gauge.frees == frees, "nothing was released in the second run before its judgement"


def test_zero_settle_seconds_judges_the_first_reading_as_before(monkeypatch):
    gauge = ScriptedGauge(monkeypatch, before=35.2, after=[67.3, 64.1, 51.2, 40.1, 38.8])
    monkeypatch.setenv("LTX25_MEMORY_LIMIT_GB", "66")
    monkeypatch.setenv("LTX25_MEMORY_SETTLE_SECONDS", "0")
    runner = _runner("text2video", "staged")

    with pytest.raises(memory.MemoryPreflightError) as caught:
        _run_once(runner)

    assert str(caught.value).startswith("Not enough memory for 'load transformer': 67.3 GB")
    assert gauge.slept == []
    assert runner.pipeline.transformer is None


@pytest.mark.skipif(sys.platform != "darwin", reason="the live gauge is vm_stat, on macOS")
def test_on_the_live_gauge_a_release_is_settled_without_really_sleeping(monkeypatch):
    clock, slept = [0.0], []

    def sleep(seconds):
        slept.append(seconds)
        clock[0] += seconds

    monkeypatch.setattr(memory, "_clock", lambda: clock[0], raising=False)
    monkeypatch.setattr(memory, "_sleep", sleep, raising=False)
    monkeypatch.setattr(local_runtime, "_freed_since_reading", False, raising=False)
    monkeypatch.delenv("LTX25_MEMORY_SETTLE_SECONDS")
    lines = []
    runner = _runner("text2video", "staged", log=lines.append)

    _run_once(runner)

    judged = _line_index(lines, "preflight[load transformer]")
    assert re.fullmatch(
        r"memory (settled in|still moving after) \d+\.\d\d s: \d+\.\d → \d+\.\d GB"
        r"(; judged on the last reading)?",
        lines[judged - 1],
    ), lines[judged - 1]
    assert slept and sum(slept) <= memory.DEFAULT_SETTLE_SECONDS + 1e-9