Исходный код СУБД 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
namespace Microsoft.ML.OnnxRuntime
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
 
    /// <summary>
    /// Flags representing options to enable when compiling a model.
    /// Matches OrtCompileApiFlags in the ORT C API.
    /// </summary>
    [Flags]
    public enum OrtCompileApiFlags : uint
    {
        NONE = 0,
        ERROR_IF_NO_NODES_COMPILED = 1 << 0,
        ERROR_IF_OUTPUT_FILE_EXISTS = 1 << 1,
    }
 
    /// <summary>
    /// This class is used to set options for model compilation, and to produce a compiled model using those options.
    /// See https://onnxruntime.ai/docs/api/c/ for further details of various options.
    /// </summary>
    public class OrtModelCompilationOptions : IDisposable
    {
        /// <summary>
        /// Create a new OrtModelCompilationOptions object from SessionOptions.
        /// </summary>
        /// <remarks>By default, the GraphOptimizationLevel is set to ORT_DISABLE_ALL. Use SetGraphOptimizationLevel()
        /// to enable graph optimizations.</remarks>
        /// <param name="sessionOptions">SessionOptions instance to read settings from.</param>
        public OrtModelCompilationOptions(SessionOptions sessionOptions)
        {
            _epContextDataReadRegistration =
                sessionOptions.InvokeWithEpContextDataReadRegistration(sessionOptionsHandle =>
                {
                    NativeApiStatus.VerifySuccess(
                        NativeMethods.CompileApi.OrtCreateModelCompilationOptionsFromSessionOptions(
                            OrtEnv.Instance().Handle, sessionOptionsHandle, out _handle));
                });
        }
 
        /// <summary>
        /// Compile the model using the options set in this object.
        /// </summary>
        public void CompileModel()
        {
            lock (_epContextDataWriteRegistrationLock)
            {
                if (_activeCompileCount == 0)
                {
                    ApplyPendingEpContextDataWriteRegistration();
                }
                ++_activeCompileCount;
            }
 
            try
            {
                NativeApiStatus.VerifySuccess(
                    NativeMethods.CompileApi.OrtCompileModel(OrtEnv.Instance().Handle, _handle));
            }
            finally
            {
                lock (_epContextDataWriteRegistrationLock)
                {
                    if (--_activeCompileCount == 0)
                    {
                        ApplyPendingEpContextDataWriteRegistration();
                    }
                }
                GC.KeepAlive(this);
            }
        }
 
 
        /// <summary>
        /// Set the input model to compile.
        /// </summary>
        /// <param name="path">Path to ONNX model to compile.</param>
        public void SetInputModelPath(string path)
        {
            var platformPath = NativeOnnxValueHelper.GetPlatformSerializedString(path);
            NativeApiStatus.VerifySuccess(
                NativeMethods.CompileApi.OrtModelCompilationOptions_SetInputModelPath(_handle, platformPath));
        }
 
        /// <summary>
        /// Set the input model to compile to be a byte array.
        /// The input bytes are NOT copied and must remain valid while in use by ORT.
        /// </summary>
        /// <param name="buffer">Input model bytes.</param>
        public void SetInputModelFromBuffer(byte[] buffer)
        {
            NativeApiStatus.VerifySuccess(
                NativeMethods.CompileApi.OrtModelCompilationOptions_SetInputModelFromBuffer(
                    _handle, buffer, (UIntPtr)buffer.Length));
        }
 
        /// <summary>
        /// Set the path to write the compiled ONNX model to.
        /// </summary>
        /// <param name="path">Path to write compiled model to.</param>
        public void SetOutputModelPath(string path)
        {
            var platformPath = NativeOnnxValueHelper.GetPlatformSerializedString(path);
            NativeApiStatus.VerifySuccess(
                NativeMethods.CompileApi.OrtModelCompilationOptions_SetOutputModelPath(_handle, platformPath));
 
        }
 
        /// <summary>
        /// Set the path to a file to write initializers as external data to,
        /// and the threshold that determines when to write an initializer to the external data file.
        /// </summary>
        /// <param name="filePath">Path to file to write external data to.</param>
        /// <param name="threshold">Size at which an initializer will be written to external data.</param>
        public void SetOutputModelExternalInitializersFile(string filePath, ulong threshold)
        {
            var platformPath = NativeOnnxValueHelper.GetPlatformSerializedString(filePath);
            NativeApiStatus.VerifySuccess(
                NativeMethods.CompileApi.OrtModelCompilationOptions_SetOutputModelExternalInitializersFile(
                    _handle, platformPath, new UIntPtr(threshold)));
        }
 
        // TODO: In order to use this to create an InferenceSession without copying bytes we need more infrastructure.
        // - Need something that wraps the allocator, pointer and size and is SafeHandle based.
        //   - When it is disposed we need to use the allocator to release the native buffer.
        // - Need the 4 InferenceSession ctors that take byte[] for the model to be duplicated to handle this new
        //   wrapper type.
        // Due to that making this API internal so we can test it. We can make it public when the other infrastructure
        // is in place as it will change the signature of the API.
        internal void SetOutputModelBuffer(OrtAllocator allocator,
                                           ref IntPtr outputModelBufferPtr, ref UIntPtr outputModelBufferSizePtr)
        {
            NativeApiStatus.VerifySuccess(
                NativeMethods.CompileApi.OrtModelCompilationOptions_SetOutputModelBuffer(
                    _handle, allocator.Pointer, ref outputModelBufferPtr, ref outputModelBufferSizePtr));
        }
 
        /// <summary>
        /// Enables or disables the embedding of EPContext binary data into the `ep_cache_context` attribute
        /// of EPContext nodes.
        /// </summary>
        /// <param name="embed">Enable if true. Default is false.</param>
        public void SetEpContextEmbedMode(bool embed)
        {
            NativeApiStatus.VerifySuccess(
                NativeMethods.CompileApi.OrtModelCompilationOptions_SetEpContextEmbedMode(_handle, embed));
        }
 
        /// <summary>
        /// Sets flags from OrtCompileApiFlags that represent one or more boolean options to enable.
        /// </summary>
        /// <param name="flags">bitwise OR of flags in OrtCompileApiFlags to enable.</param>
        public void SetFlags(OrtCompileApiFlags flags)
        {
            NativeApiStatus.VerifySuccess(
                NativeMethods.CompileApi.OrtModelCompilationOptions_SetFlags(_handle, (uint)flags));
        }
 
        /// <summary>
        /// Sets information related to EP context binary file. The Ep uses this information to decide the
        /// location and context binary file name when compiling with both the input and output models
        /// stored in buffers.
        /// </summary>
        /// <param name="outputDirectory">Path to the model directory.</param>
        /// <param name="modelName">The name of the model.</param>
        public void SetEpContextBinaryInformation(string outputDirectory, string modelName)
        {
            var platformOutputDirectory = NativeOnnxValueHelper.GetPlatformSerializedString(outputDirectory);
            var platformModelName = NativeOnnxValueHelper.GetPlatformSerializedString(modelName);
            NativeApiStatus.VerifySuccess(
                NativeMethods.CompileApi.OrtModelCompilationOptions_SetEpContextBinaryInformation(
                    _handle, platformOutputDirectory, platformModelName));
        }
 
        /// <summary>
        /// Sets the graph optimization level. Defaults to ORT_DISABLE_ALL if not specified.
        /// </summary>
        /// <param name="graphOptimizationLevel">The graph optimization level to set.</param>
        public void SetGraphOptimizationLevel(GraphOptimizationLevel graphOptimizationLevel)
        {
            NativeApiStatus.VerifySuccess(
                NativeMethods.CompileApi.OrtModelCompilationOptions_SetGraphOptimizationLevel(
                    _handle, graphOptimizationLevel));
        }
 
        /// <summary>
        /// Delegate that receives one complete external EPContext payload during model compilation.
        /// The data view is valid only for the duration of the delegate invocation.
        /// </summary>
        /// <param name="name">Logical UTF-8 name stored in the EPContext node.</param>
        /// <param name="data">Non-owning view of the payload.</param>
        /// <remarks>ORT may invoke this delegate concurrently. The application must synchronize shared state.</remarks>
        public delegate void WriteEpContextDataDelegate(string name, OrtEpContextData data);
 
        /// <summary>
        /// Registers a delegate that receives external EPContext data when embed mode is disabled.
        /// </summary>
        /// <param name="writeDelegate">Delegate invoked by ORT to receive external EPContext data.</param>
        public void SetEpContextDataWriteDelegate(WriteEpContextDataDelegate writeDelegate)
        {
            if (writeDelegate == null)
            {
                throw new ArgumentNullException(nameof(writeDelegate));
            }
 
            var newRegistration = new EpContextDataWriteRegistration(writeDelegate);
            try
            {
                lock (_epContextDataWriteRegistrationLock)
                {
                    if (_activeCompileCount > 0)
                    {
                        var previousRegistration = _epContextDataWriteRegistration;
                        _epContextDataWriteRegistration = newRegistration;
                        RetireEpContextDataWriteRegistration(previousRegistration);
                        _epContextDataWriteRegistrationUpdatePending = true;
                    }
                    else
                    {
                        ApplyPendingEpContextDataWriteRegistration();
                        var previousRegistration = _epContextDataWriteRegistration;
                        NativeApiStatus.VerifySuccess(
                            NativeMethods.CompileApi.OrtModelCompilationOptions_SetEpContextDataWriteFunc(
                                _handle,
                                newRegistration.FunctionPointer,
                                newRegistration.State));
                        _epContextDataWriteRegistration = newRegistration;
                        RetireEpContextDataWriteRegistration(previousRegistration);
                    }
                }
            }
            catch
            {
                newRegistration.Dispose();
                throw;
            }
        }
 
        /// <summary>
        /// Clears a previously registered EPContext data write delegate.
        /// </summary>
        public void ClearEpContextDataWriteDelegate()
        {
            lock (_epContextDataWriteRegistrationLock)
            {
                if (_activeCompileCount > 0)
                {
                    var previousRegistration = _epContextDataWriteRegistration;
                    _epContextDataWriteRegistration = null;
                    RetireEpContextDataWriteRegistration(previousRegistration);
                    _epContextDataWriteRegistrationUpdatePending = true;
                }
                else
                {
                    ApplyPendingEpContextDataWriteRegistration();
                    var previousRegistration = _epContextDataWriteRegistration;
                    NativeApiStatus.VerifySuccess(
                        NativeMethods.CompileApi.OrtModelCompilationOptions_SetEpContextDataWriteFunc(
                            _handle, IntPtr.Zero, IntPtr.Zero));
                    _epContextDataWriteRegistration = null;
                    RetireEpContextDataWriteRegistration(previousRegistration);
                }
            }
        }
 
        private void ApplyPendingEpContextDataWriteRegistration()
        {
            if (!_epContextDataWriteRegistrationUpdatePending)
            {
                return;
            }
 
            var registration = _epContextDataWriteRegistration;
            NativeApiStatus.VerifySuccess(
                NativeMethods.CompileApi.OrtModelCompilationOptions_SetEpContextDataWriteFunc(
                    _handle,
                    registration?.FunctionPointer ?? IntPtr.Zero,
                    registration?.State ?? IntPtr.Zero));
 
            _epContextDataWriteRegistrationUpdatePending = false;
            foreach (var retiredRegistration in _retiredEpContextDataWriteRegistrations)
            {
                retiredRegistration.Dispose();
            }
            _retiredEpContextDataWriteRegistrations.Clear();
        }
 
        private void RetireEpContextDataWriteRegistration(EpContextDataWriteRegistration registration)
        {
            if (registration == null)
            {
                return;
            }
 
            // Native compilation snapshots the callback after entering CompileModel, so any registration
            // replaced during an active call may still be used by that call.
            if (_activeCompileCount > 0)
            {
                _retiredEpContextDataWriteRegistrations.Add(registration);
            }
            else
            {
                registration.Dispose();
            }
        }
 
        /// <summary>
        /// Delegate to write/save a buffer containing ONNX model bytes to a custom destination. The delegate
        /// may be called repeatedly until the entire output model has been written out. Each call to the delegate
        /// is expected to consume the entire buffer.
        /// </summary>
        /// <param name="buffer">The buffer to write out.</param>
        /// <see cref="OrtModelCompilationOptions.SetOutputModelWriteDelegate"/>
        public delegate void WriteBufferToDestinationDelegate(ReadOnlySpan<byte> buffer);
 
        /// <summary>
        /// Sets a delegate that is called by ORT to write out the output model's serialized ONNX bytes.
        /// The provided delegate may be called repeatedly until the entire output model has been written out.
        /// Each call to the delegate is expected to consume/handle the entire input buffer.
        /// </summary>
        /// <param name="writeBufferDelegate">The delegate called by ORT to write out the model.</param>
        public void SetOutputModelWriteDelegate(WriteBufferToDestinationDelegate writeBufferDelegate)
        {
            _writeBufferToDestinationDelegateState?.Dispose();
            _writeBufferToDestinationDelegateState =
                new DelegateResources<WriteBufferToDestinationConnector,
                                      NativeMethods.DOrtWriteBufferToDestinationDelegate>(
                    new WriteBufferToDestinationConnector(writeBufferDelegate),
                    new NativeMethods.DOrtWriteBufferToDestinationDelegate(
                        WriteBufferToDestinationConnector.WriteBufferToDestinationDelegateWrapper));
 
            IntPtr funcPtr = _writeBufferToDestinationDelegateState.GetFunctionPointerForDelegate();
 
            NativeApiStatus.VerifySuccess(
                NativeMethods.CompileApi.OrtModelCompilationOptions_SetOutputModelWriteFunc(
                    _handle,
                    funcPtr,
                    _writeBufferToDestinationDelegateState.GetConnectorHandleAsPointer()));
        }
 
        /// <summary>
        /// Delegate called by ORT for every initializer when generating the compiled model.
        /// The delegate allows the user to determine whether the initializer should be stored within the compiled
        /// model or externally in a file. If the delegate chooses to store an initializer externally, the delegate
        /// implementation is responsible for writing the initializer data to a file.
        /// </summary>
        /// <param name="initializerName">The initializer's name.</param>
        /// <param name="initializerValue">The readonly OrtValue instance containing the data, type, and
        /// shape of the initializer.</param>
        /// <param name="originalInitializerLocation">May be null. If the initializer is originally stored externally,
        /// this contains the file path, file offset, and data size. Otherwise, this is null.</param>
        /// <returns>A new OrtExternalInitializerInfo indicating the new location of the initializer.
        /// Returns null if the initializer should be stored within the generated compiled model.</returns>
        /// <remarks>The return value may be null.</remarks>
        /// <see cref="OrtModelCompilationOptions.SetOutputModelGetInitializerLocationDelegate"/>
        public delegate OrtExternalInitializerInfo GetInitializerLocationDelegate(
            string initializerName,
            IReadOnlyOrtValue initializerValue,
            IReadOnlyExternalInitializerInfo originalInitializerLocation);
 
        /// <summary>
        /// Sets a delegate that is called by ORT for every initializer when generating the compiled model.
        /// The delegate allows the user to determine whether the initializer should be stored within the compiled
        /// model or externally in a file. If the delegate chooses to store an initializer externally, the delegate
        /// implementation is responsible for writing the initializer data to a file.
        /// </summary>
        /// <param name="getInitializerLocationDelegate">The delegate called by ORT for every initializer.</param>
        public void SetOutputModelGetInitializerLocationDelegate(
            GetInitializerLocationDelegate getInitializerLocationDelegate)
        {
            _getInitializerLocationDelegateState?.Dispose();
            _getInitializerLocationDelegateState =
                new DelegateResources<GetInitializerLocationConnector,
                                      NativeMethods.DOrtGetInitializerLocationDelegate>(
                    new GetInitializerLocationConnector(getInitializerLocationDelegate),
                    new NativeMethods.DOrtGetInitializerLocationDelegate(
                        GetInitializerLocationConnector.GetInitializerLocationDelegateWrapper));
 
            IntPtr funcPtr = _getInitializerLocationDelegateState.GetFunctionPointerForDelegate();
 
            NativeApiStatus.VerifySuccess(
                NativeMethods.CompileApi.OrtModelCompilationOptions_SetOutputModelGetInitializerLocationFunc(
                    _handle,
                    funcPtr,
                    _getInitializerLocationDelegateState.GetConnectorHandleAsPointer()));
        }
 
        #region Delegate helpers
        private sealed class EpContextDataWriteConnector
        {
            internal EpContextDataWriteConnector(WriteEpContextDataDelegate writeDelegate)
            {
                _writeDelegate = writeDelegate;
            }
 
            internal static IntPtr WriteEpContextDataDelegateWrapper(
                IntPtr state, IntPtr name, IntPtr buffer, UIntPtr bufferSize)
            {
                try
                {
                    var connector = (EpContextDataWriteConnector)GCHandle.FromIntPtr(state).Target;
                    string dataName = NativeOnnxValueHelper.StringFromNativeUtf8(name);
                    var data = new OrtEpContextData(buffer, bufferSize);
                    try
                    {
                        connector._writeDelegate(dataName, data);
                    }
                    finally
                    {
                        data.Invalidate();
                    }
                    return IntPtr.Zero;
                }
                catch (Exception ex)
                {
                    string error = $"The C# EPContext data write delegate threw an exception: {ex.Message}";
                    return NativeMethods.OrtCreateStatus(
                        (uint)ErrorCode.Fail, NativeOnnxValueHelper.StringToZeroTerminatedUtf8(error));
                }
            }
 
            private readonly WriteEpContextDataDelegate _writeDelegate;
        }
 
        private sealed class EpContextDataWriteRegistration : IDisposable
        {
            internal EpContextDataWriteRegistration(WriteEpContextDataDelegate writeDelegate)
            {
                _connector = new EpContextDataWriteConnector(writeDelegate);
                _nativeDelegate = new CompileApi.NativeMethods.DOrtWriteNamedBufferDelegate(
                    EpContextDataWriteConnector.WriteEpContextDataDelegateWrapper);
                _connectorHandle = GCHandle.Alloc(_connector);
                try
                {
                    FunctionPointer = Marshal.GetFunctionPointerForDelegate(_nativeDelegate);
                    State = GCHandle.ToIntPtr(_connectorHandle);
                }
                catch
                {
                    _connectorHandle.Free();
                    throw;
                }
            }
 
            internal IntPtr FunctionPointer { get; }
 
            internal IntPtr State { get; }
 
            internal void Release()
            {
                if (System.Threading.Interlocked.Decrement(ref _referenceCount) == 0)
                {
                    if (_connectorHandle.IsAllocated)
                    {
                        _connectorHandle.Free();
                    }
 
                    _connector = null;
                    _nativeDelegate = null;
                }
            }
 
            public void Dispose()
            {
                if (System.Threading.Interlocked.Exchange(ref _ownerReleased, 1) == 0)
                {
                    Release();
                }
 
                GC.SuppressFinalize(this);
            }
 
            ~EpContextDataWriteRegistration()
            {
                if (System.Threading.Interlocked.Exchange(ref _ownerReleased, 1) == 0)
                {
                    Release();
                }
            }
 
            private EpContextDataWriteConnector _connector;
            private CompileApi.NativeMethods.DOrtWriteNamedBufferDelegate _nativeDelegate;
            private GCHandle _connectorHandle;
            private int _referenceCount = 1;
            private int _ownerReleased;
        }
 
        /// <summary>
        /// Class to bridge the C# and native worlds for the "write buffer to destination" delegate
        /// </summary>
        private class WriteBufferToDestinationConnector
        {
            private readonly WriteBufferToDestinationDelegate _userDelegate;
 
            internal WriteBufferToDestinationConnector(WriteBufferToDestinationDelegate writeBufferDelegate)
            {
                _userDelegate = writeBufferDelegate;
            }
 
            public static IntPtr WriteBufferToDestinationDelegateWrapper(IntPtr /* void* */ state,
                                                                         IntPtr /* const void* */ buffer,
                                                                         UIntPtr /* size_t */ bufferNumBytes)
            {
                try
                {
 
                    WriteBufferToDestinationConnector connector = (WriteBufferToDestinationConnector)
                        GCHandle.FromIntPtr(state).Target;
                    ReadOnlySpan<byte> bufferSpan;
 
                    unsafe
                    {
                        // NOTE: A Span<byte> can only view 2GB of data. This is fine because ORT does not write out
                        // chunks that large. However, if we ever need to, the solution is to just write a loop here
                        // that repeatedly calls the delegate with smaller chunks of data.
                        bufferSpan = new ReadOnlySpan<byte>(buffer.ToPointer(), checked((int)bufferNumBytes));
                    }
 
                    connector._userDelegate(bufferSpan);
                }
                catch (Exception ex)
                {
                    var error = $"The C# WriteBufferToDestination delegate threw an exception: {ex.Message}";
                    IntPtr status = NativeMethods.OrtCreateStatus((uint)ErrorCode.Fail,
                                            NativeOnnxValueHelper.StringToZeroTerminatedUtf8(error));
                    return status;
                }
 
                return IntPtr.Zero;
            }
        }
 
        /// <summary>
        /// Class to bridge the C# and native worlds for the "get initializer location" delegate
        /// </summary>
        private class GetInitializerLocationConnector
        {
            private readonly GetInitializerLocationDelegate _userDelegate;
 
            internal GetInitializerLocationConnector(GetInitializerLocationDelegate getInitializerLocationDelegate)
            {
                _userDelegate = getInitializerLocationDelegate;
            }
 
            public static IntPtr GetInitializerLocationDelegateWrapper(
                IntPtr /* void* */ state,
                IntPtr /* const char* */ initializerName,
                IntPtr /* const OrtValue* */ initializerValue,
                IntPtr /* const OrtExternalInitializerInfo* */ originalInitializerLocation,
                out IntPtr /* OrtExternalInitializerInfo** */ newInitializerLocationOutput)
            {
                newInitializerLocationOutput = IntPtr.Zero;
 
                try
                {
 
                    GetInitializerLocationConnector connector = (GetInitializerLocationConnector)GCHandle.
                        FromIntPtr(state).Target;
                    string utf8InitializerName = NativeOnnxValueHelper.StringFromNativeUtf8(initializerName);
                    IReadOnlyOrtValue readOnlyInitializerValue = new OrtValue(initializerValue, owned: false);
                    IReadOnlyExternalInitializerInfo readOnlyOriginalInitializerLocation = null;
 
                    if (originalInitializerLocation != IntPtr.Zero)
                    {
                        readOnlyOriginalInitializerLocation = new OrtExternalInitializerInfo(
                            originalInitializerLocation, ownsHandle: false);
                    }
 
                    // Call user's delegate, which may return the new location of the initializer.
                    OrtExternalInitializerInfo newInitializerLocation = connector._userDelegate(
                        utf8InitializerName, readOnlyInitializerValue, readOnlyOriginalInitializerLocation);
 
                    if (newInitializerLocation != null)
                    {
                        // Delegate returned info about a new location for the initializer.
                        // Can't guarantee that the new external info returned by user's delegate is not referenced
                        // by other C# code. ORT expects to own the new external info, so create a copy here and
                        // give it to ORT.
                        string newFilePath = newInitializerLocation.GetFilePath();
                        byte[] newFilePathBytes = NativeOnnxValueHelper.GetPlatformSerializedString(newFilePath);
 
                        IntPtr status = NativeMethods.OrtCreateExternalInitializerInfo(
                            newFilePathBytes,
                            newInitializerLocation.GetFileOffset(),
                            (UIntPtr)newInitializerLocation.GetByteSize(),
                            out newInitializerLocationOutput);
 
                        if (status != IntPtr.Zero)
                        {
                            return status;
                        }
                    }
                    else
                    {
                        // User's delegate did not return a new location for the initializer. ORT will store initializer
                        // within the generated compiled model.
                        newInitializerLocationOutput = IntPtr.Zero;
                    }
                }
                catch (Exception ex)
                {
                    var error = $"The C# GetInitializerLocation delegate threw an exception: {ex.Message}";
                    IntPtr status = NativeMethods.OrtCreateStatus((uint)ErrorCode.Fail,
                                            NativeOnnxValueHelper.StringToZeroTerminatedUtf8(error));
                    return status;
                }
 
                return IntPtr.Zero;
            }
        }
 
        /// <summary>
        /// Disposable class that stores resources for a delegate provided by the user.
        /// </summary>
        /// <typeparam name="Connector">The type of the connector class
        /// (e.g., WriteBufferToDestinationConnector)</typeparam>
        /// <typeparam name="Delegate">The type of the native delegate.</typeparam>
        private class DelegateResources<Connector, Delegate> : IDisposable
            where Connector : class
            where Delegate : class
        {
            public DelegateResources(Connector connector, Delegate @delegate)
            {
                _connector = connector;
                _delegate = @delegate;
                _connectorHandle = GCHandle.Alloc(_connector);
                _delegateHandle = GCHandle.Alloc(_delegate);
            }
 
            internal IntPtr GetFunctionPointerForDelegate()
            {
                return Marshal.GetFunctionPointerForDelegate(_delegate);
            }
 
            internal IntPtr GetConnectorHandleAsPointer()
            {
                return GCHandle.ToIntPtr(_connectorHandle);
            }
 
            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
 
            protected virtual void Dispose(bool disposing)
            {
                if (_disposed)
                {
                    return;
                }
 
                if (disposing)
                {
                    // Dispose other children disposables. We have none.
                }
 
                if (_connectorHandle.IsAllocated)
                {
                    _connectorHandle.Free();
                    _connector = null;
                }
 
                if (_delegateHandle.IsAllocated)
                {
                    _delegateHandle.Free();
                    _delegate = null;
                }
 
                _disposed = true;
            }
 
            ~DelegateResources()
            {
                Dispose(false);
            }
 
            private Connector _connector = null;
            private Delegate _delegate = null;
            private GCHandle _connectorHandle = default;
            private GCHandle _delegateHandle = default;
            private bool _disposed = false;
        }
        #endregion
 
        #region IDispose implementation
        /// <summary>
        /// IDispose implementation.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
 
        /// <summary>
        /// IDispose implementation
        /// </summary>
        /// <param name="disposing">True if Dispose() has been called by the user-side code. False if
        /// called by the runtime from inside the finalizer.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }
 
            Debug.Assert(_handle != IntPtr.Zero);
            NativeMethods.CompileApi.OrtReleaseModelCompilationOptions(_handle);
            _handle = IntPtr.Zero;
 
            if (_epContextDataReadRegistration != null)
            {
                _epContextDataReadRegistration.Release();
                _epContextDataReadRegistration = null;
            }
 
            lock (_epContextDataWriteRegistrationLock)
            {
                var writeRegistration = _epContextDataWriteRegistration;
                _epContextDataWriteRegistration = null;
                RetireEpContextDataWriteRegistration(writeRegistration);
                foreach (var retiredRegistration in _retiredEpContextDataWriteRegistrations)
                {
                    retiredRegistration.Dispose();
                }
                _retiredEpContextDataWriteRegistrations.Clear();
            }
 
            if (disposing)
            {
                _writeBufferToDestinationDelegateState?.Dispose();
                _getInitializerLocationDelegateState?.Dispose();
            }
 
            _disposed = true;
        }
 
        /// <summary>
        /// Finalizer that releases the native handle if not already released by Dispose().
        /// </summary>
        ~OrtModelCompilationOptions()
        {
            Dispose(false);
        }
        #endregion
 
        /// <summary>
        /// Handle to the native OrtModelCompilationOptions object.
        /// </summary>
        private IntPtr _handle;
 
        /// <summary>
        /// True if this OrtModelCompilationOptions instance has already been disposed.
        /// </summary>
        private bool _disposed = false;
 
        private SessionOptions.EpContextDataReadRegistration _epContextDataReadRegistration = null;
 
        /// <summary>
        /// Stores delegate state for the "write buffer to destination" delegate.
        /// </summary>
        private DelegateResources<WriteBufferToDestinationConnector, NativeMethods.DOrtWriteBufferToDestinationDelegate>
            _writeBufferToDestinationDelegateState = null;
 
        private readonly object _epContextDataWriteRegistrationLock = new object();
        private EpContextDataWriteRegistration _epContextDataWriteRegistration = null;
        private int _activeCompileCount;
        private bool _epContextDataWriteRegistrationUpdatePending;
        private readonly List<EpContextDataWriteRegistration> _retiredEpContextDataWriteRegistrations =
            new List<EpContextDataWriteRegistration>();
 
        /// <summary>
        /// Stores delegate state for the "get initializer location" delegate.
        /// </summary>
        private DelegateResources<GetInitializerLocationConnector, NativeMethods.DOrtGetInitializerLocationDelegate>
            _getInitializerLocationDelegateState = null;
    }
}