Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
#include <algorithm>
#include <fstream>
#include <filesystem>
#include <gsl/gsl>
 
#include "gtest/gtest.h"
#include "gmock/gmock.h"
 
#include "core/common/narrow.h"
#include "core/graph/constants.h"
#include "core/session/onnxruntime_c_api.h"
#include "core/session/onnxruntime_cxx_api.h"
#include "core/session/onnxruntime_lite_custom_op.h"
#include "core/session/onnxruntime_session_options_config_keys.h"
 
#include "test/shared_lib/test_fixture.h"
#include "test/shared_lib/utils.h"
#include "test/util/include/api_asserts.h"
#include "test/util/include/test_allocator.h"
 
#include "onnxruntime_config.h"  // generated file in build output dir
 
extern std::unique_ptr<Ort::Env> ort_env;
 
using namespace Ort;
 
namespace {
 
Ort::Session CreateSession(Ort::Env& env,
                           Model& graph_api_model,
                           Ort::SessionOptions* session_options_for_test = nullptr) {
  Ort::SessionOptions default_session_options;
  Ort::SessionOptions& session_options = session_options_for_test ? *session_options_for_test
                                                                  : default_session_options;
 
  // Set this to save the model if you want to debug.
  // session_options.SetOptimizedModelFilePath(ORT_TSTR("model_builder_output.onnx"));
 
  Ort::Session session(env, graph_api_model, session_options);
 
  // Session should not require the model to stay alive so free it now to validate.
  graph_api_model = Model(nullptr);
 
  return session;
}
 
template <typename ModelOutputT, typename ModelInputT = float>
void TestInference(Ort::Session& session,
                   const std::vector<Input<ModelInputT>>& inputs,
                   const char* output_name,
                   const std::vector<int64_t>& expected_dims,
                   const std::vector<ModelOutputT>& expected_values) {
  auto default_allocator = std::make_unique<MockedOrtAllocator>();
 
  // without preallocated output tensor
  RunSession<ModelOutputT, ModelInputT>(default_allocator.get(),
                                        session,
                                        inputs,
                                        output_name,
                                        expected_dims,
                                        expected_values,
                                        nullptr);
}
 
// Create OrtNode using the C API
OrtNode* CreateNode(const OrtModelEditorApi& api,
                    const char* operator_name, const char* node_name,
                    const gsl::span<const char*> input_names,
                    const gsl::span<const char*> output_names,
                    const gsl::span<OrtOpAttr*> attributes = {},
                    const char* domain_name = onnxruntime::kOnnxDomain) {
  OrtNode* node = nullptr;
  Ort::ThrowOnError(api.CreateNode(operator_name, domain_name, node_name,
                                   input_names.data(), input_names.size(),
                                   output_names.data(), output_names.size(),
                                   attributes.data(), attributes.size(),
                                   &node));
  return node;
}
 
// convenience func to convert initalizer lists to gsl::span
OrtNode* CreateNode(const OrtModelEditorApi& api,
                    const char* operator_name, const char* node_name,
                    const std::initializer_list<const char*> input_names,
                    const std::initializer_list<const char*> output_names,
                    const std::initializer_list<OrtOpAttr*> attributes = {},
                    const char* domain_name = onnxruntime::kOnnxDomain) {
  std::vector<const char*> inputs(input_names);
  std::vector<const char*> outputs(output_names);
  std::vector<OrtOpAttr*> attrs(attributes);
  return CreateNode(api, operator_name, node_name, inputs, outputs, attrs, domain_name);
}
}  // namespace
 
struct TestAllocator : public OrtAllocator {
  TestAllocator() {
    version = ORT_API_VERSION;
    Info = [](const struct OrtAllocator* this_ptr) -> const struct OrtMemoryInfo* {
      auto* test_allocator = static_cast<const TestAllocator*>(this_ptr);
      return test_allocator->memory_info;
    };
 
    Free = [](struct OrtAllocator* allocator, void* p) -> void {
      auto* test_allocator = static_cast<TestAllocator*>(allocator);
      // find the matching pointer and remove it
      auto it = std::find_if(test_allocator->weights.begin(), test_allocator->weights.end(),
                             [p](const std::unique_ptr<std::vector<float>>& v) { return v->data() == p; });
      if (it == test_allocator->weights.end()) {
        throw std::runtime_error("Free called with unknown pointer");
      }
 
      test_allocator->weights.erase(it);
    };
 
    Alloc = [](struct OrtAllocator* /*this*/, size_t /*size*/) -> void* {
      throw std::runtime_error("This should not be used");
    };
 
    Reserve = [](struct OrtAllocator* /*this*/, size_t /*size*/) -> void* {
      throw std::runtime_error("This should not be used");
    };
 
    GetStats = nullptr;
    AllocOnStream = nullptr;
    Shrink = nullptr;
  }
 
  // initializers that are used directly by the model. as there's no copy they must remain valid.
  // we store them in the test allocator so we can validate that Free is called
  std::vector<std::unique_ptr<std::vector<float>>> weights;
  Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu(OrtAllocatorType::OrtDeviceAllocator,
                                                           OrtMemType::OrtMemTypeDefault);
};
 
// Test the ModelEditorAPI C api
// Uses the ORT C++ api for the rest for simplicity
TEST(ModelEditorAPITest, Basic_CApi) {
  const auto& api = Ort::GetApi();
  const auto& model_editor_api = Ort::GetModelEditorApi();
 
  TestAllocator deleter;
 
  // return void so we can use ASSERT_* in the lambda
  const auto build_model = [&](bool use_constant_node, OrtModel*& model) -> void {
    OrtGraph* graph = nullptr;
    Ort::ThrowOnError(model_editor_api.CreateGraph(&graph));
 
    //
    // Create OrtModel with a Gemm. X input is 3x4, Y input is 4x8, Z output is 3x8.
    // X is model input. Y is initializer.
    // Set the alpha attribute of the Gemm node to 2.0 to test attribute handling.
    //
 
    // model input
    OrtTensorTypeAndShapeInfo* tensor_type_info = nullptr;
    std::vector<int64_t> input_dims = {3, 4};
    // can use api.SetSymbolicDimensions to set symbolic dimensions.
    // the input array should have the same rank as the call to SetDimensions.
    // e.g. call SetDimensions with {-1, 3, 2} and SetSymbolicDimensions with {"N", nullptr, nullptr} to create
    //      a shape of {"N", 3, 2}
 
    Ort::ThrowOnError(api.CreateTensorTypeAndShapeInfo(&tensor_type_info));
    Ort::ThrowOnError(api.SetTensorElementType(tensor_type_info, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT));
    Ort::ThrowOnError(api.SetDimensions(tensor_type_info, input_dims.data(), input_dims.size()));
 
    OrtTypeInfo* input_type_info = nullptr;
    Ort::ThrowOnError(model_editor_api.CreateTensorTypeInfo(tensor_type_info, &input_type_info));
    api.ReleaseTensorTypeAndShapeInfo(tensor_type_info);  // input_type_info took a copy
 
    // create ValueInfo and release the type info as CreateValueInfo takes a copy.
    OrtValueInfo* input_value_info = nullptr;
    Ort::ThrowOnError(model_editor_api.CreateValueInfo("X", input_type_info, &input_value_info));
    api.ReleaseTypeInfo(input_type_info);  // input_value_info took a copy
    tensor_type_info = nullptr;
 
    // model outputs
    OrtTypeInfo* output_type_info = nullptr;
    std::vector<int64_t> output_dims = {3, 8};
 
    Ort::ThrowOnError(api.CreateTensorTypeAndShapeInfo(&tensor_type_info));
    Ort::ThrowOnError(api.SetTensorElementType(tensor_type_info, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT));
    Ort::ThrowOnError(api.SetDimensions(tensor_type_info, output_dims.data(), output_dims.size()));
 
    Ort::ThrowOnError(model_editor_api.CreateTensorTypeInfo(tensor_type_info, &output_type_info));
    api.ReleaseTensorTypeAndShapeInfo(tensor_type_info);  // input_type_info took a copy
 
    OrtValueInfo* output_value_info = nullptr;
    Ort::ThrowOnError(model_editor_api.CreateValueInfo("Z", output_type_info, &output_value_info));
    api.ReleaseTypeInfo(output_type_info);
 
    std::vector<OrtValueInfo*> graph_inputs = {input_value_info};
    std::vector<OrtValueInfo*> graph_outputs = {output_value_info};
    Ort::ThrowOnError(model_editor_api.SetGraphInputs(graph, graph_inputs.data(), graph_inputs.size()));
    Ort::ThrowOnError(model_editor_api.SetGraphOutputs(graph, graph_outputs.data(), graph_outputs.size()));
    input_value_info = nullptr;  // graph now owns the input/output values
    output_value_info = nullptr;
 
    //
    // Gemm node
    //
 
    OrtOpAttr* alpha_attr = nullptr;
    float alpha_value = 2.0;
    Ort::ThrowOnError(api.CreateOpAttr("alpha", &alpha_value, 1, OrtOpAttrType::ORT_OP_ATTR_FLOAT, &alpha_attr));
 
    std::vector<const char*> node_input_names = {"X", "Y"};
    const std::string gemm_output_name = use_constant_node ? "Z_temp" : "Z";
    std::vector<const char*> node_output_names = {gemm_output_name.c_str()};
    std::vector<OrtOpAttr*> node_attributes{alpha_attr};
    OrtNode* node = CreateNode(model_editor_api, "Gemm", "Gemm1", node_input_names, node_output_names, node_attributes);
    alpha_attr = nullptr;  // Node now owns
 
    Ort::ThrowOnError(model_editor_api.AddNodeToGraph(graph, node));
    node = nullptr;  // graph now owns node
 
    // Y input
    // As it's 128 bytes it could either be allocated using CreateTensorAsOrtValue or use existing memory.
    // Under 128 bytes must use CreateTensorAsOrtValue.
    std::vector<int64_t> y_dims = {4, 8};
 
    deleter.weights.emplace_back(std::make_unique<std::vector<float>>(32));
    auto& y_values = *deleter.weights.back();
    std::iota(y_values.begin(), y_values.end(), 1.0f);
 
    // create an initializer for the Y input. add to `weights` so the memory remains valid.
    OrtValue* y_tensor = nullptr;
    Ort::ThrowOnError(
        api.CreateTensorWithDataAndDeleterAsOrtValue(&deleter,
                                                     y_values.data(), y_values.size() * sizeof(y_values[0]),
                                                     y_dims.data(), y_dims.size(),
                                                     ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT,
                                                     &y_tensor));
 
    Ort::ThrowOnError(model_editor_api.AddInitializerToGraph(graph, "Y", y_tensor, /*data is external*/ true));
    y_tensor = nullptr;  // graph now owns
 
    if (use_constant_node) {
      // Test that a Constant node is converted to an initializer
 
      // create Constant nodes for min/max to limit output range
      OrtOpAttr* min_attr = nullptr;
      float min = 400.0f;
      Ort::ThrowOnError(api.CreateOpAttr("value", &min, sizeof(min), ORT_OP_ATTR_FLOAT, &min_attr));
      node = CreateNode(model_editor_api, "Constant", "clip_min", {}, {"min"}, {min_attr});
      Ort::ThrowOnError(model_editor_api.AddNodeToGraph(graph, node));
      node = nullptr;  // graph now owns node
 
      OrtOpAttr* max_attr = nullptr;
      float max = 900.0f;
      Ort::ThrowOnError(api.CreateOpAttr("value", &max, sizeof(max), ORT_OP_ATTR_FLOAT, &max_attr));
      node = CreateNode(model_editor_api, "Constant", "clip_max", {}, {"max"}, {max_attr});
      Ort::ThrowOnError(model_editor_api.AddNodeToGraph(graph, node));
      node = nullptr;  // graph now owns node
 
      node = CreateNode(model_editor_api, "Clip", "Clip1", {gemm_output_name.c_str(), "min", "max"}, {"Z"});
      Ort::ThrowOnError(model_editor_api.AddNodeToGraph(graph, node));
      node = nullptr;  // graph now owns node
    }
 
    // Normal usage would be to add kOnnxDomain. We use the alias to test the implementation converts to kOnnxDomain.
    // std::vector<const char*> domain_names = {onnxruntime::kOnnxDomain};
    std::vector<const char*> domain_names = {onnxruntime::kOnnxDomainAlias};
    std::vector<int> opset_versions = {18};
    Ort::ThrowOnError(model_editor_api.CreateModel(domain_names.data(), opset_versions.data(), domain_names.size(),
                                                   &model));
    Ort::ThrowOnError(model_editor_api.AddGraphToModel(model, graph));
    graph = nullptr;  // model now owns
  };
 
  auto run_test = [&](bool use_constant_node) -> void {
    OrtModel* model = nullptr;
    build_model(use_constant_node, model);
 
    ASSERT_NE(model, nullptr) << "build_model should have created a model";
 
    std::vector<Input<float>> inputs(1);
    auto& input = inputs[0];
    input.name = "X";
    input.dims = {3, 4};
    input.values = {1.0f, 2.0f, 3.0f, 4.0f,
                    8.0f, 7.0f, 6.0f, 5.0f,
                    9.0f, 3.0f, 5.0f, 7.0f};
 
    std::vector<int64_t> expected_dims = {3, 8};
 
    Ort::SessionOptions session_options;
    auto saved_model_path = ORT_TSTR("model_editor_test_output.onnx");
    session_options.SetOptimizedModelFilePath(saved_model_path);
 
    Model cxx_model(model);
    auto session = CreateSession(*ort_env, cxx_model, &session_options);
 
    std::vector<float> expected_output;
    if (use_constant_node) {
      // clipped with min 400 and max 900
      expected_output = {400.0f, 400.0f, 400.0f, 400.0f, 420.0f, 440.0f, 460.0f, 480.0f,
                         596.0f, 648.0f, 700.0f, 752.0f, 804.0f, 856.0f, 900.0f, 900.0f,
                         592.0f, 640.0f, 688.0f, 736.0f, 784.0f, 832.0f, 880.0f, 900.0f};
    } else {
      expected_output = {340.0f, 360.0f, 380.0f, 400.0f, 420.0f, 440.0f, 460.0f, 480.0f,
                         596.0f, 648.0f, 700.0f, 752.0f, 804.0f, 856.0f, 908.0f, 960.0f,
                         592.0f, 640.0f, 688.0f, 736.0f, 784.0f, 832.0f, 880.0f, 928.0f};
    }
 
    TestInference<float>(session, inputs, "Z", expected_dims, expected_output);
 
    api.ReleaseSession(session.release());
 
    ASSERT_EQ(deleter.weights.size(), size_t(0)) << "All weights should have been freed";
 
    // make sure the saved model can be loaded
    Ort::Session session2(*ort_env, saved_model_path, Ort::SessionOptions());
 
    // make sure entries for the internal domains were added to the opset imports in the saved model
    std::vector<char> buffer(std::filesystem::file_size(saved_model_path));
 
    std::ifstream file(saved_model_path, std::ios::binary);
    ASSERT_TRUE(file.read(buffer.data(), buffer.size()));
 
    std::string_view buffer_view(buffer.data(), buffer.size());
    ASSERT_NE(buffer_view.find(onnxruntime::kMSInternalNHWCDomain), std::string_view::npos);
    ASSERT_NE(buffer_view.find(onnxruntime::kMSNchwcDomain), std::string_view::npos);
  };
 
  run_test(false);
  run_test(true);  // use Constant node for initializer
}
 
TEST(ModelEditorAPITest, Basic_CxxApi) {
  // initializers that are used directly by the model. as there's no copy they must remain valid
  std::vector<std::unique_ptr<std::vector<float>>> weights;
 
  Ort::Graph graph;
 
  //
  // Create OrtModel with a Gemm. X input is 3x4, Y input is 4x8, Z output is 3x8.
  // X is model input. Y is initializer.
  // Set the alpha attribute of the Gemm node to 2.0 to test attribute handling.
  //
 
  std::vector<ValueInfo> graph_inputs;
  std::vector<ValueInfo> graph_outputs;
 
  // model input. it's {3, 4} but use a symbolic dim to test that works.
  std::vector<int64_t> input_dims({-1, 4});
  std::vector<std::string> input_symbolic_dims({"multiple_of_3", ""});
  TensorTypeAndShapeInfo input_tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT,
                                           input_dims,
                                           &input_symbolic_dims);
  auto input_type_info = TypeInfo::CreateTensorInfo(input_tensor_info.GetConst());
  graph_inputs.emplace_back("X", input_type_info.GetConst());
 
  // model outputs
  std::vector<int64_t> output_dims = {-1, 8};
  std::vector<std::string> output_symbolic_dims({"multiple_of_3", ""});
  TensorTypeAndShapeInfo output_tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT,
                                            output_dims,
                                            &output_symbolic_dims);
  auto output_type_info = TypeInfo::CreateTensorInfo(output_tensor_info.GetConst());
  graph_outputs.emplace_back("Z", output_type_info.GetConst());
 
  graph.SetInputs(graph_inputs);
  graph.SetOutputs(graph_outputs);
 
  //
  // Gemm node
  //
 
  std::vector<OpAttr> attributes;
  float alpha_value = 2.0;
  attributes.push_back(OpAttr("alpha", &alpha_value, 1, OrtOpAttrType::ORT_OP_ATTR_FLOAT));
 
  Node node("Gemm", onnxruntime::kOnnxDomain, "Gemm1", {"X", "Y"}, {"Z"}, attributes);
 
  graph.AddNode(node);
 
  // create an initializer for the Y input.
  // add to `weights` so it remains valid for the lifetime of the session and we can avoid copying the data.
  // As it's 128 bytes it could either be allocated using CreateTensorAsOrtValue or use existing memory.
  // Under 128 bytes must use CreateTensorAsOrtValue.
  std::vector<int64_t> y_dims = {4, 8};
 
  weights.emplace_back(std::make_unique<std::vector<float>>(32));
  auto& y_values = *weights.back();
  std::iota(y_values.begin(), y_values.end(), 1.0f);
 
  auto info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeDefault);
 
  // if you use this API the initializer data MUST remain valid for the lifetime of the InferenceSession
  auto y_tensor = Value::CreateTensor(info, y_values.data(), y_values.size(), y_dims.data(), y_dims.size());
  graph.AddInitializer("Y", y_tensor, /*data is external*/ true);
 
  std::vector<Model::DomainOpsetPair> opsets{{onnxruntime::kOnnxDomain, 18}};
  Model model(opsets);
  model.AddGraph(graph);
 
  std::vector<Input<float>> inputs(1);
  auto& input = inputs[0];
  input.name = "X";
  input.dims = {3, 4};
  input.values = {1.0f, 2.0f, 3.0f, 4.0f,
                  8.0f, 7.0f, 6.0f, 5.0f,
                  9.0f, 3.0f, 5.0f, 7.0f};
 
  std::vector<int64_t> expected_dims = {3, 8};
 
  auto session = CreateSession(*ort_env, model);
  TestInference<float>(session, inputs, "Z", expected_dims,
                       {340.0f, 360.0f, 380.0f, 400.0f, 420.0f, 440.0f, 460.0f, 480.0f,
                        596.0f, 648.0f, 700.0f, 752.0f, 804.0f, 856.0f, 908.0f, 960.0f,
                        592.0f, 640.0f, 688.0f, 736.0f, 784.0f, 832.0f, 880.0f, 928.0f});
}
 
TEST(ModelEditorAPITest, BasicModelEdit_CxxApi) {
  //
  // Load existing model
  // Add Cast to change the model input from float to int64
  // Update model inputs to match
  // Run
  //
 
  SessionOptions so;
 
  // Set this to save the model if you want to debug.
  // so.SetOptimizedModelFilePath(ORT_TSTR("model_builder_edited.onnx"));
 
  Session session = Session::CreateModelEditorSession(*ort_env, TSTR("testdata/mnist.onnx"), so);
 
  ASSERT_EQ(session.GetOpset(""), 8);  // ONNX domain is empty string
 
  // we augment the original model with nodes, initializers and the updated model inputs/outputs from this model.
  // the original graph is unchanged. nodes can be added before/after it. initializers can be added.
  // new nodes must conform to the original domain:opset of the model.
  // additional operator domain:opset pairs can be added.
  std::vector<Model::DomainOpsetPair> opsets;  // no additional opsets required
  Model model(opsets);
 
  std::vector<ValueInfo> graph_inputs = session.GetInputs();
  ASSERT_EQ(graph_inputs.size(), size_t(1));
  ASSERT_EQ(graph_inputs[0].TypeInfo().GetTensorTypeAndShapeInfo().GetElementType(),
            ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT);
 
  // typically this isn't needed. we replace this input but need to read info from it later on in the test
  // validation so we save the info locally to keep it accessible.
  auto orig_input_name = graph_inputs[0].GetName();
  auto input_shape = graph_inputs[0].TypeInfo().GetTensorTypeAndShapeInfo().GetShape();
  const std::string new_input_name = "Int64Input";
 
  // Add Cast node to convert input from float to int64
  std::vector<OpAttr> attributes;
  int64_t to = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT;
  attributes.push_back(OpAttr("to", &to, 1, OrtOpAttrType::ORT_OP_ATTR_INT));
 
  Ort::Node node("Cast", onnxruntime::kOnnxDomain, new_input_name, {"Int64Input"},
                 // the existing node will now consume the output from the Cast instead of a graph input
                 {orig_input_name},
                 attributes);
 
  // we're replacing the only input. the shape is the same but the name and data type change.
  TensorTypeAndShapeInfo input_tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64,
                                           input_shape);
  auto input_type_info = TypeInfo::CreateTensorInfo(input_tensor_info.GetConst());
  graph_inputs[0] = ValueInfo(new_input_name, input_type_info.GetConst());
 
  Graph graph;  // new info to augment the model with
 
  graph.AddNode(node);
  graph.SetInputs(graph_inputs);
 
  // the node we added does not require any new opsets.
  model.AddGraph(graph);
  session.FinalizeModelEditorSession(model, so);
 
  std::vector<Input<int64_t>> inputs(1);
  auto& input = inputs[0];
  input.name = new_input_name.c_str();
  input.dims = input_shape;
 
  auto num_values = std::accumulate(input.dims.begin(), input.dims.end(), int64_t(1), std::multiplies<int64_t>());
  input.values.resize(size_t(num_values));
  std::iota(input.values.begin(), input.values.end(), 1);
 
  std::vector<int64_t> expected_dims = {1, 10};
  std::vector<float> expected_output = {-48.5088f, -1040.2948f, -347.0959f, 101.7392f, 421.3352f,
                                        750.92145f, 231.5060f, -1694.4152f, 681.5623f, 378.1689f};
 
  TestInference<float>(session, inputs, session.GetOutputNames()[0].c_str(), expected_dims, expected_output);
 
  // double check with original model
  {
    SessionOptions expected_so;
    Session expected_session = Session(*ort_env, TSTR("testdata/mnist.onnx"), expected_so);
    std::vector<Input<float>> expected_inputs(1);
    auto& expected_input = expected_inputs[0];
    expected_input.name = orig_input_name.c_str();
    expected_input.dims = input_shape;
    expected_input.values.reserve(size_t(num_values));
    std::transform(input.values.begin(), input.values.end(), std::back_inserter(expected_input.values),
                   [&](int64_t value) { return float(value); });
 
    TestInference<float>(expected_session, expected_inputs, session.GetOutputNames()[0].c_str(),
                         expected_dims, expected_output);
  }
}
 
TEST(ModelEditorAPITest, InvalidDimension) {
  try {
    std::vector<int64_t> input_dims = {-2, 2};
    TensorTypeAndShapeInfo tensor_type_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT,
                                            input_dims);
    // invalid dim of -2 should cause exception
    TypeInfo::CreateTensorInfo(tensor_type_info.GetConst());
    FAIL() << "Expected exception for invalid dimension";
  } catch (const Ort::Exception& e) {
    ASSERT_STREQ(e.what(), "dim_values must be -1 (symbolic dimension) or larger.");
  }
}
 
TEST(ModelEditorAPITest, CreateInvalidModel_NoOpsets) {
  Ort::Graph graph;
  std::vector<ValueInfo> graph_inputs;
  std::vector<ValueInfo> graph_outputs;
 
  std::vector<int64_t> dims({4});
  TensorTypeAndShapeInfo tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, dims);
  auto type_info = TypeInfo::CreateTensorInfo(tensor_info.GetConst());
  graph_inputs.emplace_back("X", type_info.GetConst());
  graph_outputs.emplace_back("Z", type_info.GetConst());
 
  graph.SetInputs(graph_inputs);
  graph.SetOutputs(graph_outputs);
 
  Ort::Node node("Add", onnxruntime::kOnnxDomain, "Add1", {"X", "X"}, {"Z"});
 
  graph.AddNode(node);
 
  std::vector<Model::DomainOpsetPair> opsets;
  Model model(opsets);
  model.AddGraph(graph);
 
  try {
    auto session = CreateSession(*ort_env, model);
    FAIL();
  } catch (const Ort::Exception& e) {
    ASSERT_THAT(e.what(), ::testing::HasSubstr("The opset for the ONNX domain must be explicitly specified"));
  }
}
 
TEST(ModelEditorAPITest, CreateInvalidModel_MissingValue) {
  Ort::Graph graph;
 
  std::vector<ValueInfo> graph_inputs;
  std::vector<ValueInfo> graph_outputs;
 
  std::vector<int64_t> dims({4});
  TensorTypeAndShapeInfo tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, dims);
  auto type_info = TypeInfo::CreateTensorInfo(tensor_info.GetConst());
  graph_inputs.emplace_back("X", type_info.GetConst());
  graph_outputs.emplace_back("Z", type_info.GetConst());
 
  graph.SetInputs(graph_inputs);
  graph.SetOutputs(graph_outputs);
 
  Ort::Node node("Add", onnxruntime::kOnnxDomain, "Add1", {"X", "missing"}, {"Z"});
  graph.AddNode(node);
 
  std::vector<Model::DomainOpsetPair> opsets{{onnxruntime::kOnnxDomain, 18}};
  Model model(opsets);
  model.AddGraph(graph);
 
  try {
    auto session = CreateSession(*ort_env, model);
    FAIL();
  } catch (const Ort::Exception& e) {
    ASSERT_THAT(e.what(), ::testing::HasSubstr("Node input 'missing' is not a graph input, "
                                               "initializer, or output of a previous node."));
  }
}
 
TEST(ModelEditorAPITest, InvalidModelEdit) {
  // Add a node but make the edit invalid in various ways
  //   - add node but don't update graph inputs
  //   - add node with invalid domain
  const auto edit_model = [](bool invalid_domain) {
    SessionOptions so;
 
    // Set this to save the model if you want to debug.
    // so.SetOptimizedModelFilePath(ORT_TSTR("model_builder_edited.onnx"));
 
    Session session = Session::CreateModelEditorSession(*ort_env, TSTR("testdata/mnist.onnx"), so);
 
    ASSERT_EQ(session.GetOpset(""), 8);  // ONNX domain is empty string
 
    std::vector<Model::DomainOpsetPair> opsets;  // no additional opsets required
    Model model(opsets);
    Graph graph;  // new info to augment the model with
 
    const char* domain = invalid_domain ? "invalid_domain" : onnxruntime::kOnnxDomain;
 
    std::vector<ValueInfo> graph_inputs = session.GetInputs();
    ASSERT_EQ(graph_inputs.size(), size_t(1));
    ASSERT_EQ(graph_inputs[0].TypeInfo().GetTensorTypeAndShapeInfo().GetElementType(),
              ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT);
 
    const std::string new_input_name = "Int64Input";
 
    // Add Cast node to convert input from float to int64
    std::vector<OpAttr> attributes;
    int64_t to = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT;
    attributes.push_back(OpAttr("to", &to, 1, OrtOpAttrType::ORT_OP_ATTR_INT));
 
    Node node("Cast", domain, "NewInputNode", {new_input_name},
              // the existing node will now consume the output from the Cast instead of a graph input
              {graph_inputs[0].GetName()},
              attributes);
    graph.AddNode(node);
 
    if (invalid_domain) {
      // we're replacing the only input. the shape is the same but the name and data type change.
      TensorTypeAndShapeInfo input_tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64,
                                               graph_inputs[0].TypeInfo().GetTensorTypeAndShapeInfo().GetShape());
      auto input_type_info = TypeInfo::CreateTensorInfo(input_tensor_info.GetConst());
      graph_inputs[0] = ValueInfo(new_input_name, input_type_info.GetConst());
      graph.SetInputs(graph_inputs);
    } else {
      // model should be invalid as we didn't connect the new node up to the graph inputs
    }
 
    // the node we added does not require any new opsets.
    model.AddGraph(graph);
 
    try {
      session.FinalizeModelEditorSession(model, so);
      FAIL() << "Should have failed to resolve graph due to invalid edits.";
    } catch (const Ort::Exception& e) {
      if (invalid_domain) {
        ASSERT_THAT(e.what(), ::testing::HasSubstr("Error No opset import for domain 'invalid_domain'"));
      } else {
        ASSERT_THAT(e.what(), ::testing::HasSubstr("This is an invalid model"));
      }
    }
  };
 
  edit_model(false);
  edit_model(true);  // add node with invalid domain
}
 
TEST(ModelEditorAPITest, CreateTypeInfo) {
  const auto& api = Ort::GetApi();
  const auto& model_editor_api = Ort::GetModelEditorApi();
 
  TensorTypeAndShapeInfo base_tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT,
                                          {2, 4});
 
  OrtTypeInfo* base_tensor_type_info = nullptr;
  Ort::ThrowOnError(model_editor_api.CreateTensorTypeInfo(base_tensor_info, &base_tensor_type_info));
 
  ONNXType onnx_type = ONNX_TYPE_UNKNOWN;
  const OrtTensorTypeAndShapeInfo* tensor_info = nullptr;
  ONNXTensorElementDataType onnx_element_type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED;
 
  // sparse tensor
  OrtTypeInfo* sparse_tensor_type_info = nullptr;
  Ort::ThrowOnError(model_editor_api.CreateSparseTensorTypeInfo(base_tensor_info, &sparse_tensor_type_info));
  Ort::ThrowOnError(api.GetOnnxTypeFromTypeInfo(sparse_tensor_type_info, &onnx_type));
  ASSERT_EQ(onnx_type, ONNXType::ONNX_TYPE_SPARSETENSOR);
  Ort::ThrowOnError(api.CastTypeInfoToTensorInfo(sparse_tensor_type_info, &tensor_info));
  Ort::ThrowOnError(api.GetTensorElementType(tensor_info, &onnx_element_type));
  ASSERT_EQ(onnx_element_type, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT);
  api.ReleaseTypeInfo(sparse_tensor_type_info);
 
  // sequence
  OrtTypeInfo* sequence_type_info = nullptr;
  const OrtSequenceTypeInfo* sequence_info = nullptr;
  OrtTypeInfo* sequence_element_type_info = nullptr;
 
  Ort::ThrowOnError(model_editor_api.CreateSequenceTypeInfo(base_tensor_type_info, &sequence_type_info));
  Ort::ThrowOnError(api.GetOnnxTypeFromTypeInfo(sequence_type_info, &onnx_type));
  ASSERT_EQ(onnx_type, ONNXType::ONNX_TYPE_SEQUENCE);
  Ort::ThrowOnError(api.CastTypeInfoToSequenceTypeInfo(sequence_type_info, &sequence_info));
  Ort::ThrowOnError(api.GetSequenceElementType(sequence_info, &sequence_element_type_info));
  Ort::ThrowOnError(api.GetOnnxTypeFromTypeInfo(sequence_element_type_info, &onnx_type));
  ASSERT_EQ(onnx_type, ONNXType::ONNX_TYPE_TENSOR);
  Ort::ThrowOnError(api.CastTypeInfoToTensorInfo(sequence_element_type_info, &tensor_info));
  Ort::ThrowOnError(api.GetTensorElementType(tensor_info, &onnx_element_type));
  ASSERT_EQ(onnx_element_type, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT);
  api.ReleaseTypeInfo(sequence_element_type_info);
  api.ReleaseTypeInfo(sequence_type_info);
 
  // map
  OrtTypeInfo* map_type_info = nullptr;
  const OrtMapTypeInfo* map_info = nullptr;
  ONNXTensorElementDataType map_key_type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED;
  OrtTypeInfo* map_value_type_info = nullptr;
  Ort::ThrowOnError(model_editor_api.CreateMapTypeInfo(ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64, base_tensor_type_info,
                                                       &map_type_info));  // clones map_type_info
  Ort::ThrowOnError(api.GetOnnxTypeFromTypeInfo(map_type_info, &onnx_type));
  ASSERT_EQ(onnx_type, ONNXType::ONNX_TYPE_MAP);
  Ort::ThrowOnError(api.CastTypeInfoToMapTypeInfo(map_type_info, &map_info));
  Ort::ThrowOnError(api.GetMapKeyType(map_info, &map_key_type));
  ASSERT_EQ(map_key_type, ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64);
  Ort::ThrowOnError(api.GetMapValueType(map_info, &map_value_type_info));
  Ort::ThrowOnError(api.GetOnnxTypeFromTypeInfo(map_value_type_info, &onnx_type));
  ASSERT_EQ(onnx_type, ONNXType::ONNX_TYPE_TENSOR);
  Ort::ThrowOnError(api.CastTypeInfoToTensorInfo(map_value_type_info, &tensor_info));
  Ort::ThrowOnError(api.GetTensorElementType(tensor_info, &onnx_element_type));
  ASSERT_EQ(onnx_element_type, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT);
  api.ReleaseTypeInfo(map_value_type_info);
  api.ReleaseTypeInfo(map_type_info);
 
  // optional
  OrtTypeInfo* optional_type_info = nullptr;
  const OrtOptionalTypeInfo* optional_info = nullptr;
  OrtTypeInfo* optional_contained_type_info = nullptr;
  Ort::ThrowOnError(model_editor_api.CreateOptionalTypeInfo(base_tensor_type_info, &optional_type_info));
  Ort::ThrowOnError(api.GetOnnxTypeFromTypeInfo(optional_type_info, &onnx_type));
  ASSERT_EQ(onnx_type, ONNXType::ONNX_TYPE_OPTIONAL);
  Ort::ThrowOnError(api.CastTypeInfoToOptionalTypeInfo(optional_type_info, &optional_info));
  Ort::ThrowOnError(api.GetOptionalContainedTypeInfo(optional_info, &optional_contained_type_info));
  Ort::ThrowOnError(api.GetOnnxTypeFromTypeInfo(optional_contained_type_info, &onnx_type));
  ASSERT_EQ(onnx_type, ONNXType::ONNX_TYPE_TENSOR);
  api.ReleaseTypeInfo(optional_contained_type_info);
  api.ReleaseTypeInfo(optional_type_info);
 
  api.ReleaseTypeInfo(base_tensor_type_info);
}
 
//
// Tests for Model Editor API + Compile API integration
//
 
namespace {
// Helper to create a simple model for testing with Model Editor API
// Creates a model with a Gemm operation: Z = X * Y where X is input and Y is initializer
Ort::Model CreateSimpleGemmModel(std::vector<std::unique_ptr<std::vector<float>>>& weights) {
  Ort::Graph graph;
 
  std::vector<ValueInfo> graph_inputs;
  std::vector<ValueInfo> graph_outputs;
 
  // Input: X is 3x4
  std::vector<int64_t> input_dims({3, 4});
  TensorTypeAndShapeInfo input_tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT,
                                           input_dims);
  auto input_type_info = TypeInfo::CreateTensorInfo(input_tensor_info.GetConst());
  graph_inputs.emplace_back("X", input_type_info.GetConst());
 
  // Output: Z is 3x8
  std::vector<int64_t> output_dims = {3, 8};
  TensorTypeAndShapeInfo output_tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT,
                                            output_dims);
  auto output_type_info = TypeInfo::CreateTensorInfo(output_tensor_info.GetConst());
  graph_outputs.emplace_back("Z", output_type_info.GetConst());
 
  graph.SetInputs(graph_inputs);
  graph.SetOutputs(graph_outputs);
 
  // Gemm node with alpha=2.0
  std::vector<OpAttr> attributes;
  float alpha_value = 2.0;
  attributes.push_back(OpAttr("alpha", &alpha_value, 1, OrtOpAttrType::ORT_OP_ATTR_FLOAT));
 
  Node node("Gemm", onnxruntime::kOnnxDomain, "Gemm1", {"X", "Y"}, {"Z"}, attributes);
  graph.AddNode(node);
 
  // Y initializer: 4x8
  std::vector<int64_t> y_dims = {4, 8};
  weights.emplace_back(std::make_unique<std::vector<float>>(32));
  auto& y_values = *weights.back();
  std::iota(y_values.begin(), y_values.end(), 1.0f);
 
  auto info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeDefault);
  auto y_tensor = Value::CreateTensor(info, y_values.data(), y_values.size(), y_dims.data(), y_dims.size());
  graph.AddInitializer("Y", y_tensor, /*data is external*/ true);
 
  std::vector<Model::DomainOpsetPair> opsets{{onnxruntime::kOnnxDomain, 18}};
  Model model(opsets);
  model.AddGraph(graph);
 
  return model;
}
 
// Helper to run inference on the simple Gemm model and verify all output values.
// Model is Z = 2.0 * X * Y where X is 3x4 (all ones) and Y is 4x8 (iota 1..32).
// Expected output: each row is 2 * column_sums_of_Y = {104, 112, 120, 128, 136, 144, 152, 160}.
void RunAndVerifySimpleGemmModel(const Ort::Model& model) {
  Ort::SessionOptions session_options;
  Ort::Session session(*ort_env, model, session_options);
  ASSERT_EQ(session.GetInputCount(), 1u);
  ASSERT_EQ(session.GetOutputCount(), 1u);
 
  std::vector<float> input_data(3 * 4, 1.0f);
  std::vector<int64_t> input_dims = {3, 4};
  auto memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeDefault);
  auto input_tensor = Ort::Value::CreateTensor<float>(memory_info, input_data.data(), input_data.size(),
                                                      input_dims.data(), input_dims.size());
 
  const char* input_names[] = {"X"};
  const char* output_names[] = {"Z"};
  auto outputs = session.Run(Ort::RunOptions{}, input_names, &input_tensor, 1, output_names, 1);
  ASSERT_EQ(outputs.size(), 1u);
  ASSERT_TRUE(outputs[0].IsTensor());
 
  auto output_shape = outputs[0].GetTensorTypeAndShapeInfo().GetShape();
  ASSERT_EQ(output_shape, (std::vector<int64_t>{3, 8}));
 
  const float* output_data = outputs[0].GetTensorData<float>();
  // alpha=2.0, X is all ones, so each output row = 2 * sum of each column of Y (iota 1..32 in 4x8)
  const std::vector<float> expected_row = {104.0f, 112.0f, 120.0f, 128.0f, 136.0f, 144.0f, 152.0f, 160.0f};
  for (int row = 0; row < 3; ++row) {
    for (int col = 0; col < 8; ++col) {
      EXPECT_FLOAT_EQ(output_data[row * 8 + col], expected_row[col])
          << "Mismatch at row=" << row << " col=" << col;
    }
  }
}
}  // namespace
 
// Test basic compilation from OrtModel
TEST(ModelEditorCompileAPITest, BasicCompileFromOrtModel) {
  std::vector<std::unique_ptr<std::vector<float>>> weights;
  auto model = CreateSimpleGemmModel(weights);
 
  Ort::SessionOptions session_options;
  Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
 
  // Set the OrtModel as input
  compile_options.SetInputModel(static_cast<const OrtModel*>(model));
 
  // Set output to buffer - use embed mode for simplicity
  compile_options.SetEpContextEmbedMode(true);
 
  std::unique_ptr<MockedOrtAllocator> allocator = std::make_unique<MockedOrtAllocator>();
  void* output_buffer = nullptr;
  size_t output_size = 0;
  compile_options.SetOutputModelBuffer(allocator.get(), &output_buffer, &output_size);
 
  // Compile should succeed (note: may not produce EPContext nodes without specific EP, but validation passes)
  ASSERT_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
 
  // Verify output was produced
  EXPECT_NE(output_buffer, nullptr);
  EXPECT_GT(output_size, 0u);
 
  // Cleanup
  if (output_buffer != nullptr) {
    allocator->Free(output_buffer);
  }
 
  // Verify the model still produces correct inference results after compilation
  RunAndVerifySimpleGemmModel(model);
}
TEST(ModelEditorCompileAPITest, CompileFromNullModel_Fails) {
  Ort::SessionOptions session_options;
  Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
 
  try {
    compile_options.SetInputModel(nullptr);
    FAIL() << "Expected exception for null model pointer";
  } catch (const Ort::Exception& e) {
    EXPECT_THAT(e.what(), ::testing::HasSubstr("null"));
  }
}
 
// Test validation: model with no graph
TEST(ModelEditorCompileAPITest, CompileFromModelWithNoGraph_Fails) {
  // Create a model but don't add a graph
  std::vector<Model::DomainOpsetPair> opsets{{onnxruntime::kOnnxDomain, 18}};
  Model model(opsets);
 
  Ort::SessionOptions session_options;
  Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
 
  compile_options.SetInputModel(static_cast<const OrtModel*>(model));
  compile_options.SetEpContextEmbedMode(true);
 
  std::unique_ptr<MockedOrtAllocator> allocator = std::make_unique<MockedOrtAllocator>();
  void* output_buffer = nullptr;
  size_t output_size = 0;
  compile_options.SetOutputModelBuffer(allocator.get(), &output_buffer, &output_size);
 
  Ort::Status status = Ort::CompileModel(*ort_env, compile_options);
  EXPECT_FALSE(status.IsOK()) << "Expected CompileModel to fail for model with no graph";
  EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("graph"));
}
 
// Test validation: model with no outputs (one input but zero outputs).
// 0 outputs is still rejected because compilation produces an output model that
// would have no consumers for any computed values.
TEST(ModelEditorCompileAPITest, CompileFromModelWithEmptyOutputs_Fails) {
  Ort::Graph graph;
 
  // Provide a single input but no outputs, to isolate the output-count check.
  std::vector<ValueInfo> graph_inputs;
  std::vector<int64_t> dims({4});
  TensorTypeAndShapeInfo tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, dims);
  auto type_info = TypeInfo::CreateTensorInfo(tensor_info.GetConst());
  graph_inputs.emplace_back("X", type_info.GetConst());
  graph.SetInputs(graph_inputs);
  // Intentionally do not call SetOutputs.
 
  std::vector<Model::DomainOpsetPair> opsets{{onnxruntime::kOnnxDomain, 18}};
  Model model(opsets);
  model.AddGraph(graph);
 
  Ort::SessionOptions session_options;
  Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
 
  compile_options.SetInputModel(static_cast<const OrtModel*>(model));
  compile_options.SetEpContextEmbedMode(true);
 
  std::unique_ptr<MockedOrtAllocator> allocator = std::make_unique<MockedOrtAllocator>();
  void* output_buffer = nullptr;
  size_t output_size = 0;
  compile_options.SetOutputModelBuffer(allocator.get(), &output_buffer, &output_size);
 
  Ort::Status status = Ort::CompileModel(*ort_env, compile_options);
  EXPECT_FALSE(status.IsOK()) << "Expected CompileModel to fail for model with no outputs";
  EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("at least one output"));
}
 
// Test: model with zero graph inputs is now accepted by CompileModel.
// Mirrors what CreateSessionFromModel already accepts (e.g., a graph composed of
// zero-input generator ops like RandomNormal that produces output without external input).
// Regression test for https://github.com/microsoft/onnxruntime/issues/28135.
//
// Scope: this test exercises only the ORT-side validation in ModelCompilationOptions::Check().
// EP-specific validation (e.g., whether the WebNN EP's partitioner accepts a 0-input subgraph)
// is owned by the respective EP and is not covered here.
TEST(ModelEditorCompileAPITest, CompileFromModelWithEmptyInputs_Succeeds) {
  Ort::Graph graph;
 
  // Zero graph inputs; one graph output produced by a RandomNormal node.
  // RandomNormal takes 0 inputs and produces a tensor with shape specified via attribute.
  // Use RandomNormal rather than Constant because Constant nodes are folded into initializers
  // at load time (see graph.cc Graph::LoadFromModelEditorApiModel) and would not exercise
  // the true 0-input producer path.
  std::vector<int64_t> output_dims = {2, 3};
  TensorTypeAndShapeInfo output_tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT,
                                            output_dims);
  auto output_type_info = TypeInfo::CreateTensorInfo(output_tensor_info.GetConst());
 
  std::vector<ValueInfo> graph_outputs;
  graph_outputs.emplace_back("Y", output_type_info.GetConst());
  graph.SetOutputs(graph_outputs);
  // Intentionally do not call SetInputs (zero graph inputs).
 
  std::vector<OpAttr> attributes;
  std::vector<int64_t> shape_attr_value = {2, 3};
  attributes.push_back(OpAttr("shape", shape_attr_value.data(),
                              static_cast<int>(shape_attr_value.size()),
                              OrtOpAttrType::ORT_OP_ATTR_INTS));
 
  Node node("RandomNormal", onnxruntime::kOnnxDomain, "RandomNormal1",
            /*input_names*/ {}, /*output_names*/ {"Y"}, attributes);
  graph.AddNode(node);
 
  std::vector<Model::DomainOpsetPair> opsets{{onnxruntime::kOnnxDomain, 18}};
  Model model(opsets);
  model.AddGraph(graph);
 
  Ort::SessionOptions session_options;
  Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
 
  compile_options.SetInputModel(static_cast<const OrtModel*>(model));
  compile_options.SetEpContextEmbedMode(true);
 
  std::unique_ptr<MockedOrtAllocator> allocator = std::make_unique<MockedOrtAllocator>();
  void* output_buffer = nullptr;
  size_t output_size = 0;
  compile_options.SetOutputModelBuffer(allocator.get(), &output_buffer, &output_size);
 
  // Compile should succeed. No specific compiling EP is required; the default
  // kGenerateModel action emits an output model even when no EPContext nodes are produced.
  ASSERT_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
 
  // Fatal: a compile that returns OK but produces no artifact bytes is a regression.
  ASSERT_NE(output_buffer, nullptr);
  ASSERT_GT(output_size, 0u);
 
  allocator->Free(output_buffer);
}
 
// Test: model can be reused after compilation.
// NOTE: This is not an explicit API guarantee. It documents current behavior so that if a future change
// breaks model reuse, the regression is surfaced and can be evaluated.
TEST(ModelEditorCompileAPITest, ModelCanBeReusedAfterCompilation) {
  std::vector<std::unique_ptr<std::vector<float>>> weights;
  auto model = CreateSimpleGemmModel(weights);
 
  // First compilation
  {
    Ort::SessionOptions session_options;
    Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
    compile_options.SetInputModel(static_cast<const OrtModel*>(model));
    compile_options.SetEpContextEmbedMode(true);
 
    std::unique_ptr<MockedOrtAllocator> allocator = std::make_unique<MockedOrtAllocator>();
    void* output_buffer = nullptr;
    size_t output_size = 0;
    compile_options.SetOutputModelBuffer(allocator.get(), &output_buffer, &output_size);
 
    ASSERT_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
 
    if (output_buffer != nullptr) {
      allocator->Free(output_buffer);
    }
  }
 
  // Second compilation with same model
  {
    Ort::SessionOptions session_options;
    Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
    compile_options.SetInputModel(static_cast<const OrtModel*>(model));
    compile_options.SetEpContextEmbedMode(true);
 
    std::unique_ptr<MockedOrtAllocator> allocator = std::make_unique<MockedOrtAllocator>();
    void* output_buffer = nullptr;
    size_t output_size = 0;
    compile_options.SetOutputModelBuffer(allocator.get(), &output_buffer, &output_size);
 
    ASSERT_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
 
    if (output_buffer != nullptr) {
      allocator->Free(output_buffer);
    }
  }
 
  // Model should still be usable for creating a session and running inference
  RunAndVerifySimpleGemmModel(model);
}
 
// Test: SetInputModel overrides previous input source (file path)
TEST(ModelEditorCompileAPITest, SetInputModelOverridesPreviousInputPath) {
  std::vector<std::unique_ptr<std::vector<float>>> weights;
  auto model = CreateSimpleGemmModel(weights);
 
  Ort::SessionOptions session_options;
  Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
 
  // First set a file path (doesn't need to exist since we'll override it)
  compile_options.SetInputModelPath(ORT_TSTR("nonexistent_file.onnx"));
 
  // Then override with OrtModel
  compile_options.SetInputModel(static_cast<const OrtModel*>(model));
  compile_options.SetEpContextEmbedMode(true);
 
  std::unique_ptr<MockedOrtAllocator> allocator = std::make_unique<MockedOrtAllocator>();
  void* output_buffer = nullptr;
  size_t output_size = 0;
  compile_options.SetOutputModelBuffer(allocator.get(), &output_buffer, &output_size);
 
  // Should use the OrtModel, not the nonexistent file
  ASSERT_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
 
  if (output_buffer != nullptr) {
    allocator->Free(output_buffer);
  }
}
 
// Test: SetInputModelPath overrides previous OrtModel setting
TEST(ModelEditorCompileAPITest, SetInputModelPathOverridesPreviousModel) {
  std::vector<std::unique_ptr<std::vector<float>>> weights;
  auto model = CreateSimpleGemmModel(weights);
 
  Ort::SessionOptions session_options;
  Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
 
  // First set an OrtModel
  compile_options.SetInputModel(static_cast<const OrtModel*>(model));
 
  // Then override with a real file path
  compile_options.SetInputModelPath(ORT_TSTR("testdata/matmul_1.onnx"));
  compile_options.SetEpContextEmbedMode(true);
 
  std::unique_ptr<MockedOrtAllocator> allocator = std::make_unique<MockedOrtAllocator>();
  void* output_buffer = nullptr;
  size_t output_size = 0;
  compile_options.SetOutputModelBuffer(allocator.get(), &output_buffer, &output_size);
 
  // Should use the file path, not the OrtModel
  ASSERT_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
 
  if (output_buffer != nullptr) {
    allocator->Free(output_buffer);
  }
}
 
// Test: Compile with output to file
TEST(ModelEditorCompileAPITest, CompileFromOrtModelToFile) {
  std::vector<std::unique_ptr<std::vector<float>>> weights;
  auto model = CreateSimpleGemmModel(weights);
 
  auto output_path = ORT_TSTR("test_compile_from_ortmodel_output.onnx");
 
  Ort::SessionOptions session_options;
  Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
 
  compile_options.SetInputModel(static_cast<const OrtModel*>(model));
  compile_options.SetOutputModelPath(output_path);
  compile_options.SetEpContextEmbedMode(true);
 
  ASSERT_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
 
  // Verify output file exists
  EXPECT_TRUE(std::filesystem::exists(output_path));
 
  // Verify the output model can be loaded
  Ort::Session session(*ort_env, output_path, Ort::SessionOptions());
  EXPECT_GE(session.GetInputCount(), 1u);
  EXPECT_GE(session.GetOutputCount(), 1u);
 
  // Cleanup
  std::filesystem::remove(output_path);
}
 
// Test: Validation error for OrtModel with no model_path, no output location, and no embed mode.
TEST(ModelEditorCompileAPITest, NoOutputLocationNoModelPathFails) {
  std::vector<std::unique_ptr<std::vector<float>>> weights;
  auto model = CreateSimpleGemmModel(weights);
 
  Ort::SessionOptions session_options;
  Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
  compile_options.SetInputModel(static_cast<const OrtModel*>(model));
  // Intentionally do NOT call SetEpContextEmbedMode, SetOutputModelPath, or SetOutputModelBuffer
 
  Ort::Status status = Ort::CompileModel(*ort_env, compile_options);
  EXPECT_FALSE(status.IsOK());
  EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("output"));
}
 
// Test: Setting embed mode with buffer output satisfies the output location requirement
// for OrtModel with no model_path.
TEST(ModelEditorCompileAPITest, EmbedModeWithBufferOutputSatisfiesValidation) {
  std::vector<std::unique_ptr<std::vector<float>>> weights;
  auto model = CreateSimpleGemmModel(weights);
 
  Ort::SessionOptions session_options;
  Ort::ModelCompilationOptions compile_options(*ort_env, session_options);
  compile_options.SetInputModel(static_cast<const OrtModel*>(model));
  compile_options.SetEpContextEmbedMode(true);
 
  std::unique_ptr<MockedOrtAllocator> allocator = std::make_unique<MockedOrtAllocator>();
  void* output_buffer = nullptr;
  size_t output_size = 0;
  compile_options.SetOutputModelBuffer(allocator.get(), &output_buffer, &output_size);
 
  ASSERT_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options));
 
  if (output_buffer != nullptr) {
    allocator->Free(output_buffer);
  }
}
 
TEST(ModelEditorAPITest, CreateNode_DuplicateAttributePointer_Fails) {
  const auto& api = Ort::GetApi();
  const auto& model_editor_api = Ort::GetModelEditorApi();
 
  float alpha_value = 1.0f;
  OrtOpAttr* attr = nullptr;
  Ort::ThrowOnError(api.CreateOpAttr("alpha", &alpha_value, 1, ORT_OP_ATTR_FLOAT, &attr));
 
  std::vector<const char*> input_names = {"X"};
  std::vector<const char*> output_names = {"Y"};
  // Pass the same attribute pointer twice — should fail without releasing it
  std::vector<OrtOpAttr*> attrs = {attr, attr};
 
  OrtNode* node = nullptr;
  Ort::Status status{model_editor_api.CreateNode("Relu", onnxruntime::kOnnxDomain, "relu1",
                                                 input_names.data(), input_names.size(),
                                                 output_names.data(), output_names.size(),
                                                 attrs.data(), attrs.size(), &node)};
  EXPECT_FALSE(status.IsOK());
  EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("Duplicate"));
  EXPECT_EQ(node, nullptr);
 
  // Caller still owns the attribute since CreateNode failed before taking ownership
  api.ReleaseOpAttr(attr);
}
 
TEST(ModelEditorAPITest, CreateNode_NullAttributeEntry_Fails) {
  const auto& api = Ort::GetApi();
  const auto& model_editor_api = Ort::GetModelEditorApi();
 
  float alpha_value = 1.0f;
  OrtOpAttr* attr = nullptr;
  Ort::ThrowOnError(api.CreateOpAttr("alpha", &alpha_value, 1, ORT_OP_ATTR_FLOAT, &attr));
 
  std::vector<const char*> input_names = {"X"};
  std::vector<const char*> output_names = {"Y"};
  std::vector<OrtOpAttr*> attrs = {attr, nullptr};
 
  OrtNode* node = nullptr;
  Ort::Status status{model_editor_api.CreateNode("Relu", onnxruntime::kOnnxDomain, "relu1",
                                                 input_names.data(), input_names.size(),
                                                 output_names.data(), output_names.size(),
                                                 attrs.data(), attrs.size(), &node)};
  EXPECT_FALSE(status.IsOK());
  EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("null"));
  EXPECT_EQ(node, nullptr);
 
  api.ReleaseOpAttr(attr);
}
 
// Regression: passing the same OrtValue* twice to AddInitializerToGraph must be rejected.
// Without the duplicate-pointer guard, the graph would own two unique_ptrs to the same allocation
// and double-free on destruction.
TEST(ModelEditorAPITest, AddInitializerToGraph_DuplicatePointer_Fails) {
  const auto& model_editor_api = Ort::GetModelEditorApi();
 
  Ort::Graph graph;
 
  // Create a CPU tensor via the C++ API (RAII).
  std::vector<float> data(4, 0.0f);
  std::vector<int64_t> dims = {2, 2};
  auto memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeDefault);
  Ort::Value value = Ort::Value::CreateTensor<float>(memory_info, data.data(), data.size(),
                                                     dims.data(), dims.size());
 
  // First add transfers ownership of the raw OrtValue* to the graph. Detach the C++ wrapper
  // so it does not also try to release it on destruction.
  OrtValue* raw = value;
  Ort::ThrowOnError(model_editor_api.AddInitializerToGraph(graph, "W1", raw, /*data_is_external*/ false));
  static_cast<void>(value.release());
 
  // Second add of the same raw pointer (under a different name) must fail without taking ownership.
  Ort::Status status{model_editor_api.AddInitializerToGraph(graph, "W2", raw, /*data_is_external*/ false)};
  EXPECT_FALSE(status.IsOK());
  EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("already been added"));
}
 
// Regression: passing the same OrtNode* twice to AddNodeToGraph must be rejected.
TEST(ModelEditorAPITest, AddNodeToGraph_DuplicatePointer_Fails) {
  const auto& model_editor_api = Ort::GetModelEditorApi();
 
  Ort::Graph graph;
  Ort::Node node("Relu", onnxruntime::kOnnxDomain, "relu1", {"X"}, {"Y"});
 
  // First add transfers ownership of the raw OrtNode* to the graph. Detach the C++ wrapper.
  OrtNode* raw = node;
  Ort::ThrowOnError(model_editor_api.AddNodeToGraph(graph, raw));
  static_cast<void>(node.release());
 
  // Second add of the same raw pointer must fail without taking ownership.
  Ort::Status status{model_editor_api.AddNodeToGraph(graph, raw)};
  EXPECT_FALSE(status.IsOK());
  EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("already been added"));
}
 
namespace {
// Helper: create a CPU OrtValue tensor of `num_floats` zero floats backed by `storage`.
// The returned Ort::Value owns only the OrtValue wrapper; the underlying buffer remains in
// `storage`, so the caller must keep `storage` alive for as long as the tensor may be accessed.
Ort::Value MakeCpuFloatTensor(std::vector<float>& storage, size_t num_floats,
                              const std::vector<int64_t>& dims) {
  storage.assign(num_floats, 0.0f);
  auto memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeDefault);
  return Ort::Value::CreateTensor<float>(memory_info, storage.data(), storage.size(),
                                         dims.data(), dims.size());
}
}  // namespace
 
// Reject a second initializer with the same name (within the regular initializer map).
TEST(ModelEditorAPITest, AddInitializerToGraph_DuplicateName_Fails) {
  const auto& model_editor_api = Ort::GetModelEditorApi();
  Ort::Graph graph;
 
  std::vector<float> storage_a, storage_b;
  Ort::Value a = MakeCpuFloatTensor(storage_a, 4, {2, 2});
  Ort::Value b = MakeCpuFloatTensor(storage_b, 4, {2, 2});
 
  OrtValue* raw_a = a;
  Ort::ThrowOnError(model_editor_api.AddInitializerToGraph(graph, "W", raw_a, /*data_is_external*/ false));
  static_cast<void>(a.release());
 
  OrtValue* raw_b = b;
  Ort::Status status{model_editor_api.AddInitializerToGraph(graph, "W", raw_b, /*data_is_external*/ false)};
  EXPECT_FALSE(status.IsOK());
  EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("name"));
  // Caller still owns `b` and Ort::Value's destructor releases it. No leak, no double-free.
}
 
// Reject a duplicate name that collides across the regular/external boundary.
TEST(ModelEditorAPITest, AddInitializerToGraph_DuplicateNameAcrossExternal_Fails) {
  const auto& model_editor_api = Ort::GetModelEditorApi();
  Ort::Graph graph;
 
  // First initializer: regular, small.
  std::vector<float> storage_small;
  Ort::Value small = MakeCpuFloatTensor(storage_small, 4, {2, 2});
  OrtValue* raw_small = small;
  Ort::ThrowOnError(model_editor_api.AddInitializerToGraph(graph, "W", raw_small,
                                                           /*data_is_external*/ false));
  static_cast<void>(small.release());
 
  // Second initializer: external, large enough to satisfy the size guard, same name.
  std::vector<float> storage_big;
  Ort::Value big = MakeCpuFloatTensor(storage_big, 64, {64});  // 256 bytes, > kSmallTensorExternalDataThreshold
  OrtValue* raw_big = big;
  Ort::Status status{model_editor_api.AddInitializerToGraph(graph, "W", raw_big,
                                                            /*data_is_external*/ true)};
  EXPECT_FALSE(status.IsOK());
  EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("name"));
}
 
// data_is_external=true with a tensor at or below kSmallTensorExternalDataThreshold must be rejected
// because the resulting in-memory external-data reference would be unusable by ONNX shape inferencing.
TEST(ModelEditorAPITest, AddInitializerToGraph_SmallExternal_Fails) {
  const auto& model_editor_api = Ort::GetModelEditorApi();
  Ort::Graph graph;
 
  std::vector<float> storage;
  Ort::Value small = MakeCpuFloatTensor(storage, 4, {2, 2});  // 16 bytes
  OrtValue* raw = small;
  Ort::Status status{model_editor_api.AddInitializerToGraph(graph, "W", raw,
                                                            /*data_is_external*/ true)};
  EXPECT_FALSE(status.IsOK());
  EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("data_is_external"));
  // Ownership not transferred; Ort::Value destructor releases `small`.
}
 
// AddInitializerToGraph rejects null arguments without taking ownership.
TEST(ModelEditorAPITest, AddInitializerToGraph_NullArgs_Fails) {
  const auto& model_editor_api = Ort::GetModelEditorApi();
  Ort::Graph graph;
 
  std::vector<float> storage;
  Ort::Value v = MakeCpuFloatTensor(storage, 4, {2, 2});
  OrtValue* raw = v;
 
  // Null graph.
  {
    Ort::Status status{model_editor_api.AddInitializerToGraph(nullptr, "W", raw, false)};
    EXPECT_FALSE(status.IsOK());
  }
  // Null name.
  {
    Ort::Status status{model_editor_api.AddInitializerToGraph(graph, nullptr, raw, false)};
    EXPECT_FALSE(status.IsOK());
  }
  // Empty name.
  {
    Ort::Status status{model_editor_api.AddInitializerToGraph(graph, "", raw, false)};
    EXPECT_FALSE(status.IsOK());
  }
  // Null tensor.
  {
    Ort::Status status{model_editor_api.AddInitializerToGraph(graph, "W", nullptr, false)};
    EXPECT_FALSE(status.IsOK());
  }
  // None of the above transferred ownership; Ort::Value destructor releases `v`.
}
 
// AddNodeToGraph rejects null arguments.
TEST(ModelEditorAPITest, AddNodeToGraph_NullArgs_Fails) {
  const auto& model_editor_api = Ort::GetModelEditorApi();
  Ort::Graph graph;
  Ort::Node node("Relu", onnxruntime::kOnnxDomain, "relu1", {"X"}, {"Y"});
 
  {
    Ort::Status status{model_editor_api.AddNodeToGraph(nullptr, node)};
    EXPECT_FALSE(status.IsOK());
  }
  {
    Ort::Status status{model_editor_api.AddNodeToGraph(graph, nullptr)};
    EXPECT_FALSE(status.IsOK());
  }
  // Ownership not transferred; Ort::Node destructor releases the node.
}
 
// AddGraphToModel rejects a second graph and rejects null arguments.
TEST(ModelEditorAPITest, AddGraphToModel_Twice_Fails) {
  const auto& model_editor_api = Ort::GetModelEditorApi();
 
  std::vector<const char*> domains = {onnxruntime::kOnnxDomain};
  std::vector<int> versions = {18};
  OrtModel* raw_model = nullptr;
  Ort::ThrowOnError(model_editor_api.CreateModel(domains.data(), versions.data(), domains.size(), &raw_model));
  Ort::Model model{raw_model};
 
  Ort::Graph g1;
  OrtGraph* raw_g1 = g1;
  Ort::ThrowOnError(model_editor_api.AddGraphToModel(model, raw_g1));
  static_cast<void>(g1.release());
 
  // Second AddGraphToModel must fail without taking ownership of g2.
  Ort::Graph g2;
  OrtGraph* raw_g2 = g2;
  Ort::Status status{model_editor_api.AddGraphToModel(model, raw_g2)};
  EXPECT_FALSE(status.IsOK());
  EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("graph"));
  // g2 destructor releases the still-owned raw_g2.
}
 
TEST(ModelEditorAPITest, AddGraphToModel_NullArgs_Fails) {
  const auto& model_editor_api = Ort::GetModelEditorApi();
 
  std::vector<const char*> domains = {onnxruntime::kOnnxDomain};
  std::vector<int> versions = {18};
  OrtModel* raw_model = nullptr;
  Ort::ThrowOnError(model_editor_api.CreateModel(domains.data(), versions.data(), domains.size(), &raw_model));
  Ort::Model model{raw_model};
 
  Ort::Graph graph;
 
  {
    Ort::Status status{model_editor_api.AddGraphToModel(nullptr, graph)};
    EXPECT_FALSE(status.IsOK());
  }
  {
    Ort::Status status{model_editor_api.AddGraphToModel(model, nullptr)};
    EXPECT_FALSE(status.IsOK());
  }
}
 
namespace {
// Build a CPU float `Ort::ValueInfo` of rank-1 shape {1} for the given name.
Ort::ValueInfo MakeFloatValueInfo(const char* name) {
  Ort::TensorTypeAndShapeInfo tts(ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, std::vector<int64_t>{1});
  Ort::TypeInfo ti = Ort::TypeInfo::CreateTensorInfo(tts.GetConst());
  return Ort::ValueInfo(name, ti.GetConst());
}
}  // namespace
 
// Reject the same OrtValueInfo* appearing twice within the SetGraphInputs array.
TEST(ModelEditorAPITest, SetGraphInputs_DuplicatePointerInArray_Fails) {
  const auto& model_editor_api = Ort::GetModelEditorApi();
 
  Ort::Graph graph;
  Ort::ValueInfo vi = MakeFloatValueInfo("X");
 
  // Implicit Base::operator T*() yields the raw pointer without releasing.
  OrtValueInfo* raw = vi;
  std::vector<OrtValueInfo*> inputs = {raw, raw};
  Ort::Status status{model_editor_api.SetGraphInputs(graph, inputs.data(), inputs.size())};
  EXPECT_FALSE(status.IsOK());
  EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("Duplicate"));
  EXPECT_NE(inputs[0], nullptr);  // ownership not transferred on failure
  EXPECT_NE(inputs[1], nullptr);
 
  // `vi` destructor releases the still-owned OrtValueInfo. No double-free.
}
 
// Reject the same OrtValueInfo* appearing twice within the SetGraphOutputs array.
TEST(ModelEditorAPITest, SetGraphOutputs_DuplicatePointerInArray_Fails) {
  const auto& model_editor_api = Ort::GetModelEditorApi();
 
  Ort::Graph graph;
  Ort::ValueInfo vi = MakeFloatValueInfo("Y");
 
  OrtValueInfo* raw = vi;
  std::vector<OrtValueInfo*> outputs = {raw, raw};
  Ort::Status status{model_editor_api.SetGraphOutputs(graph, outputs.data(), outputs.size())};
  EXPECT_FALSE(status.IsOK());
  EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("Duplicate"));
  EXPECT_NE(outputs[0], nullptr);
  EXPECT_NE(outputs[1], nullptr);
}
 
// Reject reusing an OrtValueInfo* already owned by the graph (input -> output).
TEST(ModelEditorAPITest, SetGraph_RejectsAlreadyOwnedPointer) {
  const auto& model_editor_api = Ort::GetModelEditorApi();
 
  Ort::Graph graph;
  Ort::ValueInfo input_vi = MakeFloatValueInfo("X");
 
  // Transfer to graph as an input via the C++ wrapper (which calls release() on success).
  OrtValueInfo* still_owned_by_graph = input_vi;  // capture before release()
  std::vector<Ort::ValueInfo> inputs;
  inputs.emplace_back(std::move(input_vi));
  graph.SetInputs(inputs);
 
  // Re-using the same raw pointer (now owned by graph) as an output must be rejected.
  std::vector<OrtValueInfo*> outputs = {still_owned_by_graph};
  Ort::Status status{model_editor_api.SetGraphOutputs(graph, outputs.data(), outputs.size())};
  EXPECT_FALSE(status.IsOK());
  EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("already been added"));
  EXPECT_NE(outputs[0], nullptr);  // ownership not transferred on failure
  // graph still owns the pointer; Graph destructor releases it.
}