Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
#include <algorithm>
#include <cstdint>
#include <filesystem>
#include <fstream>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
// #include <absl/base/config.h>
#include <gsl/gsl>
#include <gtest/gtest.h>
 
#include "core/graph/constants.h"
#include "core/graph/onnx_protobuf.h"
#include "core/session/onnxruntime_cxx_api.h"
#include "core/session/onnxruntime_session_options_config_keys.h"
#include "core/session/onnxruntime_ep_device_ep_metadata_keys.h"
#include "nlohmann/json.hpp"
 
#include "test/autoep/ep_context_data_callbacks.h"
#include "test/autoep/test_autoep_utils.h"
#include "test/autoep/library/ep_context_data_utils.h"
#include "test/autoep/library/example_plugin_ep/ep_test_hooks.h"
#include "test/shared_lib/utils.h"
#include "test/util/include/api_asserts.h"
#include "test/util/include/asserts.h"
 
extern std::unique_ptr<Ort::Env> ort_env;
 
namespace onnxruntime {
namespace test {
 
namespace {
 
void SetEpContextDataReadFunc(Ort::SessionOptions& session_options, OrtReadNamedBufferFunc read_func, void* state) {
  ASSERT_NO_THROW(session_options.SetEpContextDataReadFunc(read_func, state));
}
 
void SetEpContextDataWriteFunc(Ort::ModelCompilationOptions& compile_options, OrtWriteNamedBufferFunc write_func,
                               void* state) {
  ASSERT_NO_THROW(compile_options.SetEpContextDataWriteFunc(write_func, state));
}
 
void LoadModelProtoFromFile(const ORTCHAR_T* model_file, ONNX_NAMESPACE::ModelProto& model_proto) {
  std::ifstream model_stream{std::basic_string<ORTCHAR_T>{model_file}, std::ios::binary};
  ASSERT_TRUE(model_stream.is_open());
  ASSERT_TRUE(model_proto.ParseFromIstream(&model_stream));
}
 
std::vector<const ONNX_NAMESPACE::NodeProto*> GetEpContextNodes(const ONNX_NAMESPACE::ModelProto& model_proto) {
  std::vector<const ONNX_NAMESPACE::NodeProto*> ep_context_nodes;
 
  for (const auto& node : model_proto.graph().node()) {
    if (node.domain() == kMSDomain && node.op_type() == "EPContext") {
      ep_context_nodes.push_back(&node);
    }
  }
 
  return ep_context_nodes;
}
 
const ONNX_NAMESPACE::AttributeProto* GetNodeAttribute(const ONNX_NAMESPACE::NodeProto& node,
                                                       std::string_view attribute_name) {
  for (const auto& attribute : node.attribute()) {
    if (attribute.name() == attribute_name) {
      return &attribute;
    }
  }
 
  return nullptr;
}
 
void RunMulModelWithPluginEp(const ORTCHAR_T* model_path, const Ort::SessionOptions& session_options) {
  Ort::Session session(*ort_env, model_path, session_options);
 
  // Create input
  Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
  std::vector<int64_t> shape = {3, 2};
  std::vector<float> input0_data(6, 2.0f);
  std::vector<Ort::Value> ort_inputs;
  std::vector<const char*> ort_input_names;
 
  ort_inputs.emplace_back(Ort::Value::CreateTensor<float>(
      memory_info, input0_data.data(), input0_data.size(), shape.data(), shape.size()));
  ort_input_names.push_back("X");
 
  // Run session and get outputs
  std::array<const char*, 1> output_names{"Y"};
  std::vector<Ort::Value> ort_outputs = session.Run(Ort::RunOptions{nullptr}, ort_input_names.data(), ort_inputs.data(),
                                                    ort_inputs.size(), output_names.data(), output_names.size());
 
  // Check expected output values
  Ort::Value& ort_output = ort_outputs[0];
  const float* output_data = ort_output.GetTensorData<float>();
  gsl::span<const float> output_span(output_data, 6);
  EXPECT_THAT(output_span, ::testing::ElementsAre(2, 4, 6, 8, 10, 12));
}
 
void RunMulModelWithPluginEp(const Ort::SessionOptions& session_options) {
  RunMulModelWithPluginEp(ORT_TSTR("testdata/mul_1.onnx"), session_options);
}
 
void RunCustomMulModelWithPluginEp(const Ort::SessionOptions& session_options) {
  Ort::Session session(*ort_env, ORT_TSTR("testdata/custom_mul.onnx"), session_options);
 
  // Create two inputs with same values
  Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
  std::vector<int64_t> shape = {3, 2};
  std::vector<float> input0_data{1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f};
  std::vector<Ort::Value> ort_inputs;
  std::vector<const char*> ort_input_names;
 
  ort_inputs.emplace_back(Ort::Value::CreateTensor<float>(
      memory_info, input0_data.data(), input0_data.size(), shape.data(), shape.size()));
  ort_inputs.emplace_back(Ort::Value::CreateTensor<float>(
      memory_info, input0_data.data(), input0_data.size(), shape.data(), shape.size()));
  ort_input_names.push_back("X");
  ort_input_names.push_back("W");
 
  // Run session and get outputs
  std::array<const char*, 1> output_names{"Y"};
  std::vector<Ort::Value> ort_outputs = session.Run(Ort::RunOptions{nullptr}, ort_input_names.data(), ort_inputs.data(),
                                                    ort_inputs.size(), output_names.data(), output_names.size());
 
  // Check expected output values
  Ort::Value& ort_output = ort_outputs[0];
  const float* output_data = ort_output.GetTensorData<float>();
  gsl::span<const float> output_span(output_data, 6);
  EXPECT_THAT(output_span, ::testing::ElementsAre(1, 4, 9, 16, 25, 36));
}
 
void RunSqueezeMulReluModel(const Ort::SessionOptions& session_options) {
  Ort::Session session(*ort_env, ORT_TSTR("testdata/squeeze_mul_relu.onnx"), session_options);
 
  // Create inputs
  Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
  std::array<int64_t, 3> a_shape = {3, 1, 2};
  std::array<int64_t, 2> b_shape = {3, 2};
 
  std::array<float, 6> a_data = {1.f, -2.f, 3.f, 4.f, -5.f, 6.f};
  std::array<float, 6> b_data = {2.f, 3.f, 4.f, -5.f, 6.f, 7.f};
 
  std::vector<Ort::Value> ort_inputs{};
  ort_inputs.emplace_back(
      Ort::Value::CreateTensor<float>(memory_info, a_data.data(), a_data.size(), a_shape.data(), a_shape.size()));
  ort_inputs.emplace_back(
      Ort::Value::CreateTensor<float>(memory_info, b_data.data(), b_data.size(), b_shape.data(), b_shape.size()));
 
  std::array ort_input_names{"A", "B"};
 
  // Run session and get outputs
  std::array output_names{"C"};
  std::vector<Ort::Value> ort_outputs = session.Run(Ort::RunOptions{nullptr}, ort_input_names.data(), ort_inputs.data(),
                                                    ort_inputs.size(), output_names.data(), output_names.size());
 
  // Check expected output values
  Ort::Value& ort_output = ort_outputs[0];
  const float* output_data = ort_output.GetTensorData<float>();
  gsl::span<const float> output_span(output_data, 6);
  EXPECT_THAT(output_span, ::testing::ElementsAre(4, 0, 24, 0, 0, 84));
}
 
void RunSubMulSubModel(const Ort::SessionOptions& session_options) {
  // This model has Sub -> Mul -> Sub: (A - B) * B - A
  // The example plugin EP supports all ops.
  Ort::Session session(*ort_env, ORT_TSTR("testdata/sub_mul_sub.onnx"), session_options);
 
  // Create inputs
  Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
  std::vector<int64_t> shape = {3, 2};
 
  std::vector<float> a_data{1, 2, 3, 4, 5, 6};
  std::vector<float> b_data{2, 3, 4, 5, 6, 7};
 
  std::vector<Ort::Value> ort_inputs{};
  ort_inputs.emplace_back(
      Ort::Value::CreateTensor<float>(memory_info, a_data.data(), a_data.size(), shape.data(), shape.size()));
  ort_inputs.emplace_back(
      Ort::Value::CreateTensor<float>(memory_info, b_data.data(), b_data.size(), shape.data(), shape.size()));
 
  std::array ort_input_names{"A", "B"};
 
  // Run session and get outputs
  std::array output_names{"C"};
  std::vector<Ort::Value> ort_outputs = session.Run(Ort::RunOptions{nullptr}, ort_input_names.data(), ort_inputs.data(),
                                                    ort_inputs.size(), output_names.data(), output_names.size());
 
  // Check expected output values
  Ort::Value& ort_output = ort_outputs[0];
  const float* output_data = ort_output.GetTensorData<float>();
  gsl::span<const float> output_span(output_data, 6);
  EXPECT_THAT(output_span, ::testing::ElementsAre(-3, -5, -7, -9, -11, -13));
}
 
void RunIfMulModel(const Ort::SessionOptions& session_options, bool if_condition) {
  // Model graph does the following computation:
  // if (A) { C = B * 2.0; }
  // else { C = B * 3; }
  Ort::Session session(*ort_env, ORT_TSTR("testdata/if_mul.onnx"), session_options);
 
  // Create inputs
  Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
  std::array<int64_t, 1> a_shape = {1};
  std::array<int64_t, 2> b_shape = {3, 2};
 
  std::array<bool, 1> a_data = {if_condition};
  std::array<float, 6> b_data = {2.f, 3.f, 4.f, -5.f, 6.f, 7.f};
 
  std::vector<Ort::Value> ort_inputs{};
  ort_inputs.emplace_back(
      Ort::Value::CreateTensor<bool>(memory_info, a_data.data(), a_data.size(), a_shape.data(), a_shape.size()));
  ort_inputs.emplace_back(
      Ort::Value::CreateTensor<float>(memory_info, b_data.data(), b_data.size(), b_shape.data(), b_shape.size()));
 
  std::array ort_input_names{"A", "B"};
 
  // Run session and get outputs
  std::array output_names{"C"};
  std::vector<Ort::Value> ort_outputs = session.Run(Ort::RunOptions{nullptr}, ort_input_names.data(), ort_inputs.data(),
                                                    ort_inputs.size(), output_names.data(), output_names.size());
 
  // Check expected output values
  Ort::Value& ort_output = ort_outputs[0];
  const float* output_data = ort_output.GetTensorData<float>();
  gsl::span<const float> output_span(output_data, 6);
 
  if (if_condition) {
    // Expect that model multiplies input B elements by 2.0.
    EXPECT_THAT(output_span, ::testing::ElementsAre(4.f, 6.f, 8.f, -10.f, 12.f, 14.f));
  } else {
    // Expect that model multiplies input B elements by 3.0.
    EXPECT_THAT(output_span, ::testing::ElementsAre(6.f, 9.f, 12.f, -15.f, 18.f, 21.f));
  }
}
 
void RunLoopSubOneModel(const Ort::SessionOptions& session_options) {
  // Model graph does the following computation:
  // x = A
  // for (int i = 0; i < MAX_ITERS; i++) {
  //   y = x - 1.0;
  //   user_val = x - 1.0;
  //   x = y;
  // }
  // C = x;
  // D = user_val (will be concatenated result of each iteration)
  Ort::Session session(*ort_env, ORT_TSTR("testdata/loop_sub_one.onnx"), session_options);
 
  // Create inputs
  Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
  std::array<int64_t, 1> max_iters_shape = {1};
  std::array<int64_t, 1> a_shape = {1};
 
  std::array<int64_t, 1> max_iters_data = {3};
  std::array<float, 1> a_data = {10.0f};
 
  std::vector<Ort::Value> ort_inputs{};
  ort_inputs.emplace_back(
      Ort::Value::CreateTensor<int64_t>(memory_info, max_iters_data.data(), max_iters_data.size(),
                                        max_iters_shape.data(), max_iters_shape.size()));
  ort_inputs.emplace_back(
      Ort::Value::CreateTensor<float>(memory_info, a_data.data(), a_data.size(), a_shape.data(), a_shape.size()));
 
  std::array ort_input_names{"MAX_ITERS", "A"};
 
  // Run session and get outputs
  std::array output_names{"C", "D"};
  std::vector<Ort::Value> ort_outputs = session.Run(Ort::RunOptions{nullptr}, ort_input_names.data(), ort_inputs.data(),
                                                    ort_inputs.size(), output_names.data(), output_names.size());
 
  // Check expected output values
  // Expect that input elems are all subtracted by 3 (1 each iteration).
  gsl::span<const float> output_c_span(ort_outputs[0].GetTensorData<float>(), 1);
  EXPECT_THAT(output_c_span, ::testing::ElementsAre(7.f));
 
  gsl::span<const float> output_d_span(ort_outputs[1].GetTensorData<float>(), 3);
  EXPECT_THAT(output_d_span, ::testing::ElementsAre(9.f, 8.f, 7.f));
}
 
void RunScanMulModel(const Ort::SessionOptions& session_options) {
  Ort::Session session(*ort_env, ORT_TSTR("testdata/scan_mul.onnx"), session_options);
 
  // Create inputs
  Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
  std::array<int64_t, 2> x_shape = {3, 3};
  std::array<float, 9> x_data = {1.f, 2.f, 3.f, 10.f, 20.f, 30.f, 100.f, 200.f, 300.f};
 
  std::vector<Ort::Value> ort_inputs{};
  ort_inputs.emplace_back(
      Ort::Value::CreateTensor<float>(memory_info, x_data.data(), x_data.size(), x_shape.data(), x_shape.size()));
 
  std::array ort_input_names{"X"};
 
  // Run session and get outputs
  std::array output_names{"Y"};
  std::vector<Ort::Value> ort_outputs = session.Run(Ort::RunOptions{nullptr}, ort_input_names.data(), ort_inputs.data(),
                                                    ort_inputs.size(), output_names.data(), output_names.size());
 
  // Check expected output values
  gsl::span<const float> output_span(ort_outputs[0].GetTensorData<float>(), 9);
  EXPECT_THAT(output_span, ::testing::ElementsAre(2.f, 4.f, 6.f, 20.f, 40.f, 60.f, 200.f, 400.f, 600.f));
}
 
using CheckEpNodeAssignmentFunc = std::function<void(const Ort::Session& session)>;
 
void RunAddMulAddModel(const Ort::SessionOptions& session_options,
                       CheckEpNodeAssignmentFunc check_ep_node_assignment_func = {}) {
  // This model has Add -> Mul -> Add. The example plugin EP supports Mul but not Add.
  Ort::Session session(*ort_env, ORT_TSTR("testdata/add_mul_add.onnx"), session_options);
 
  if (check_ep_node_assignment_func) {
    ASSERT_NO_FATAL_FAILURE(check_ep_node_assignment_func(session));
  }
 
  // Create inputs
  Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
  std::vector<int64_t> shape = {3, 2};
 
  std::vector<float> a_data{1, 2, 3, 4, 5, 6};
  std::vector<float> b_data{2, 3, 4, 5, 6, 7};
 
  std::vector<Ort::Value> ort_inputs{};
  ort_inputs.emplace_back(
      Ort::Value::CreateTensor<float>(memory_info, a_data.data(), a_data.size(), shape.data(), shape.size()));
  ort_inputs.emplace_back(
      Ort::Value::CreateTensor<float>(memory_info, b_data.data(), b_data.size(), shape.data(), shape.size()));
 
  std::array ort_input_names{"A", "B"};
 
  // Run session and get outputs
  std::array output_names{"C"};
  std::vector<Ort::Value> ort_outputs = session.Run(Ort::RunOptions{nullptr}, ort_input_names.data(), ort_inputs.data(),
                                                    ort_inputs.size(), output_names.data(), output_names.size());
 
  // Check expected output values
  Ort::Value& ort_output = ort_outputs[0];
  const float* output_data = ort_output.GetTensorData<float>();
  gsl::span<const float> output_span(output_data, 6);
  EXPECT_THAT(output_span, ::testing::ElementsAre(7, 17, 31, 49, 71, 97));
}
 
void RunMulModelWithPluginEpUsingIOBinding(const Ort::SessionOptions& session_options) {
  Ort::Session session(*ort_env, ORT_TSTR("testdata/mul_1.onnx"), session_options);
 
  // Create input
  Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
  std::vector<int64_t> shape = {3, 2};
  std::vector<float> input0_data(6, 2.0f);
  std::vector<Ort::Value> ort_inputs;
 
  ort_inputs.emplace_back(Ort::Value::CreateTensor<float>(
      memory_info, input0_data.data(), input0_data.size(), shape.data(), shape.size()));
 
  Ort::IoBinding io_binding(session);
  io_binding.BindInput("X", ort_inputs[0]);
  io_binding.BindOutput("Y", memory_info);
 
  Ort::RunOptions run_options;
 
  // Run session and get outputs
  session.Run(run_options, io_binding);
  io_binding.SynchronizeOutputs();
  std::vector<Ort::Value> ort_outputs = io_binding.GetOutputValues();
 
  // Check expected output values
  Ort::Value& ort_output = ort_outputs[0];
  const float* output_data = ort_output.GetTensorData<float>();
  gsl::span<const float> output_span(output_data, 6);
  EXPECT_THAT(output_span, ::testing::ElementsAre(2, 4, 6, 8, 10, 12));
}
 
enum class PreallocatedOutputBinding { kRunFetches,
                                       kIoBinding };
 
// Runs mul_1.onnx with a caller-allocated output buffer, supplied either directly to Run() or via
// IoBinding. Both paths must land the result in `output_data` itself, not a copy.
void RunMulModelWithPluginEpUsingPreallocatedOutput(const Ort::SessionOptions& session_options,
                                                    PreallocatedOutputBinding binding) {
  Ort::Session session(*ort_env, ORT_TSTR("testdata/mul_1.onnx"), session_options);
 
  Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
  const auto output_memory_info = session.GetEpDeviceForOutputs().at(0).GetMemoryInfo(OrtDeviceMemoryType_DEFAULT);
  std::vector<int64_t> shape = {3, 2};
  std::vector<float> input0_data(6, 2.0f);
  std::vector<float> output_data(6, -1.0f);
  Ort::Value input = Ort::Value::CreateTensor<float>(
      memory_info, input0_data.data(), input0_data.size(), shape.data(), shape.size());
  Ort::Value output = Ort::Value::CreateTensor<float>(
      output_memory_info, output_data.data(), output_data.size(), shape.data(), shape.size());
 
  if (binding == PreallocatedOutputBinding::kRunFetches) {
    const char* input_names[] = {"X"};
    const char* output_names[] = {"Y"};
    session.Run(Ort::RunOptions{nullptr}, input_names, &input, 1, output_names, &output, 1);
  } else {
    Ort::IoBinding io_binding(session);
    io_binding.BindInput("X", input);
    io_binding.BindOutput("Y", output);
    session.Run(Ort::RunOptions{nullptr}, io_binding);
  }
 
  // The EP wrote through the caller's buffer rather than into an ORT-allocated one.
  EXPECT_EQ(output.GetTensorMutableData<float>(), output_data.data());
  EXPECT_THAT(output_data, ::testing::ElementsAre(2, 4, 6, 8, 10, 12));
}
 
// Builds a minimal ONNX model bytes with a single FP16 HardSigmoid node.
// Graph: X[1,4 float16] -> HardSigmoid -> Y[1,4 float16]
// HardSigmoid is used because it has NO MLFloat16 CPU kernel on any build config,
// ensuring the node remains unassigned during partitioning and exercises the
// InsertCastTransformer callback path.
std::string BuildFp16HardSigmoidModelBytes() {
  ONNX_NAMESPACE::ModelProto model;
  model.set_ir_version(ONNX_NAMESPACE::Version::IR_VERSION);
  auto* opset = model.add_opset_import();
  opset->set_domain("");
  opset->set_version(14);
 
  ONNX_NAMESPACE::GraphProto* graph = model.mutable_graph();
  graph->set_name("fp16_hardsigmoid");
 
  auto add_fp16_value_info = [](ONNX_NAMESPACE::GraphProto* g, bool is_input,
                                const std::string& name) {
    auto* v = is_input ? g->add_input() : g->add_output();
    v->set_name(name);
    auto* t = v->mutable_type()->mutable_tensor_type();
    t->set_elem_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT16);
    t->mutable_shape()->add_dim()->set_dim_value(1);
    t->mutable_shape()->add_dim()->set_dim_value(4);
  };
 
  add_fp16_value_info(graph, /*is_input=*/true, "X");
  add_fp16_value_info(graph, /*is_input=*/false, "Y");
 
  auto* node = graph->add_node();
  node->set_name("hardsigmoid_0");
  node->set_op_type("HardSigmoid");
  node->set_domain("");
  node->add_input("X");
  node->add_output("Y");
 
  std::string bytes;
  EXPECT_TRUE(model.SerializeToString(&bytes)) << "Failed to serialize FP16 HardSigmoid ONNX model";
  return bytes;
}
 
// Builds a minimal ONNX model with zero graph inputs: two float initializers fed into a single Mul node.
// Graph: A[3,2 float] * B[3,2 float] -> Y[3,2 float]
// Used to test EPContext generation for models with no external inputs.
std::string BuildZeroInputMulModelBytes() {
  ONNX_NAMESPACE::ModelProto model;
  model.set_ir_version(ONNX_NAMESPACE::Version::IR_VERSION);
  auto* opset = model.add_opset_import();
  opset->set_domain("");
  opset->set_version(18);
 
  ONNX_NAMESPACE::GraphProto* graph = model.mutable_graph();
  graph->set_name("zero_input_mul");
 
  // No graph inputs.
 
  // Graph output: Y [3, 2] float
  auto* output = graph->add_output();
  output->set_name("Y");
  auto* out_type = output->mutable_type()->mutable_tensor_type();
  out_type->set_elem_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT);
  out_type->mutable_shape()->add_dim()->set_dim_value(3);
  out_type->mutable_shape()->add_dim()->set_dim_value(2);
 
  // Initializer A: [3, 2] float, values = {1, 2, 3, 4, 5, 6}
  auto* init_a = graph->add_initializer();
  init_a->set_name("A");
  init_a->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT);
  init_a->add_dims(3);
  init_a->add_dims(2);
  for (float v : {1.f, 2.f, 3.f, 4.f, 5.f, 6.f}) {
    init_a->add_float_data(v);
  }
 
  // Initializer B: [3, 2] float, values = {2, 3, 4, 5, 6, 7}
  auto* init_b = graph->add_initializer();
  init_b->set_name("B");
  init_b->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT);
  init_b->add_dims(3);
  init_b->add_dims(2);
  for (float v : {2.f, 3.f, 4.f, 5.f, 6.f, 7.f}) {
    init_b->add_float_data(v);
  }
 
  // Mul node: Y = A * B
  auto* node = graph->add_node();
  node->set_name("mul_0");
  node->set_op_type("Mul");
  node->set_domain("");
  node->add_input("A");
  node->add_input("B");
  node->add_output("Y");
 
  std::string bytes;
  EXPECT_TRUE(model.SerializeToString(&bytes)) << "Failed to serialize zero-input Mul ONNX model";
  return bytes;
}
 
}  // namespace
 
// Creates a session with the example plugin EP and runs a model with a single Mul node.
// Uses AppendExecutionProvider_V2 to append the example plugin EP to the session.
TEST(OrtEpLibrary, PluginEp_AppendV2_MulInference) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  // Create session with example plugin EP
  Ort::SessionOptions session_options;
  std::unordered_map<std::string, std::string> ep_options;
  session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
  RunMulModelWithPluginEp(session_options);
}
 
TEST(OrtEpLibrary, PluginEp_NullSessionAllocatorUsesDefaultCpuAllocator) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  Ort::SessionOptions session_options;
  session_options.AddConfigEntry("ep.example.use_default_cpu_allocator", "1");
  std::unordered_map<std::string, std::string> ep_options;
  session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
  RunMulModelWithPluginEp(session_options);
}
 
// Registers the example EP, appends it to session options, and loads its test hooks.
static void SetUpPreallocatedOutputTest(RegisteredEpDeviceUniquePtr& example_ep,
                                        Ort::SessionOptions& session_options,
                                        Utils::LoadExampleEpHooksPtr& example_ep_hooks) {
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  std::unordered_map<std::string, std::string> ep_options;
  session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
  ASSERT_NO_FATAL_FAILURE(Utils::LoadExampleEpHooks(Utils::example_ep_info, example_ep_hooks));
  ASSERT_NE(example_ep_hooks->reset_preallocated_output_query, nullptr);
  ASSERT_NE(example_ep_hooks->get_preallocated_output_query_result, nullptr);
  ASSERT_NE(example_ep_hooks->get_preallocated_output_bad_index_rejected, nullptr);
  example_ep_hooks->reset_preallocated_output_query();
}
 
TEST(OrtEpLibrary, PluginEp_KernelContextPreallocatedOutput_Run) {
  RegisteredEpDeviceUniquePtr example_ep;
  Ort::SessionOptions session_options;
  Utils::LoadExampleEpHooksPtr example_ep_hooks;
  ASSERT_NO_FATAL_FAILURE(SetUpPreallocatedOutputTest(example_ep, session_options, example_ep_hooks));
 
  ASSERT_NO_FATAL_FAILURE(
      RunMulModelWithPluginEpUsingPreallocatedOutput(session_options, PreallocatedOutputBinding::kRunFetches));
  ASSERT_EQ(example_ep_hooks->get_preallocated_output_query_result(), 1);
  // Out-of-range output index rejected without disturbing the out parameter.
  ASSERT_EQ(example_ep_hooks->get_preallocated_output_bad_index_rejected(), 1);
}
 
TEST(OrtEpLibrary, PluginEp_KernelContextPreallocatedOutput_IoBinding) {
  RegisteredEpDeviceUniquePtr example_ep;
  Ort::SessionOptions session_options;
  Utils::LoadExampleEpHooksPtr example_ep_hooks;
  ASSERT_NO_FATAL_FAILURE(SetUpPreallocatedOutputTest(example_ep, session_options, example_ep_hooks));
 
  ASSERT_NO_FATAL_FAILURE(
      RunMulModelWithPluginEpUsingPreallocatedOutput(session_options, PreallocatedOutputBinding::kIoBinding));
  ASSERT_EQ(example_ep_hooks->get_preallocated_output_query_result(), 1);
  ASSERT_EQ(example_ep_hooks->get_preallocated_output_bad_index_rejected(), 1);
}
 
TEST(OrtEpLibrary, PluginEp_KernelContextPreallocatedOutput_NotPreallocated) {
  RegisteredEpDeviceUniquePtr example_ep;
  Ort::SessionOptions session_options;
  Utils::LoadExampleEpHooksPtr example_ep_hooks;
  ASSERT_NO_FATAL_FAILURE(SetUpPreallocatedOutputTest(example_ep, session_options, example_ep_hooks));
 
  ASSERT_NO_FATAL_FAILURE(RunMulModelWithPluginEp(session_options));
  ASSERT_EQ(example_ep_hooks->get_preallocated_output_query_result(), 0);
 
  example_ep_hooks->reset_preallocated_output_query();
  ASSERT_NO_FATAL_FAILURE(RunMulModelWithPluginEpUsingIOBinding(session_options));
  ASSERT_EQ(example_ep_hooks->get_preallocated_output_query_result(), 0);
}
 
// Creates a session with the example plugin EP and runs a model with a single Mul node.
// Uses the PREFER_CPU policy to append the example plugin EP to the session.
TEST(OrtEpLibrary, PluginEp_PreferCpu_MulInference) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
 
  {
    // PREFER_CPU pick our example EP over ORT CPU EP. TODO: Actually assert this.
    Ort::SessionOptions session_options;
    session_options.SetEpSelectionPolicy(OrtExecutionProviderDevicePolicy_PREFER_CPU);
    RunMulModelWithPluginEp(session_options);
  }
}
 
TEST(OrtEpLibrary, PluginEp_AppendV2_PartiallySupportedModelInference) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  // Create session with example plugin EP
  Ort::SessionOptions session_options;
  std::unordered_map<std::string, std::string> ep_options;
 
  // Create session that enables recording of EP-graph assignment info
  session_options.AddConfigEntry(kOrtSessionOptionsRecordEpGraphAssignmentInfo, "1");
  session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
  // Function that checks the ep graph/node assignment (Mul on plugin EP, others on CPU EP).
  // Model has 3 subgraphs (in no particular order):
  // - Subgraph 1: Add assigned to CPU EP.
  // - Subgraph 2: Mul assigned to plugin EP.
  // - Subgraph 3: Add assigned to CPU EP.
  auto check_ep_node_assignment = [](const Ort::Session& session) -> void {
    std::vector<Ort::ConstEpAssignedSubgraph> ep_subgraphs = session.GetEpGraphAssignmentInfo();
    ASSERT_EQ(ep_subgraphs.size(), 3);
 
    for (Ort::ConstEpAssignedSubgraph ep_subgraph : ep_subgraphs) {
      std::string ep_name = ep_subgraph.GetEpName();
      ASSERT_TRUE(ep_name == Utils::example_ep_info.ep_name || ep_name == kCpuExecutionProvider);
 
      const std::vector<Ort::ConstEpAssignedNode> ep_nodes = ep_subgraph.GetNodes();
 
      ASSERT_GE(ep_nodes.size(), 1);  // All of these subgraphs just have one node.
      std::string domain = ep_nodes[0].GetDomain();
      std::string op_type = ep_nodes[0].GetOperatorType();
      std::string node_name = ep_nodes[0].GetName();
 
      ASSERT_EQ(domain, kOnnxDomain);  // All node ops should have the ONNX domain
 
      // Check that CPU EP has the Adds and that the example EP has the Mul.
      if (ep_name == kCpuExecutionProvider) {
        ASSERT_EQ(op_type, "Add");
        ASSERT_TRUE(node_name == "add_0" || node_name == "add_1");
      } else {
        ASSERT_TRUE(ep_name == Utils::example_ep_info.ep_name);
        ASSERT_EQ(op_type, "Mul");
        ASSERT_EQ(node_name, "mul_0");
      }
    }
  };
 
  RunAddMulAddModel(session_options, check_ep_node_assignment);
}
 
// Verifies that GetEpGraphAssignmentInfo() correctly captures the FP16 HardSigmoid node being
// assigned to the CPU EP by InsertCastTransformer.
//
// During graph partitioning (step 4 in TransformGraph), the FP16 assigned node is not claimed by
// any EP (the example EP only supports FP32 Mul; the CPU EP has no FP16 HardSigmoid kernel), so
// on_partition_assignment_fn is never called at that stage.
//
// InsertCastTransformer (step 6) then converts the FP16 HardSigmoid: it inserts Cast(FP16->FP32)
// before the node, assigns the HardSigmoid to the CPU EP, and inserts Cast(FP32->FP16) after.
// InsertCastTransformer now invokes on_partition_assignment_fn when it assigns the HardSigmoid to
// CPU, so the node must appear in GetEpGraphAssignmentInfo().
TEST(OrtEpLibrary, PluginEp_AppendV2_Fp16HardSigmoid_EpGraphAssignmentInfo) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  Ort::SessionOptions session_options;
  std::unordered_map<std::string, std::string> ep_options;
 
  // Enable recording of EP-graph assignment info.
  session_options.AddConfigEntry(kOrtSessionOptionsRecordEpGraphAssignmentInfo, "1");
  session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
  const std::string model_bytes = BuildFp16HardSigmoidModelBytes();
  Ort::Session session(*ort_env, model_bytes.data(), model_bytes.size(), session_options);
 
  // InsertCastTransformer assigns the HardSigmoid to CPU EP and fires the callback, so there must
  // be exactly one subgraph entry: the HardSigmoid node on the CPU EP.
  std::vector<Ort::ConstEpAssignedSubgraph> ep_subgraphs = session.GetEpGraphAssignmentInfo();
  ASSERT_EQ(ep_subgraphs.size(), 1u)
      << "Expected exactly one EP subgraph (HardSigmoid on CPU EP), got " << ep_subgraphs.size();
 
  std::string ep_name = ep_subgraphs[0].GetEpName();
  ASSERT_EQ(ep_name, kCpuExecutionProvider)
      << "Expected HardSigmoid to be assigned to CPU EP, got: " << ep_name;
 
  const std::vector<Ort::ConstEpAssignedNode> ep_nodes = ep_subgraphs[0].GetNodes();
  ASSERT_EQ(ep_nodes.size(), 1u) << "Expected exactly one node in the CPU EP subgraph";
  ASSERT_EQ(ep_nodes[0].GetOperatorType(), std::string("HardSigmoid"));
  ASSERT_EQ(ep_nodes[0].GetName(), std::string("hardsigmoid_0"));
}
 
// Generate an EPContext model with a plugin EP.
// This test uses the OrtCompileApi but could also be done by setting the appropriate session option configs.
TEST(OrtEpLibrary, PluginEp_GenEpContextModel) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  {
    const ORTCHAR_T* input_model_file = ORT_TSTR("testdata/mul_1.onnx");
    const ORTCHAR_T* output_model_file = ORT_TSTR("plugin_ep_mul_1_ctx.onnx");
    std::filesystem::remove(output_model_file);
 
    // Create session with example plugin EP
    Ort::SessionOptions session_options;
    std::unordered_map<std::string, std::string> ep_options;
 
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    // Create model compilation options from the session options.
    Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
    compile_options.SetFlags(OrtCompileApiFlags_ERROR_IF_NO_NODES_COMPILED);
    compile_options.SetInputModelPath(input_model_file);
    compile_options.SetOutputModelPath(output_model_file);
 
    // Compile the model.
    ASSERT_CXX_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
    // Make sure the compiled model was generated.
    ASSERT_TRUE(std::filesystem::exists(output_model_file));
  }
}
 
TEST(OrtEpLibrary, PluginEp_ExternalInitializerBufferIsPublishedOnlyAfterCompileSucceeds) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::SessionOptions session_options;
  const std::unordered_map<std::string, std::string> ep_options;
  session_options.AppendExecutionProvider_V2(*ort_env, {Ort::ConstEpDevice(example_ep.get())}, ep_options);
 
  ONNX_NAMESPACE::ModelProto model;
  ASSERT_NO_FATAL_FAILURE(LoadModelProtoFromFile(ORT_TSTR("testdata/mul_1.onnx"), model));
  auto& graph = *model.mutable_graph();
  ASSERT_EQ(graph.node_size(), 1);
  const std::string output_name = graph.node(0).output(0);
  graph.mutable_node(0)->set_output(0, "mul_intermediate");
  auto& bias = *graph.add_initializer();
  bias.set_name("bias");
  bias.set_data_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT);
  bias.add_float_data(1.0f);
  auto& add = *graph.add_node();
  add.set_name("cpu_add");
  add.set_op_type("Add");
  add.add_input("mul_intermediate");
  add.add_input("bias");
  add.add_output(output_name);
  const std::string model_bytes = model.SerializeAsString();
 
  Ort::AllocatorWithDefaultOptions allocator;
  char sentinel;
  void* external_buffer = &sentinel;
  size_t external_size = 123;
  auto cleanup = gsl::finally([&]() {
    if (external_buffer != &sentinel) allocator.Free(external_buffer);
  });
  struct WriteState {
    std::string model_bytes;
    bool fail = true;
  } write_state;
  Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
  compile_options.SetFlags(OrtCompileApiFlags_ERROR_IF_NO_NODES_COMPILED);
  compile_options.SetInputModelFromBuffer(model_bytes.data(), model_bytes.size());
  compile_options.SetGraphOptimizationLevel(ORT_DISABLE_ALL);
  compile_options.SetEpContextEmbedMode(true);
  compile_options.SetOutputModelExternalInitializersBuffer(ORT_TSTR("weights.bin"), 0, allocator,
                                                           &external_buffer, &external_size);
  compile_options.SetOutputModelWriteFunc(
      [](void* state, const void* buffer, size_t size) -> OrtStatus* {
        auto& output = *static_cast<WriteState*>(state);
        output.model_bytes.append(static_cast<const char*>(buffer), size);
        return output.fail ? Ort::GetApi().CreateStatus(ORT_FAIL, "Intentional model write failure") : nullptr;
      },
      &write_state);
  const Ort::Status failed_status = Ort::CompileModel(*ort_env, compile_options);
  EXPECT_FALSE(failed_status.IsOK());
  EXPECT_EQ(external_buffer, &sentinel);
  EXPECT_EQ(external_size, 123u);
  ASSERT_FALSE(write_state.model_bytes.empty());
  ONNX_NAMESPACE::ModelProto compiled;
  ASSERT_TRUE(compiled.ParseFromString(write_state.model_bytes));
  ASSERT_EQ(GetEpContextNodes(compiled).size(), 1u);
  ASSERT_EQ(compiled.graph().initializer_size(), 1);
  EXPECT_EQ(compiled.graph().initializer(0).data_location(), ONNX_NAMESPACE::TensorProto_DataLocation_EXTERNAL);
 
  // Reusing the same options must not retain the failed call's temporary output locations.
  write_state.fail = false;
  write_state.model_bytes.clear();
  ASSERT_CXX_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
  EXPECT_NE(external_buffer, &sentinel);
  EXPECT_NE(external_buffer, nullptr);
  EXPECT_EQ(external_size, sizeof(float));
}
 
TEST(OrtEpLibrary, PluginEp_GenEpContextModel_EmbedModeDoesNotUseCallbacks) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  const ORTCHAR_T* input_model_file = ORT_TSTR("testdata/mul_1.onnx");
  const ORTCHAR_T* output_model_file = ORT_TSTR("plugin_ep_mul_1_embedded_ctx.onnx");
  std::filesystem::remove(output_model_file);
  auto cleanup = gsl::finally([&]() { std::filesystem::remove(output_model_file); });
 
  EpContextDataCallbackState write_callback_state;
  EpContextDataCallbackState compile_read_callback_state;
  {
    Ort::SessionOptions session_options;
    session_options.AddConfigEntry(kExampleEpTestEpContextDataSupport, "0");
    ASSERT_NO_FATAL_FAILURE(
        SetEpContextDataReadFunc(session_options, LoadEpContextDataCallback, &compile_read_callback_state));
 
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
    compile_options.SetFlags(OrtCompileApiFlags_ERROR_IF_NO_NODES_COMPILED);
    compile_options.SetInputModelPath(input_model_file);
    compile_options.SetOutputModelPath(output_model_file);
    compile_options.SetEpContextEmbedMode(true);
    ASSERT_NO_FATAL_FAILURE(
        SetEpContextDataWriteFunc(compile_options, StoreEpContextDataCallback, &write_callback_state));
 
    ASSERT_CXX_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
  }
 
  ASSERT_TRUE(std::filesystem::exists(output_model_file));
  EXPECT_FALSE(write_callback_state.write_called);
  EXPECT_FALSE(compile_read_callback_state.read_called);
 
  ONNX_NAMESPACE::ModelProto compiled_model;
  ASSERT_NO_FATAL_FAILURE(LoadModelProtoFromFile(output_model_file, compiled_model));
 
  auto ep_context_nodes = GetEpContextNodes(compiled_model);
  ASSERT_EQ(ep_context_nodes.size(), 1u);
 
  const ONNX_NAMESPACE::AttributeProto* embed_mode_attr = GetNodeAttribute(*ep_context_nodes[0], "embed_mode");
  ASSERT_NE(embed_mode_attr, nullptr);
  EXPECT_EQ(embed_mode_attr->type(), ONNX_NAMESPACE::AttributeProto_AttributeType_INT);
  EXPECT_EQ(embed_mode_attr->i(), 1);
 
  const ONNX_NAMESPACE::AttributeProto* ep_cache_context_attr = GetNodeAttribute(*ep_context_nodes[0],
                                                                                 "ep_cache_context");
  ASSERT_NE(ep_cache_context_attr, nullptr);
  EXPECT_EQ(ep_cache_context_attr->type(), ONNX_NAMESPACE::AttributeProto_AttributeType_STRING);
  EXPECT_EQ(ep_cache_context_attr->s(), "binary_data");
 
  EpContextDataCallbackState load_read_callback_state;
  {
    Ort::SessionOptions session_options;
    session_options.AddConfigEntry(kExampleEpTestEpContextDataSupport, "0");
    ASSERT_NO_FATAL_FAILURE(
        SetEpContextDataReadFunc(session_options, LoadEpContextDataCallback, &load_read_callback_state));
 
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    Ort::Session session(*ort_env, output_model_file, session_options);
  }
 
  EXPECT_FALSE(load_read_callback_state.read_called);
}
 
TEST(OrtEpLibrary, PluginEp_GenAndLoadEpContextModel_ExternalDataUsesFileFallback) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  const ORTCHAR_T* input_model_file = ORT_TSTR("testdata/mul_1.onnx");
  const ORTCHAR_T* output_model_file = ORT_TSTR("plugin_ep_mul_1_file_ctx.onnx");
  std::vector<std::filesystem::path> files_to_cleanup{std::filesystem::path{output_model_file}};
  for (const auto& path : files_to_cleanup) {
    std::filesystem::remove(path);
  }
  auto cleanup = gsl::finally([&]() {
    for (const auto& path : files_to_cleanup) {
      std::filesystem::remove(path);
    }
  });
 
  {
    Ort::SessionOptions session_options;
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
    compile_options.SetFlags(OrtCompileApiFlags_ERROR_IF_NO_NODES_COMPILED);
    compile_options.SetInputModelPath(input_model_file);
    compile_options.SetOutputModelPath(output_model_file);
    compile_options.SetEpContextEmbedMode(false);
 
    ASSERT_CXX_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
  }
 
  ASSERT_TRUE(std::filesystem::exists(output_model_file));
 
  ONNX_NAMESPACE::ModelProto compiled_model;
  ASSERT_NO_FATAL_FAILURE(LoadModelProtoFromFile(output_model_file, compiled_model));
 
  auto ep_context_nodes = GetEpContextNodes(compiled_model);
  ASSERT_EQ(ep_context_nodes.size(), 1u);
 
  const ONNX_NAMESPACE::AttributeProto* embed_mode_attr = GetNodeAttribute(*ep_context_nodes[0], "embed_mode");
  ASSERT_NE(embed_mode_attr, nullptr);
  EXPECT_EQ(embed_mode_attr->type(), ONNX_NAMESPACE::AttributeProto_AttributeType_INT);
  EXPECT_EQ(embed_mode_attr->i(), 0);
 
  const ONNX_NAMESPACE::AttributeProto* ep_cache_context_attr = GetNodeAttribute(*ep_context_nodes[0],
                                                                                 "ep_cache_context");
  ASSERT_NE(ep_cache_context_attr, nullptr);
  EXPECT_EQ(ep_cache_context_attr->type(), ONNX_NAMESPACE::AttributeProto_AttributeType_STRING);
  ASSERT_FALSE(ep_cache_context_attr->s().empty());
 
  const std::filesystem::path output_model_dir = std::filesystem::path{output_model_file}.parent_path();
  std::filesystem::path ep_cache_context_rel;
  ASSERT_ORTSTATUS_OK(
      ep_context_data_utils::Utf8Path(Ort::GetApi(), ep_cache_context_attr->s().c_str(), ep_cache_context_rel));
  const std::filesystem::path context_data_path = output_model_dir / ep_cache_context_rel;
  files_to_cleanup.push_back(context_data_path);
  ASSERT_TRUE(std::filesystem::exists(context_data_path));
 
  std::vector<char> context_data;
  std::string context_data_file_name;
  ASSERT_ORTSTATUS_OK(ep_context_data_utils::PathToUtf8String(Ort::GetApi(), context_data_path,
                                                              context_data_file_name));
  ASSERT_ORTSTATUS_OK(ep_context_data_utils::ReadEpContextDataFromFile(Ort::GetApi(), context_data_file_name.c_str(),
                                                                       nullptr, context_data));
  EXPECT_EQ(std::string(context_data.begin(), context_data.end()), "binary_data");
 
  {
    Ort::SessionOptions session_options;
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    Ort::Session session(*ort_env, output_model_file, session_options);
  }
}
 
TEST(OrtEpLibrary, PluginEp_GenEpContextModel_ExternalDataUsesWriteCallback) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  const ORTCHAR_T* input_model_file = ORT_TSTR("testdata/mul_1.onnx");
  const ORTCHAR_T* output_model_file = ORT_TSTR("plugin_ep_mul_1_external_ctx.onnx");
  std::filesystem::remove(output_model_file);
  auto cleanup = gsl::finally([&]() { std::filesystem::remove(output_model_file); });
 
  Ort::SessionOptions session_options;
  std::unordered_map<std::string, std::string> ep_options;
  session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
  EpContextDataCallbackState callback_state;
  Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
  compile_options.SetFlags(OrtCompileApiFlags_ERROR_IF_NO_NODES_COMPILED);
  compile_options.SetInputModelPath(input_model_file);
  compile_options.SetOutputModelPath(output_model_file);
  compile_options.SetEpContextEmbedMode(false);
  ASSERT_NO_FATAL_FAILURE(SetEpContextDataWriteFunc(compile_options, StoreEpContextDataCallback, &callback_state));
 
  ASSERT_CXX_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
  ASSERT_TRUE(std::filesystem::exists(output_model_file));
  ASSERT_TRUE(callback_state.write_called);
  EXPECT_FALSE(callback_state.write_file_name.empty());
  EXPECT_EQ(std::string(callback_state.payload.begin(), callback_state.payload.end()), "binary_data");
}
 
TEST(OrtEpLibrary, PluginEp_LoadEpContextModel_ExternalDataUsesReadCallback) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  const ORTCHAR_T* input_model_file = ORT_TSTR("testdata/mul_1.onnx");
  const ORTCHAR_T* compiled_model_file = ORT_TSTR("plugin_ep_mul_1_external_ctx_load.onnx");
  std::filesystem::remove(compiled_model_file);
  auto cleanup = gsl::finally([&]() { std::filesystem::remove(compiled_model_file); });
 
  EpContextDataCallbackState write_callback_state;
  {
    Ort::SessionOptions session_options;
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
    compile_options.SetFlags(OrtCompileApiFlags_ERROR_IF_NO_NODES_COMPILED);
    compile_options.SetInputModelPath(input_model_file);
    compile_options.SetOutputModelPath(compiled_model_file);
    compile_options.SetEpContextEmbedMode(false);
    ASSERT_NO_FATAL_FAILURE(
        SetEpContextDataWriteFunc(compile_options, StoreEpContextDataCallback, &write_callback_state));
 
    ASSERT_CXX_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
    ASSERT_TRUE(std::filesystem::exists(compiled_model_file));
    ASSERT_TRUE(write_callback_state.write_called);
  }
 
  EpContextDataCallbackState read_callback_state;
  read_callback_state.payload = write_callback_state.payload;
  {
    Ort::SessionOptions session_options;
    ASSERT_NO_FATAL_FAILURE(SetEpContextDataReadFunc(session_options, LoadEpContextDataCallback, &read_callback_state));
 
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    Ort::Session session(*ort_env, compiled_model_file, session_options);
  }
 
  ASSERT_TRUE(read_callback_state.read_called);
  EXPECT_EQ(read_callback_state.read_file_name, write_callback_state.write_file_name);
}
 
// Sandbox scenario for a compiling EP: no filesystem is needed to compile or to load the compiled model. The model,
// external initializers and EPContext data all travel through caller-owned buffers.
TEST(OrtEpLibrary, PluginEp_CompileAndLoadWithoutFilesystem_ExternalInitializersAndEpContextData) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  // mul_1 (compiled by the plugin EP) followed by an Add with an initializer that stays on the CPU EP.
  ONNX_NAMESPACE::ModelProto model;
  ASSERT_NO_FATAL_FAILURE(LoadModelProtoFromFile(ORT_TSTR("testdata/mul_1.onnx"), model));
  auto& graph = *model.mutable_graph();
  ASSERT_EQ(graph.node_size(), 1);
  const std::string output_name = graph.node(0).output(0);
  graph.mutable_node(0)->set_output(0, "mul_intermediate");
  auto& bias = *graph.add_initializer();
  bias.set_name("bias");
  bias.set_data_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT);
  bias.add_float_data(1.0f);
  auto& add = *graph.add_node();
  add.set_name("cpu_add");
  add.set_op_type("Add");
  add.add_input("mul_intermediate");
  add.add_input("bias");
  add.add_output(output_name);
  const std::string model_bytes = model.SerializeAsString();
 
  Ort::AllocatorWithDefaultOptions allocator;
  void* compiled_model = nullptr;
  size_t compiled_model_size = 0;
  void* external_buffer = nullptr;
  size_t external_size = 0;
  auto free_buffers = gsl::finally([&]() {
    allocator.Free(compiled_model);
    allocator.Free(external_buffer);
  });
  const std::basic_string<ORTCHAR_T> logical_file_name = ORT_TSTR("weights.bin");
 
  EpContextDataCallbackState write_callback_state;
  {
    Ort::SessionOptions session_options;
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
    compile_options.SetFlags(OrtCompileApiFlags_ERROR_IF_NO_NODES_COMPILED);
    compile_options.SetInputModelFromBuffer(model_bytes.data(), model_bytes.size());
    compile_options.SetGraphOptimizationLevel(ORT_DISABLE_ALL);
    compile_options.SetEpContextEmbedMode(false);
    compile_options.SetOutputModelBuffer(allocator, &compiled_model, &compiled_model_size);
    compile_options.SetOutputModelExternalInitializersBuffer(logical_file_name.c_str(), 0, allocator,
                                                             &external_buffer, &external_size);
    ASSERT_NO_FATAL_FAILURE(
        SetEpContextDataWriteFunc(compile_options, StoreEpContextDataCallback, &write_callback_state));
    ASSERT_CXX_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
  }
 
  ASSERT_NE(compiled_model, nullptr);
  ASSERT_NE(external_buffer, nullptr);
  EXPECT_EQ(external_size, sizeof(float));
  ASSERT_TRUE(write_callback_state.write_called);
  EXPECT_FALSE(std::filesystem::exists(logical_file_name));
 
#if !defined(DISABLE_EXTERNAL_INITIALIZERS)
  for (const char* use_buffers_directly : {"0", "1"}) {
    SCOPED_TRACE(use_buffers_directly);
    EpContextDataCallbackState read_callback_state;
    read_callback_state.payload = write_callback_state.payload;
 
    Ort::SessionOptions session_options;
    ASSERT_NO_FATAL_FAILURE(SetEpContextDataReadFunc(session_options, LoadEpContextDataCallback, &read_callback_state));
    session_options.AddConfigEntry(kOrtSessionOptionsConfigUseExternalInitializerFileBuffersDirectly,
                                   use_buffers_directly);
    session_options.AddExternalInitializersFromFilesInMemory({logical_file_name},
                                                             {static_cast<char*>(external_buffer)},
                                                             {external_size});
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    ASSERT_NO_THROW((Ort::Session{*ort_env, compiled_model, compiled_model_size, session_options}));
    EXPECT_TRUE(read_callback_state.read_called);
    EXPECT_EQ(read_callback_state.read_file_name, write_callback_state.write_file_name);
  }
#endif
}
 
TEST(OrtEpLibrary, PluginEp_ExternalEpContextCallbacksRequireAdvertisedSupport) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  const ORTCHAR_T* input_model_file = ORT_TSTR("testdata/mul_1.onnx");
  const ORTCHAR_T* compiled_model_file = ORT_TSTR("plugin_ep_callback_support_test.onnx");
  std::filesystem::remove(compiled_model_file);
  auto cleanup = gsl::finally([&]() { std::filesystem::remove(compiled_model_file); });
 
  EpContextDataCallbackState rejected_write_state;
  for (bool legacy_ep : {false, true}) {
    SCOPED_TRACE(legacy_ep ? "API version 30" : "No advertised support");
    Ort::SessionOptions session_options;
    session_options.AddConfigEntry(kExampleEpTestEpContextDataSupport, legacy_ep ? "1" : "0");
    session_options.AddConfigEntry(kExampleEpTestOrtVersion, legacy_ep ? "30" : "current");
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
    compile_options.SetFlags(OrtCompileApiFlags_ERROR_IF_NO_NODES_COMPILED);
    compile_options.SetInputModelPath(input_model_file);
    compile_options.SetOutputModelPath(compiled_model_file);
    compile_options.SetEpContextEmbedMode(false);
    ASSERT_NO_FATAL_FAILURE(
        SetEpContextDataWriteFunc(compile_options, StoreEpContextDataCallback, &rejected_write_state));
 
    Ort::Status status = Ort::CompileModel(*ort_env, compile_options);
    ASSERT_FALSE(status.IsOK());
    EXPECT_THAT(status.GetErrorMessage(),
                testing::HasSubstr("does not support the registered EPContext data write callback"));
  }
  EXPECT_FALSE(rejected_write_state.write_called);
  EXPECT_FALSE(std::filesystem::exists(compiled_model_file));
 
  EpContextDataCallbackState stored_context;
  {
    Ort::SessionOptions session_options;
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
    compile_options.SetFlags(OrtCompileApiFlags_ERROR_IF_NO_NODES_COMPILED);
    compile_options.SetInputModelPath(input_model_file);
    compile_options.SetOutputModelPath(compiled_model_file);
    compile_options.SetEpContextEmbedMode(false);
    ASSERT_NO_FATAL_FAILURE(
        SetEpContextDataWriteFunc(compile_options, StoreEpContextDataCallback, &stored_context));
    ASSERT_CXX_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
  }
  ASSERT_TRUE(stored_context.write_called);
  ASSERT_TRUE(std::filesystem::exists(compiled_model_file));
 
  EpContextDataCallbackState rejected_read_state;
  rejected_read_state.payload = stored_context.payload;
  for (bool legacy_ep : {false, true}) {
    SCOPED_TRACE(legacy_ep ? "API version 30" : "No advertised support");
    Ort::SessionOptions session_options;
    session_options.AddConfigEntry(kExampleEpTestEpContextDataSupport, legacy_ep ? "1" : "0");
    session_options.AddConfigEntry(kExampleEpTestOrtVersion, legacy_ep ? "30" : "current");
    ASSERT_NO_FATAL_FAILURE(
        SetEpContextDataReadFunc(session_options, LoadEpContextDataCallback, &rejected_read_state));
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    std::string error;
    try {
      Ort::Session session(*ort_env, compiled_model_file, session_options);
      FAIL() << "Expected unsupported EPContext data read callback rejection";
    } catch (const Ort::Exception& ex) {
      error = ex.what();
    }
    EXPECT_THAT(error, testing::HasSubstr("does not support the registered EPContext data read callback"));
  }
  EXPECT_FALSE(rejected_read_state.read_called);
 
  EpContextDataCallbackState unused_read_state;
  {
    Ort::SessionOptions session_options;
    session_options.AddConfigEntry(kExampleEpTestEpContextDataSupport, "0");
    ASSERT_NO_FATAL_FAILURE(
        SetEpContextDataReadFunc(session_options, LoadEpContextDataCallback, &unused_read_state));
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    ASSERT_NO_FATAL_FAILURE(RunMulModelWithPluginEp(input_model_file, session_options));
  }
  EXPECT_FALSE(unused_read_state.read_called);
}
 
TEST(OrtEpLibrary, PluginEp_GenWeightlessEpContextModel) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  {
    const ORTCHAR_T* input_model_file = ORT_TSTR("testdata/mul_1.onnx");
    const ORTCHAR_T* output_model_file = ORT_TSTR("plugin_ep_weightless_mul_1_ctx.onnx");
    std::filesystem::remove(output_model_file);
 
    std::unordered_map<std::string, std::string> ep_options;
    Ort::SessionOptions session_options;
 
    // Set session option config entry to enable weightless EP Context nodes.
    session_options.AddConfigEntry(kOrtSessionOptionEpEnableWeightlessEpContextNodes, "1");
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    // Create model compilation options from the session options.
    Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
    compile_options.SetFlags(OrtCompileApiFlags_ERROR_IF_NO_NODES_COMPILED);
    compile_options.SetInputModelPath(input_model_file);
    compile_options.SetOutputModelPath(output_model_file);
 
    // Compile the model.
    ASSERT_CXX_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
    // Make sure the compiled model was generated.
    // The compiled model has an EPContext node with initializers as explicit node inputs.
    ASSERT_TRUE(std::filesystem::exists(output_model_file));
  }
}
 
// Test weightless EP context model generation using the new ep.enable_weightless session option
// and ModelCompilationOptions_SetWeightlessEnabled API.
TEST(OrtEpLibrary, PluginEp_WeightlessAllInitializers_CompileApi) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  {
    const ORTCHAR_T* input_model_file = ORT_TSTR("testdata/mul_1.onnx");
    const ORTCHAR_T* output_model_file = ORT_TSTR("plugin_ep_weightless_all_init_ctx.onnx");
    std::filesystem::remove(output_model_file);
 
    std::unordered_map<std::string, std::string> ep_options;
    Ort::SessionOptions session_options;
 
    // Use the new unified weightless option (ep.enable_weightless) instead of the deprecated one.
    session_options.AddConfigEntry(kOrtSessionOptionEpEnableWeightless, "1");
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    // Create model compilation options and enable weightless cache via the CompileApi.
    Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
    compile_options.SetFlags(OrtCompileApiFlags_ERROR_IF_NO_NODES_COMPILED);
    compile_options.SetInputModelPath(input_model_file);
    compile_options.SetOutputModelPath(output_model_file);
    compile_options.SetWeightlessEnabled(true);
 
    // Compile the model.
    ASSERT_CXX_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
    ASSERT_TRUE(std::filesystem::exists(output_model_file));
 
    // Clean up.
    std::filesystem::remove(output_model_file);
  }
}
 
// Test SessionOptionsSetWeightlessSourceModelBuffer with valid and invalid inputs.
TEST(OrtEpLibrary, PluginEp_WeightlessSourceModelBuffer_Validation) {
  Ort::SessionOptions session_options;
  const auto& api = Ort::GetApi();
 
  // Valid buffer.
  {
    const char dummy_data[] = "dummy model bytes";
    OrtStatus* status = api.SessionOptionsSetWeightlessSourceModelBuffer(
        session_options, dummy_data, sizeof(dummy_data));
    ASSERT_EQ(status, nullptr);
  }
 
  // Null buffer should fail.
  {
    OrtStatus* status = api.SessionOptionsSetWeightlessSourceModelBuffer(
        session_options, nullptr, 100);
    ASSERT_NE(status, nullptr);
    ASSERT_EQ(api.GetErrorCode(status), ORT_INVALID_ARGUMENT);
    api.ReleaseStatus(status);
  }
 
  // Zero-length buffer should fail.
  {
    const char dummy_data[] = "data";
    OrtStatus* status = api.SessionOptionsSetWeightlessSourceModelBuffer(
        session_options, dummy_data, 0);
    ASSERT_NE(status, nullptr);
    ASSERT_EQ(api.GetErrorCode(status), ORT_INVALID_ARGUMENT);
    api.ReleaseStatus(status);
  }
}
 
// Test that weightless mode returns an error when the EP does not implement GetWeightlessSupport.
// The virtual GPU EP is compiled with ORT_API_VERSION >= 29 but does not set GetWeightlessSupport,
// so the validation in Compile() should return EP_FAIL.
TEST(OrtEpLibrary, PluginEp_WeightlessMode_ErrorWhenEpDoesNotSupport) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_virt_gpu_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  const ORTCHAR_T* input_model_file = ORT_TSTR("testdata/add_mul_add.onnx");
  const ORTCHAR_T* output_model_file = ORT_TSTR("plugin_ep_weightless_error_test.onnx");
  std::filesystem::remove(output_model_file);
 
  std::unordered_map<std::string, std::string> ep_options;
  Ort::SessionOptions session_options;
 
  // Request weightless mode.
  session_options.AddConfigEntry(kOrtSessionOptionEpEnableWeightless, "1");
  session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
  Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
  compile_options.SetInputModelPath(input_model_file);
  compile_options.SetOutputModelPath(output_model_file);
  compile_options.SetWeightlessEnabled(true);
 
  // CompileModel should fail because the virtual GPU EP does not implement GetWeightlessSupport.
  auto status = Ort::CompileModel(*ort_env, compile_options);
  ASSERT_FALSE(status.IsOK());
  ASSERT_THAT(status.GetErrorMessage(), testing::HasSubstr("does not implement GetWeightlessSupport"));
 
  // Clean up.
  std::filesystem::remove(output_model_file);
}
 
// Test loading a compiled model without registering the required EP with the session.
// We expect to get an explicit error that says that an EPContext node generated by "example_ep"
// was not assigned to the appropriate EP.
TEST(OrtEpLibrary, PluginEp_ErrorWhenLoadEPContextModel_WithoutRequiredEp) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  // Create a compiled model for the example EP.
  const ORTCHAR_T* compiled_model_file = ORT_TSTR("plugin_ep_compiled_test_errorwhenloadwithoutep.onnx");
  {
    const ORTCHAR_T* input_model_file = ORT_TSTR("testdata/mul_1.onnx");
    std::filesystem::remove(compiled_model_file);
 
    Ort::SessionOptions session_options;
    std::unordered_map<std::string, std::string> ep_options;
 
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
    compile_options.SetFlags(OrtCompileApiFlags_ERROR_IF_NO_NODES_COMPILED);
    compile_options.SetInputModelPath(input_model_file);
    compile_options.SetOutputModelPath(compiled_model_file);
 
    ASSERT_CXX_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
    ASSERT_TRUE(std::filesystem::exists(compiled_model_file));
  }
 
  // Create a session without the plugin EP and expect an error.
  {
    Ort::SessionOptions session_options;
 
    try {
      Ort::Session session(*ort_env, compiled_model_file, session_options);
      FAIL() << "Expected error when loading compiled model without the necessary EP";
    } catch (const Ort::Exception& e) {
      std::string error_msg = e.what();
      std::string_view expected_msg_prefix =
          "EPContext node generated by 'example_ep' is not compatible with any execution provider "
          "added to the session.";
      std::string_view expected_session_eps = "[CPUExecutionProvider]";
 
      EXPECT_TRUE(error_msg.find(expected_msg_prefix) != std::string::npos &&
                  error_msg.find(expected_session_eps) != std::string::npos)
          << "Error should mention EPContext node's required EP and the available EPs:\n"
          << error_msg;
    }
  }
 
  std::filesystem::remove(compiled_model_file);
}
 
// Generate an EPContext model with a plugin EP that uses a virtual GPU.
TEST(OrtEpLibrary, PluginEp_VirtGpu_GenEpContextModel) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_virt_gpu_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  {
    const ORTCHAR_T* input_model_file = ORT_TSTR("testdata/add_mul_add.onnx");
    const ORTCHAR_T* output_model_file = ORT_TSTR("plugin_ep_virt_gpu_add_mul_add_ctx.onnx");
    std::filesystem::remove(output_model_file);
 
    // Create session with example plugin EP
    Ort::SessionOptions session_options;
    std::unordered_map<std::string, std::string> ep_options;
 
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    // Create model compilation options from the session options.
    Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
    compile_options.SetFlags(OrtCompileApiFlags_ERROR_IF_NO_NODES_COMPILED);
    compile_options.SetInputModelPath(input_model_file);
    compile_options.SetOutputModelPath(output_model_file);
 
    // Compile the model.
    ASSERT_CXX_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
    // Make sure the compiled model was generated.
    ASSERT_TRUE(std::filesystem::exists(output_model_file));
  }
}
 
// Test that compatibility info is written to compiled model metadata
TEST(OrtEpLibrary, PluginEp_CompatibilityInfo_WrittenToMetadata) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  const ORTCHAR_T* input_model_file = ORT_TSTR("testdata/mul_1.onnx");
  const ORTCHAR_T* output_model_file = ORT_TSTR("plugin_ep_compat_test.onnx");
  std::filesystem::remove(output_model_file);
 
  // Compile the model
  {
    Ort::SessionOptions session_options;
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
    compile_options.SetFlags(OrtCompileApiFlags_ERROR_IF_NO_NODES_COMPILED);
    compile_options.SetInputModelPath(input_model_file);
    compile_options.SetOutputModelPath(output_model_file);
 
    ASSERT_CXX_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
    ASSERT_TRUE(std::filesystem::exists(output_model_file));
  }
 
  // Load the compiled model and check metadata for compatibility info
  {
    Ort::SessionOptions session_options;
    // Need to add the EP to handle EPContext nodes
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    Ort::Session session(*ort_env, output_model_file, session_options);
    Ort::AllocatorWithDefaultOptions allocator;
 
    // Check that the model has EP compatibility metadata
    Ort::ModelMetadata metadata = session.GetModelMetadata();
    auto custom_metadata_keys = metadata.GetCustomMetadataMapKeysAllocated(allocator);
 
    // Check for the exact metadata key for this EP: "ep_compatibility_info.example_ep"
    const std::string expected_key = std::string(kOrtModelMetadata_EpCompatibilityInfoPrefix) + "example_ep";
 
    bool found_compatibility_key = false;
    for (const auto& key : custom_metadata_keys) {
      std::string key_str(key.get());
      if (key_str == expected_key) {
        found_compatibility_key = true;
        break;
      }
    }
    ASSERT_TRUE(found_compatibility_key) << "Expected metadata key '" << expected_key << "' in compiled model";
 
    // Verify the compatibility value contains expected EP information
    auto value = metadata.LookupCustomMetadataMapAllocated(expected_key.c_str(), allocator);
    ASSERT_NE(value.get(), nullptr);
    std::string compatibility_value = value.get();
    ASSERT_GT(compatibility_value.length(), 0) << "Compatibility info should not be empty";
 
    // Validate the compatibility string format and values
    // Format: "example_ep;version=0.1.0;ort_api_version=<ORT_API_VERSION>;..."
    std::string expected_compatibility_info = "example_ep;version=0.1.0;ort_api_version=" +
                                              std::to_string(ORT_API_VERSION);
    EXPECT_TRUE(compatibility_value.starts_with(expected_compatibility_info));
  }
 
  std::filesystem::remove(output_model_file);
}
 
// Test loading a compiled model validates compatibility successfully
TEST(OrtEpLibrary, PluginEp_CompatibilityInfo_ValidatedOnLoad) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  const ORTCHAR_T* input_model_file = ORT_TSTR("testdata/mul_1.onnx");
  const ORTCHAR_T* compiled_model_file = ORT_TSTR("plugin_ep_compat_validate.onnx");
  std::filesystem::remove(compiled_model_file);
 
  // Step 1: Compile the model
  {
    Ort::SessionOptions session_options;
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
    compile_options.SetFlags(OrtCompileApiFlags_ERROR_IF_NO_NODES_COMPILED);
    compile_options.SetInputModelPath(input_model_file);
    compile_options.SetOutputModelPath(compiled_model_file);
 
    ASSERT_CXX_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
    ASSERT_TRUE(std::filesystem::exists(compiled_model_file));
  }
 
  // Step 2: Load the compiled model with the same EP - should succeed
  // The EP should validate compatibility and return OPTIMAL status
  {
    Ort::SessionOptions session_options;
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    // This should not throw - EP should validate compatibility as OPTIMAL
    ASSERT_NO_THROW(Ort::Session session(*ort_env, compiled_model_file, session_options));
  }
 
  std::filesystem::remove(compiled_model_file);
}
 
// Test that loading a compiled model with ep_context_enable=1 returns an error.
// This is an invalid configuration: the user is asking to generate EP context from a model
// that already contains EPContext nodes.
TEST(OrtEpLibrary, PluginEp_Error_LoadCompiledModelWithEpContextEnabled) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  const ORTCHAR_T* input_model_file = ORT_TSTR("testdata/mul_1.onnx");
  const ORTCHAR_T* compiled_model_file = ORT_TSTR("plugin_ep_recompile_test.onnx");
  std::filesystem::remove(compiled_model_file);
 
  // Step 1: Compile the original model (CompileModel API implicitly generates EPContext nodes)
  {
    Ort::SessionOptions session_options;
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
    compile_options.SetFlags(OrtCompileApiFlags_ERROR_IF_NO_NODES_COMPILED);
    compile_options.SetInputModelPath(input_model_file);
    compile_options.SetOutputModelPath(compiled_model_file);
 
    ASSERT_CXX_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
    ASSERT_TRUE(std::filesystem::exists(compiled_model_file));
  }
 
  // Step 2: Attempt to load the compiled model with ep.context_enable=1 - should fail
  {
    Ort::SessionOptions session_options;
    session_options.AddConfigEntry(kOrtSessionOptionEpContextEnable, "1");  // Request EP context generation
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    // Loading a compiled model with ep_context_enable=1 should fail
    try {
      Ort::Session session(*ort_env, compiled_model_file, session_options);
      FAIL() << "Expected error when loading compiled model with ep_context_enable=1";
    } catch (const Ort::Exception& e) {
      std::string error_msg = e.what();
      // Verify error message mentions the issue
      EXPECT_TRUE(error_msg.find("EPContext") != std::string::npos ||
                  error_msg.find("already") != std::string::npos ||
                  error_msg.find("re-compile") != std::string::npos)
          << "Error should mention EPContext or re-compilation: " << error_msg;
    }
  }
 
  std::filesystem::remove(compiled_model_file);
}
 
// Test that EPContext inference returns expected "not implemented" error.
// This documents that the example EP does not fully support EPContext execution.
TEST(OrtEpLibrary, PluginEp_EpContextInference_NotImplemented) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  const ORTCHAR_T* input_model_file = ORT_TSTR("testdata/mul_1.onnx");
  const ORTCHAR_T* compiled_model_file = ORT_TSTR("plugin_ep_inference_test.onnx");
  std::filesystem::remove(compiled_model_file);
 
  // Step 1: Compile the model with EP context enabled
  {
    Ort::SessionOptions session_options;
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
    compile_options.SetFlags(OrtCompileApiFlags_ERROR_IF_NO_NODES_COMPILED);
    compile_options.SetInputModelPath(input_model_file);
    compile_options.SetOutputModelPath(compiled_model_file);
 
    ASSERT_CXX_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
    ASSERT_TRUE(std::filesystem::exists(compiled_model_file));
  }
 
  // Step 2: Load compiled model and attempt inference - should fail with clear error
  {
    Ort::SessionOptions session_options;
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    Ort::Session session(*ort_env, compiled_model_file, session_options);
 
    // Prepare inputs - mul_1.onnx has input X of shape [3,2]
    std::vector<float> input_x = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f};
    std::vector<int64_t> input_shape = {3, 2};
 
    Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeDefault);
    Ort::Value input_x_tensor = Ort::Value::CreateTensor<float>(
        memory_info, input_x.data(), input_x.size(),
        input_shape.data(), input_shape.size());
 
    const char* input_names[] = {"X"};
    const char* output_names[] = {"Y"};
    std::vector<Ort::Value> input_tensors;
    input_tensors.push_back(std::move(input_x_tensor));
 
    // Inference should fail with NOT_IMPLEMENTED - verify exception content
    try {
      auto outputs = session.Run(Ort::RunOptions{nullptr},
                                 input_names, input_tensors.data(), input_tensors.size(),
                                 output_names, 1);
      FAIL() << "Expected exception for EPContext inference, but Run() succeeded";
    } catch (const Ort::Exception& e) {
      std::string msg = e.what();
      // Verify error mentions the limitation
      EXPECT_TRUE(msg.find("not implemented") != std::string::npos ||
                  msg.find("NOT_IMPLEMENTED") != std::string::npos ||
                  msg.find("EPContext") != std::string::npos)
          << "Expected NOT_IMPLEMENTED or EPContext in error, got: " << msg;
    }
  }
 
  std::filesystem::remove(compiled_model_file);
}
 
// Uses the original compiling approach with session option configs (instead of explicit compile API).
// Test that ORT does not overwrite an output model if it already exists.
// Notably, this tests the case in which ORT automatically generates the output model name.
TEST(OrtEpLibrary, PluginEp_GenEpContextModel_ErrorOutputModelExists_AutoGenOutputModelName) {
  const ORTCHAR_T* input_model_file = ORT_TSTR("testdata/mul_1.onnx");
  const ORTCHAR_T* expected_output_model_file = ORT_TSTR("testdata/mul_1_ctx.onnx");
  std::filesystem::remove(expected_output_model_file);
 
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
  std::unordered_map<std::string, std::string> ep_options;
 
  // Compile a model and let ORT set the output model name. This should succeed.
  {
    Ort::SessionOptions so;
    so.AddConfigEntry(kOrtSessionOptionEpContextEnable, "1");
    // Don't specify an output model path to let ORT automatically generate it!
    // so.AddConfigEntry(kOrtSessionOptionEpContextFilePath, "");
 
    so.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    Ort::Session session(*ort_env, input_model_file, so);
    ASSERT_TRUE(std::filesystem::exists(expected_output_model_file));  // check compiled model was generated.
  }
 
  auto modify_time_1 = std::filesystem::last_write_time(expected_output_model_file);
 
  // Try compiling the model again. ORT should return an error because the output model already exists.
  // Original compiled model should not be modified.
  {
    Ort::SessionOptions so;
    so.AddConfigEntry(kOrtSessionOptionEpContextEnable, "1");
    // Don't specify an output model path to let ORT automatically generate it!
    // so.AddConfigEntry(kOrtSessionOptionEpContextFilePath, "");
 
    so.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    try {
      Ort::Session session(*ort_env, input_model_file, so);
      FAIL();  // Should not get here!
    } catch (const Ort::Exception& excpt) {
      ASSERT_EQ(excpt.GetOrtErrorCode(), ORT_FAIL);
      ASSERT_THAT(excpt.what(),
                  testing::HasSubstr("exists already. "
                                     "Please remove the EP context model if you want to re-generate it."));
 
      ASSERT_TRUE(std::filesystem::exists(expected_output_model_file));
      auto modify_time_2 = std::filesystem::last_write_time(expected_output_model_file);
      ASSERT_TRUE(modify_time_2 == modify_time_1);  // Check that file was not modified
    }
  }
 
  std::filesystem::remove(expected_output_model_file);
}
 
// Test that EPContext generation and inference work correctly when non-ASCII Unicode characters
// appear in both the model file path and the EPContext output path.
TEST(OrtEpLibrary, PluginEp_GenEpContextModel_UnicodePath) {
  namespace fs = std::filesystem;
 
  // Set up a Unicode working directory and model path (U+4E2D U+6587, "中文").
  const fs::path unicode_dir{fs::path(u8"\u4e2d\u6587")};
  fs::remove_all(unicode_dir);
  fs::create_directories(unicode_dir);
  auto cleanup = gsl::finally([&unicode_dir] {
    std::error_code ec;
    fs::remove_all(unicode_dir, ec);
  });
 
  const fs::path input_model = unicode_dir / fs::path(u8"\u4e2d\u6587.onnx");
  const fs::path output_model = unicode_dir / fs::path(u8"\u4e2d\u6587_ctx.onnx");
 
  fs::copy_file(ORT_TSTR("testdata/mul_1.onnx"), input_model, fs::copy_options::overwrite_existing);
  fs::remove(output_model);
 
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
  std::unordered_map<std::string, std::string> ep_options;
 
  // Convert the Unicode output path to a UTF-8 string for the session config entry.
  // ep_context_options.cc must correctly convert this back to a wide path on Windows.
  const auto u8str = output_model.u8string();
  const std::string utf8_output_path(u8str.begin(), u8str.end());
 
  // Generate EPContext model.
  {
    Ort::SessionOptions session_options;
    session_options.AddConfigEntry(kOrtSessionOptionEpContextEnable, "1");
    session_options.AddConfigEntry(kOrtSessionOptionEpContextFilePath, utf8_output_path.c_str());
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    Ort::Session session(*ort_env, input_model.c_str(), session_options);
    ASSERT_TRUE(fs::exists(output_model)) << "EPContext not created at: " << utf8_output_path;
  }
}
 
// Test that a model with zero graph inputs can be compiled into an EPContext model and reloaded.
// The compiled EPContext node will have 0 inputs, exercising the EPContext schema change
// that allows min_input=0.
TEST(OrtEpLibrary, PluginEp_GenEpContextModel_ZeroInputModel) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  const ORTCHAR_T* output_model_file = ORT_TSTR("plugin_ep_zero_input_ctx.onnx");
  std::filesystem::remove(output_model_file);
  auto cleanup = gsl::finally([&]() { std::filesystem::remove(output_model_file); });
 
  // Build a model with 0 graph inputs.
  const std::string model_bytes = BuildZeroInputMulModelBytes();
 
  // Compile the model with the example EP.
  {
    Ort::SessionOptions session_options;
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
    compile_options.SetInputModelFromBuffer(model_bytes.data(), model_bytes.size());
    compile_options.SetOutputModelPath(output_model_file);
    compile_options.SetEpContextEmbedMode(true);
 
    ASSERT_CXX_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
    ASSERT_TRUE(std::filesystem::exists(output_model_file));
  }
 
  // Verify the compiled model has an EPContext node with 0 inputs.
  ONNX_NAMESPACE::ModelProto compiled_model;
  ASSERT_NO_FATAL_FAILURE(LoadModelProtoFromFile(output_model_file, compiled_model));
 
  auto ep_context_nodes = GetEpContextNodes(compiled_model);
  ASSERT_GE(ep_context_nodes.size(), 1u);
 
  // The EPContext node replacing the Mul (whose inputs were both initializers) should have 0 inputs.
  EXPECT_EQ(ep_context_nodes[0]->input_size(), 0)
      << "EPContext node from a zero-input model should have 0 inputs";
 
  // Reload the compiled model into a session to verify graph validation passes.
  {
    Ort::SessionOptions session_options;
    std::unordered_map<std::string, std::string> ep_options;
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
    ASSERT_NO_THROW(Ort::Session session(*ort_env, output_model_file, session_options))
        << "Loading a compiled model with a 0-input EPContext node should succeed";
  }
}
 
// Test that inference works correctly when non-ASCII Unicode characters appear in the model file path.
TEST(OrtEpLibrary, PluginEp_Inference_UnicodePath) {
  namespace fs = std::filesystem;
 
  const fs::path unicode_dir{fs::path(u8"\u4e2d\u6587")};
  fs::remove_all(unicode_dir);
  fs::create_directories(unicode_dir);
  auto cleanup = gsl::finally([&unicode_dir] {
    std::error_code ec;
    fs::remove_all(unicode_dir, ec);
  });
 
  const fs::path input_model = unicode_dir / fs::path(u8"\u4e2d\u6587.onnx");
  fs::copy_file(ORT_TSTR("testdata/mul_1.onnx"), input_model, fs::copy_options::overwrite_existing);
 
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
  std::unordered_map<std::string, std::string> ep_options;
 
  Ort::SessionOptions session_options;
  session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
  RunMulModelWithPluginEp(input_model.c_str(), session_options);
}
 
TEST(OrtEpLibrary, KernelPluginEp_Inference) {
  RegisteredEpDeviceUniquePtr example_kernel_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_kernel_registry_info,
                                                         example_kernel_ep));
  Ort::ConstEpDevice plugin_ep_device(example_kernel_ep.get());
 
  // Run model with squeeze, mul, and relu nodes.
  // No sharing of pre-packed weights.
  {
    std::unordered_map<std::string, std::string> ep_options;
    Ort::SessionOptions session_options;
 
    session_options.AddConfigEntry(kOrtSessionOptionsDisableCPUEPFallback, "1");  // Fail if any node assigned to CPU EP.
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
    ASSERT_NO_FATAL_FAILURE(RunSqueezeMulReluModel(session_options));
  }
 
  // Run model with squeeze, mul, and relu nodes.
  // Enable sharing of pre-packed weights.
  {
    std::unordered_map<std::string, std::string> ep_options = {{"enable_prepack_weight_sharing", "1"}};
    Ort::SessionOptions session_options;
 
    session_options.AddConfigEntry(kOrtSessionOptionsDisableCPUEPFallback, "1");  // Fail if any node assigned to CPU EP
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
    ASSERT_NO_FATAL_FAILURE(RunSqueezeMulReluModel(session_options));
  }
 
  // Run model with sub, mul, sub.
  // No sharing of pre-packed weights.
  {
    Ort::SessionOptions session_options;
    std::unordered_map<std::string, std::string> ep_options;
 
    session_options.AddConfigEntry(kOrtSessionOptionsDisableCPUEPFallback, "1");  // Fail if any node assigned to CPU EP
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
    ASSERT_NO_FATAL_FAILURE(RunSubMulSubModel(session_options));
  }
 
  // Run model with sub, mul, sub.
  // Enable sharing of pre-packed weights.
  {
    std::unordered_map<std::string, std::string> ep_options = {{"enable_prepack_weight_sharing", "1"}};
    Ort::SessionOptions session_options;
 
    session_options.AddConfigEntry(kOrtSessionOptionsDisableCPUEPFallback, "1");  // Fail if any node assigned to CPU EP
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
    ASSERT_NO_FATAL_FAILURE(RunSubMulSubModel(session_options));
  }
}
 
TEST(OrtEpLibrary, KernelPluginEp_ControlFlow_If) {
  RegisteredEpDeviceUniquePtr example_kernel_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_kernel_registry_info,
                                                         example_kernel_ep));
  Ort::ConstEpDevice plugin_ep_device(example_kernel_ep.get());
 
  // Run model with If and Mul ops.
  // No sharing of pre-packed weights.
  {
    std::unordered_map<std::string, std::string> ep_options;
    Ort::SessionOptions session_options;
 
    session_options.AddConfigEntry(kOrtSessionOptionsDisableCPUEPFallback, "1");  // Fail if any node assigned to CPU EP.
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
    ASSERT_NO_FATAL_FAILURE(RunIfMulModel(session_options, /*if_condition*/ true));
    ASSERT_NO_FATAL_FAILURE(RunIfMulModel(session_options, /*if_condition*/ false));
  }
 
  // Run model with If and Mul ops.
  // Enable sharing of pre-packed weights.
  {
    std::unordered_map<std::string, std::string> ep_options = {{"enable_prepack_weight_sharing", "1"}};
    Ort::SessionOptions session_options;
 
    session_options.AddConfigEntry(kOrtSessionOptionsDisableCPUEPFallback, "1");  // Fail if any node assigned to CPU EP
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
    ASSERT_NO_FATAL_FAILURE(RunIfMulModel(session_options, /*if_condition*/ true));
    ASSERT_NO_FATAL_FAILURE(RunIfMulModel(session_options, /*if_condition*/ false));
  }
}
 
TEST(OrtEpLibrary, KernelPluginEp_ControlFlow_Loop) {
  RegisteredEpDeviceUniquePtr example_kernel_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_kernel_registry_info,
                                                         example_kernel_ep));
  Ort::ConstEpDevice plugin_ep_device(example_kernel_ep.get());
 
  // Run model with Loop and Sub ops.
  // No sharing of pre-packed weights.
  {
    std::unordered_map<std::string, std::string> ep_options;
    Ort::SessionOptions session_options;
 
    session_options.AddConfigEntry(kOrtSessionOptionsDisableCPUEPFallback, "1");  // Fail if any node assigned to CPU EP
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
    ASSERT_NO_FATAL_FAILURE(RunLoopSubOneModel(session_options));
  }
 
  // Run model with Loop and Sub ops.
  // Enable sharing of pre-packed weights.
  {
    std::unordered_map<std::string, std::string> ep_options = {{"enable_prepack_weight_sharing", "1"}};
    Ort::SessionOptions session_options;
 
    session_options.AddConfigEntry(kOrtSessionOptionsDisableCPUEPFallback, "1");  // Fail if any node assigned to CPU EP
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
    ASSERT_NO_FATAL_FAILURE(RunLoopSubOneModel(session_options));
  }
}
 
TEST(OrtEpLibrary, KernelPluginEp_ControlFlow_Scan) {
  RegisteredEpDeviceUniquePtr example_kernel_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_kernel_registry_info,
                                                         example_kernel_ep));
  Ort::ConstEpDevice plugin_ep_device(example_kernel_ep.get());
 
  // Run model with Scan and Mul ops.
  // No sharing of pre-packed weights.
  {
    std::unordered_map<std::string, std::string> ep_options;
    Ort::SessionOptions session_options;
 
    session_options.AddConfigEntry(kOrtSessionOptionsDisableCPUEPFallback, "1");  // Fail if any node assigned to CPU EP
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
    ASSERT_NO_FATAL_FAILURE(RunScanMulModel(session_options));
  }
 
  // Run model with Scan and Mul ops.
  // Enable sharing of pre-packed weights.
  {
    std::unordered_map<std::string, std::string> ep_options = {{"enable_prepack_weight_sharing", "1"}};
    Ort::SessionOptions session_options;
 
    session_options.AddConfigEntry(kOrtSessionOptionsDisableCPUEPFallback, "1");  // Fail if any node assigned to CPU EP
    session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
    ASSERT_NO_FATAL_FAILURE(RunScanMulModel(session_options));
  }
}
 
enum class ProfilingMode {
  Session,
  Run
};
 
// Runs a model with profiling enabled (at the session or run level) and verifies the example kernel
// EP's profiling events appear in the output.
void RunKernelPluginEpProfilingTest(ProfilingMode mode) {
  RegisteredEpDeviceUniquePtr example_kernel_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_kernel_registry_info,
                                                         example_kernel_ep));
  Ort::ConstEpDevice plugin_ep_device(example_kernel_ep.get());
 
  std::unordered_map<std::string, std::string> ep_options;
  Ort::SessionOptions session_options;
  session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
  const ORTCHAR_T* profile_prefix = mode == ProfilingMode::Session ? ORT_TSTR("plugin_ep_session_profiling_test")
                                                                   : ORT_TSTR("plugin_ep_run_profiling_test");
 
  if (mode == ProfilingMode::Session) {
    session_options.EnableProfiling(profile_prefix);
  }
 
  Ort::Session session(*ort_env, ORT_TSTR("testdata/if_mul.onnx"), session_options);
 
  // Create inputs.
  Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
  std::array<int64_t, 1> a_shape = {1};
  std::array<int64_t, 2> b_shape = {3, 2};
 
  std::array<bool, 1> a_data = {true};
  std::array<float, 6> b_data = {2.f, 3.f, 4.f, -5.f, 6.f, 7.f};
 
  std::vector<Ort::Value> ort_inputs{};
  ort_inputs.emplace_back(
      Ort::Value::CreateTensor<bool>(memory_info, a_data.data(), a_data.size(), a_shape.data(), a_shape.size()));
  ort_inputs.emplace_back(
      Ort::Value::CreateTensor<float>(memory_info, b_data.data(), b_data.size(), b_shape.data(), b_shape.size()));
 
  std::array ort_input_names{"A", "B"};
  std::array output_names{"C"};
 
  // Run the model.
  Ort::RunOptions run_options;
 
  if (mode == ProfilingMode::Run) {
    run_options.EnableProfiling(profile_prefix);
  }
 
  session.Run(run_options, ort_input_names.data(), ort_inputs.data(),
              ort_inputs.size(), output_names.data(), output_names.size());
 
  // Get the profile file path.
  std::filesystem::path profile_file_path;
 
  if (mode == ProfilingMode::Session) {
    Ort::AllocatorWithDefaultOptions allocator;
    Ort::AllocatedStringPtr profile_file = session.EndProfilingAllocated(allocator);
    profile_file_path = profile_file.get();
  } else {
    // The APIs for run-profiling do not support retrieving the name of the actual profile file
    // generated by ORT, so find it by prefix in the current directory.
    std::filesystem::file_time_type newest_time{};
    bool found_profile_file = false;
 
    for (const auto& entry : std::filesystem::directory_iterator(ORT_TSTR("."))) {
      auto filename = entry.path().filename().native();
      if (filename.starts_with(profile_prefix) && filename.ends_with(ORT_TSTR(".json"))) {
        auto current_time = std::filesystem::last_write_time(entry.path());
 
        if (!found_profile_file || current_time > newest_time) {
          newest_time = current_time;
          profile_file_path = entry.path();
          found_profile_file = true;
        }
      }
    }
 
    ASSERT_TRUE(found_profile_file) << "Could not find run profile with prefix '"
                                    << profile_prefix << "' in current directory";
  }
 
  auto cleanup_profile_file = gsl::finally([&profile_file_path] {
    std::error_code ec;
    std::filesystem::remove(profile_file_path, ec);
    if (ec) {
      std::cerr << ec.message() << std::endl;
    }
  });
 
  std::ifstream profile(profile_file_path);
  ASSERT_TRUE(profile.is_open()) << "Could not open profile file: " << profile_file_path;
 
  std::string content(std::istreambuf_iterator<char>{profile}, std::istreambuf_iterator<char>{});
  profile.close();
 
  const auto profile_json = nlohmann::json::parse(content);
 
  // Find EP's event entry inside the profile
  const char* ep_event_name = "ExampleKernelEp_Mul";
  nlohmann::json ep_event_entry;
 
  for (const auto& profile_entry : profile_json) {
    if (profile_entry.is_object() && profile_entry.contains("name")) {
      if (profile_entry["name"] == ep_event_name) {
        ep_event_entry = profile_entry;
        break;
      }
    }
  }
  ASSERT_TRUE(ep_event_entry.is_object() && ep_event_entry.size() > 0)
      << "Did not find EP expected event entry '" << ep_event_name << "'. Profile contents: " << content;
  ASSERT_EQ(ep_event_entry["cat"], "Kernel") << ep_event_entry;
  ASSERT_TRUE(ep_event_entry.contains("ts")) << ep_event_entry;
  ASSERT_TRUE(ep_event_entry.contains("dur")) << ep_event_entry;
  ASSERT_TRUE(ep_event_entry.contains("args")) << ep_event_entry;
  ASSERT_TRUE(ep_event_entry["args"].contains("parent_name")) << ep_event_entry;
 
  // Check the expected ORT parent event's name.
  std::string parent_event_name = ep_event_entry["args"]["parent_name"];
 
  if (mode == ProfilingMode::Session) {
    ASSERT_TRUE(parent_event_name.starts_with("mul_"));
    ASSERT_TRUE(parent_event_name.ends_with("_kernel_time"));
  } else /*if (mode == ProfilingMode::Run)*/ {
    // TODO: Fix run profilers because they do not profile nested subgraphs (e.g., branches of If operator).
    // Currently, this will incorrectly report that "if_kernel" is the parent, but it should be the Mul within the
    // if branch.
 
    // ASSERT_TRUE(parent_event_name.starts_with("mul_"));
    // ASSERT_TRUE(parent_event_name.ends_with("_kernel_time"));
  }
 
  // Find the EP event's parent ORT entry
  nlohmann::json parent_ort_entry;
 
  for (const auto& profile_entry : profile_json) {
    if (profile_entry.is_object() && profile_entry.contains("name")) {
      if (profile_entry["name"] == parent_event_name) {
        parent_ort_entry = profile_entry;
        break;
      }
    }
  }
 
  ASSERT_TRUE(parent_ort_entry.is_object() && parent_ort_entry.size() > 0)
      << "Did not find expected parent ORT event entry '" << parent_event_name << "'. Profile contents " << content;
  ASSERT_TRUE(parent_ort_entry.contains("ts"));
  ASSERT_TRUE(parent_ort_entry.contains("dur"));
 
  // Check that the parent ORT event's interval completely encompasses the EP event's interval.
  int64_t ep_start = ep_event_entry["ts"].get<int64_t>();
  int64_t ep_end = ep_start + ep_event_entry["dur"].get<int64_t>();
  int64_t parent_start = parent_ort_entry["ts"].get<int64_t>();
  int64_t parent_end = parent_start + parent_ort_entry["dur"].get<int64_t>();
  EXPECT_GE(ep_start, parent_start);
  EXPECT_LE(ep_end, parent_end);
}
 
TEST(OrtEpLibrary, KernelPluginEp_SessionProfiling) {
  RunKernelPluginEpProfilingTest(ProfilingMode::Session);
}
 
TEST(OrtEpLibrary, KernelPluginEp_RunProfiling) {
  RunKernelPluginEpProfilingTest(ProfilingMode::Run);
}
 
// Creates a session with the example plugin EP and runs a model with a single Costom_Mul node.
// Uses AppendExecutionProvider_V2 to append the example plugin EP to the session.
TEST(OrtEpLibrary, PluginEp_Custom_Op_Inference_With_Explicit_Ep) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  // Create session with example plugin EP
  Ort::SessionOptions session_options;
  std::unordered_map<std::string, std::string> ep_options;
  session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
  RunCustomMulModelWithPluginEp(session_options);
}
 
// Creates a session with the example plugin EP and runs a model with a single Costom_Mul node.
// Uses the PREFER_CPU policy to append the example plugin EP to the session.
TEST(OrtEpLibrary, PluginEp_Custom_Op_Inference_With_Prefer_Cpu) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  {
    // PREFER_CPU pick our example EP over ORT CPU EP. TODO: Actually assert this.
    Ort::SessionOptions session_options;
    session_options.SetEpSelectionPolicy(OrtExecutionProviderDevicePolicy_PREFER_CPU);
    RunCustomMulModelWithPluginEp(session_options);
  }
}
 
// Tests the GetHardwareDeviceEpIncompatibilityDetails C API with the example plugin EP.
// The example plugin EP supports CPU devices, so this test verifies that a CPU device
// is reported as compatible (reasons_bitmask == 0).
TEST(OrtEpLibrary, PluginEp_CpuDevice_ReturnsCompatible) {
  const OrtApi* api = OrtGetApiBase()->GetApi(ORT_API_VERSION);
  ASSERT_NE(api, nullptr);
 
  OrtEnv* env = static_cast<OrtEnv*>(*ort_env);
 
  // Register the example plugin EP
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
 
  // Get all hardware devices
  size_t num_hw_devices = 0;
  ASSERT_ORTSTATUS_OK(api->GetNumHardwareDevices(env, &num_hw_devices));
  ASSERT_GT(num_hw_devices, 0u);
  std::vector<const OrtHardwareDevice*> hw_devices(num_hw_devices);
  ASSERT_ORTSTATUS_OK(api->GetHardwareDevices(env, hw_devices.data(), num_hw_devices));
 
  // Find a CPU device using the public accessor
  const OrtHardwareDevice* cpu_device = nullptr;
  for (size_t i = 0; i < num_hw_devices; ++i) {
    if (api->HardwareDevice_Type(hw_devices[i]) == OrtHardwareDeviceType_CPU) {
      cpu_device = hw_devices[i];
      break;
    }
  }
  ASSERT_NE(cpu_device, nullptr) << "No CPU device found";
 
  // Check compatibility - ExampleEP supports CPU, so should return no incompatibility reasons
  OrtDeviceEpIncompatibilityDetails* details = nullptr;
  ASSERT_ORTSTATUS_OK(api->GetHardwareDeviceEpIncompatibilityDetails(env, Utils::example_ep_info.registration_name.c_str(),
                                                                     cpu_device, &details));
  ASSERT_NE(details, nullptr);
 
  // Verify compatible (no incompatibility reasons)
  uint32_t reasons_bitmask = 0xFFFFFFFF;
  ASSERT_ORTSTATUS_OK(api->DeviceEpIncompatibilityDetails_GetReasonsBitmask(details, &reasons_bitmask));
  EXPECT_EQ(reasons_bitmask, 0u) << "CPU device should be compatible with example_plugin_ep";
 
  int32_t error_code = -1;
  ASSERT_ORTSTATUS_OK(api->DeviceEpIncompatibilityDetails_GetErrorCode(details, &error_code));
  EXPECT_EQ(error_code, 0);
 
  api->ReleaseDeviceEpIncompatibilityDetails(details);
}
 
// Tests the GetHardwareDeviceEpIncompatibilityDetails C API with the example plugin EP.
// The example plugin EP only supports CPU devices, so this test verifies that a GPU device
// is reported as incompatible (reasons_bitmask != 0).
TEST(OrtEpLibrary, PluginEp_GpuDevice_ReturnsInCompatible) {
  const OrtApi* api = OrtGetApiBase()->GetApi(ORT_API_VERSION);
  ASSERT_NE(api, nullptr);
 
  OrtEnv* env = static_cast<OrtEnv*>(*ort_env);
 
  // Register the regular example plugin EP (CPU-only)
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
 
  // Get all hardware devices
  size_t num_hw_devices = 0;
  ASSERT_ORTSTATUS_OK(api->GetNumHardwareDevices(env, &num_hw_devices));
  ASSERT_GT(num_hw_devices, 0u);
  std::vector<const OrtHardwareDevice*> hw_devices(num_hw_devices);
  ASSERT_ORTSTATUS_OK(api->GetHardwareDevices(env, hw_devices.data(), num_hw_devices));
 
  // Find a GPU device using the public accessor
  const OrtHardwareDevice* gpu_device = nullptr;
  for (size_t i = 0; i < num_hw_devices; ++i) {
    if (api->HardwareDevice_Type(hw_devices[i]) == OrtHardwareDeviceType_GPU) {
      gpu_device = hw_devices[i];
      break;
    }
  }
 
  if (gpu_device == nullptr) {
    // GPU device not found, early exit
    GTEST_SKIP() << "No GPU device found";
  }
 
  // Check compatibility - ExampleEP only supports CPU, so GPU should return incompatibility reasons
  OrtDeviceEpIncompatibilityDetails* details = nullptr;
  ASSERT_ORTSTATUS_OK(api->GetHardwareDeviceEpIncompatibilityDetails(env, Utils::example_ep_info.registration_name.c_str(),
                                                                     gpu_device, &details));
  ASSERT_NE(details, nullptr);
 
  // Verify incompatible (should have incompatibility reasons)
  uint32_t reasons_bitmask = 0;
  ASSERT_ORTSTATUS_OK(api->DeviceEpIncompatibilityDetails_GetReasonsBitmask(details, &reasons_bitmask));
  EXPECT_NE(reasons_bitmask, 0u) << "GPU device should be incompatible with example_plugin_ep (CPU-only)";
 
  api->ReleaseDeviceEpIncompatibilityDetails(details);
}
 
TEST(OrtEpLibrary, CompilingPluginEp_MultiSubgraphs_DuplicateMetaDefIdBug) {
  // Test a fix to a bug that incorrectly assigned duplicate MetaDef IDs to fused nodes
  // that live in different GraphViews (e.g., in different branches of an If node).
  //
  // The test model graph does the following computation:
  //   if (A) { C = Mul(B, 2.0) }
  //   else { C = Mul(B, 3) }
  //   return C
  //
  // The example plugin EP should support and execute both Mul nodes (as compiled fused nodes).
  // However, the bug (in PluginExecutionProvider::GetCapability) assigned the same MetaDef ID
  // to both compiled Mul nodes, which caused session creation to fail with error:
  //
  //   > Failed to add kernel for example_ep_9433721956998717990_0 example_ep example_ep:
  //     Conflicting with a registered kernel with op versions. the since version is: 1
  //
  // The fix was to use the same instance of `ModelMetadefIdGenerator` across all calls to
  // PluginExecutionProvider::GetCapability(). This ensures that the MetaDef IDs are unique.
  RegisteredEpDeviceUniquePtr example_kernel_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info,
                                                         example_kernel_ep));
  Ort::ConstEpDevice plugin_ep_device(example_kernel_ep.get());
 
  std::unordered_map<std::string, std::string> ep_options;
  Ort::SessionOptions session_options;
 
  session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
  ASSERT_NO_FATAL_FAILURE(RunIfMulModel(session_options, /*if_condition*/ true));
}
 
TEST(OrtEpLibrary, PluginEp_Sync) {
  RegisteredEpDeviceUniquePtr example_ep;
  ASSERT_NO_FATAL_FAILURE(Utils::RegisterAndGetExampleEp(*ort_env, Utils::example_ep_info, example_ep));
  Ort::ConstEpDevice plugin_ep_device(example_ep.get());
 
  // Create session with example plugin EP
  Ort::SessionOptions session_options;
  std::unordered_map<std::string, std::string> ep_options;
  session_options.AppendExecutionProvider_V2(*ort_env, {plugin_ep_device}, ep_options);
 
  Utils::LoadExampleEpHooksPtr example_ep_hooks;
  ASSERT_NO_FATAL_FAILURE(Utils::LoadExampleEpHooks(Utils::example_ep_info, example_ep_hooks));
  ASSERT_NE(example_ep_hooks->reset_sync_count, nullptr);
  ASSERT_NE(example_ep_hooks->get_sync_count, nullptr);
 
  example_ep_hooks->reset_sync_count();
 
  RunMulModelWithPluginEpUsingIOBinding(session_options);
 
  ASSERT_EQ(example_ep_hooks->get_sync_count(), 1) << "Expected Sync to be called once during inference";
}
 
TEST(OrtApi, KernelContextGetPreallocatedOutputContract) {
  const OrtApi* api = OrtGetApiBase()->GetApi(ORT_API_VERSION);
  ASSERT_NE(api->KernelContext_GetPreallocatedOutput, nullptr);
 
  auto expect_rejected = [&](OrtStatus* status) {
    ASSERT_NE(status, nullptr);
    const OrtErrorCode code = api->GetErrorCode(status);
    EXPECT_TRUE(code == ORT_INVALID_ARGUMENT) << code;
    api->ReleaseStatus(status);
  };
 
  // Null arguments are rejected, and a failed call leaves the out parameter untouched.
  OrtValue* const sentinel_value = reinterpret_cast<OrtValue*>(static_cast<uintptr_t>(1));
  OrtValue* sentinel = sentinel_value;
  expect_rejected(api->KernelContext_GetPreallocatedOutput(nullptr, 0, &sentinel));
  EXPECT_EQ(sentinel, sentinel_value);
 
  expect_rejected(api->KernelContext_GetPreallocatedOutput(nullptr, 0, nullptr));
}
}  // namespace test
}  // namespace onnxruntime