Исходный код СУБД 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
#include "dbms_vector_onnx.hpp"
 
/*
 * DBMS_VECTOR local ONNX inference core: the onnxruntime C API wrapper used
 * by provider 'database' (LOAD validation + UTL_TO_EMBEDDING/UTL_TO_EMBEDDINGS
 * inference).
 *
 * Compiled with and without --with-onnxruntime.  Without the flag the stubs
 * at the bottom of the file keep the module linkable and the provider
 * dispatch reports the deferred-inference error.
 *
 * Implementation notes:
 * - Pure C API (onnxruntime_cxx_api.h is avoided on purpose: its wrappers
 *   throw C++ exceptions, which must not cross an ereport/longjmp boundary).
 * - Every OrtStatus is released before the matching ereport, and every error
 *   path destroys the per-call session first: ereport longjmps, so nothing
 *   allocated by the runtime would otherwise be freed.
 * - The one-shot path creates a fresh session per call.  Additionally a
 *   per-backend session cache backs INMEMORY_ONNX_MODEL: pinning a stored
 *   model creates its session once (owner, name, content digest key), and
 *   provider 'database' batches run on the cached session while the digest
 *   and the cluster generation counter still match.  DROP_ONNX_MODEL bumps
 *   the shared counter, which invalidates every backend's cache.
 * - Sessions run sequentially with a single intra-op thread: a backend
 *   process embeds one request at a time, and a private thread pool per
 *   backend would multiply memory footprint for no throughput gain.
 */
 
#include <cstring>
#include <string>
#include <vector>
 
extern "C"
{
 
#include "lib/stringinfo.h"
#include "storage/ipc.h"
#include "storage/lwlock.h"
#include "storage/shmem.h"
#include "port/atomics.h"
#include "utils/builtins.h"
#include "vector/vector.h"
 
} // extern "C"
 
/*
 * Cluster-wide model generation counter (shmem slop allocation, the same
 * tiny-allocation pattern the vector AMs use for tranche ids).  Every
 * DROP_ONNX_MODEL increments it; backend caches hold entries pinned to
 * the value they observed, so a bump invalidates all of them lazily.
 */
static pg_atomic_uint64 *dbms_vector_model_generation = nullptr;
 
static uint64_t
dbms_vector_onnx_generation()
{
    if (dbms_vector_model_generation == nullptr)
    {
        bool found = false;
 
        LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
        dbms_vector_model_generation = (pg_atomic_uint64 *)
            ShmemInitStruct("dbms_vector model generation",
                            sizeof(pg_atomic_uint64), &found);
        if (!found)
            pg_atomic_init_u64(dbms_vector_model_generation, 0);
        LWLockRelease(AddinShmemInitLock);
    }
 
    return pg_atomic_read_u64(dbms_vector_model_generation);
}
 
void
dbms_vector_onnx_bump_generation()
{
    dbms_vector_onnx_generation();
    pg_atomic_fetch_add_u64(dbms_vector_model_generation, 1);
}
 
#ifdef USE_ONNXRUNTIME
#include "core/session/onnxruntime_c_api.h"
#endif
 
#ifdef USE_ONNXRUNTIME
 
namespace
{
 
/*
 * Raise for a failed runtime call: copy the message out of the status,
 * release the status, then ereport.  GetErrorMessage points into the status,
 * so the copy must happen first.
 */
void
dbms_vector_ort_runtime_error(OrtStatus *status, const char *what)
{
    const OrtApi *api = OrtGetApiBase()->GetApi(ORT_API_VERSION);
    char *message = pstrdup(status != nullptr
                            ? api->GetErrorMessage(status) : "(no status)");
    if (status != nullptr)
        api->ReleaseStatus(status);
 
    ereport(ERROR,
            (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
             errmsg("ONNX runtime %s failed: %s", what, message)));
}
 
/*
 * Raise for a model that does not satisfy the embedding contract
 * (Oracle IMPORT_ONNX_MODEL validation parity, ORA-20003 in the detail).
 * Destroys the session first when one is open.
 */
struct DbmsVectorOrtSession
{
    OrtSessionOptions *options = nullptr;
    OrtSession        *session = nullptr;
    OrtAllocator      *allocator = nullptr; /* default allocator, not owned */
 
    std::string input_name;                 /* graph input receiving DATA */
    std::string output_name;                /* graph output with the embedding */
};
 
void
dbms_vector_ort_session_destroy(DbmsVectorOrtSession &s)
{
    const OrtApi *api = OrtGetApiBase()->GetApi(ORT_API_VERSION);
 
    if (s.session != nullptr)
    {
        api->ReleaseSession(s.session);
        s.session = nullptr;
    }
    if (s.options != nullptr)
    {
        api->ReleaseSessionOptions(s.options);
        s.options = nullptr;
    }
}
 
[[noreturn]] void
dbms_vector_ort_model_error(DbmsVectorOrtSession *session,
                            const char *errmsg_text,
                            const char *detail_text = nullptr,
                            const char *hint_text = nullptr)
{
    if (session != nullptr)
        dbms_vector_ort_session_destroy(*session);
 
    ereport(ERROR,
            (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
             errmsg("%s", errmsg_text),
             detail_text != nullptr
                 ? errdetail("%s", detail_text) : 0,
             hint_text != nullptr
                 ? errhint("%s", hint_text) : 0));
}
 
const OrtApi *
dbms_vector_ort_api()
{
    const OrtApi *api = OrtGetApiBase()->GetApi(ORT_API_VERSION);
 
    if (api == nullptr)
        ereport(ERROR,
                (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
                 errmsg("could not initialize the ONNX runtime API")));
    return api;
}
 
/*
 * Per-backend OrtEnv singleton (created on first use, never released: it
 * lives for the lifetime of the backend process).
 */
OrtEnv *
dbms_vector_ort_env(const OrtApi *api)
{
    static OrtEnv *env = nullptr;
 
    if (env == nullptr)
    {
        OrtStatus *status = api->CreateEnv(ORT_LOGGING_LEVEL_WARNING,
                                           "dbms_vector", &env);
        if (status != nullptr)
            dbms_vector_ort_runtime_error(status, "environment creation");
    }
 
    return env;
}
 
void
dbms_vector_ort_session_create(const bytea *model_data,
                               DbmsVectorOrtSession &s)
{
    const OrtApi *api = dbms_vector_ort_api();
    OrtEnv *env = dbms_vector_ort_env(api);
    OrtStatus *status;
 
    status = api->CreateSessionOptions(&s.options);
    if (status != nullptr)
        dbms_vector_ort_runtime_error(status, "session options creation");
 
    status = api->SetIntraOpNumThreads(s.options, 1);
    if (status != nullptr)
        dbms_vector_ort_runtime_error(status, "session configuration");
 
    status = api->SetInterOpNumThreads(s.options, 1);
    if (status != nullptr)
        dbms_vector_ort_runtime_error(status, "session configuration");
 
    status = api->SetSessionExecutionMode(s.options, ORT_SEQUENTIAL);
    if (status != nullptr)
        dbms_vector_ort_runtime_error(status, "session configuration");
 
    /*
     * CreateSessionFromArray both parses the protobuf and initializes the
     * graph, so it doubles as the real model validation for LOAD_ONNX_MODEL.
     */
    status = api->CreateSessionFromArray(env,
                                         VARDATA(model_data),
                                         VARSIZE_ANY_EXHDR(model_data),
                                         s.options, &s.session);
    if (status != nullptr)
    {
        char *message = pstrdup(api->GetErrorMessage(status));
        api->ReleaseStatus(status);
        dbms_vector_ort_session_destroy(s);
 
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("invalid ONNX model: %s", message),
                 errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR).")));
    }
 
    status = api->GetAllocatorWithDefaultOptions(&s.allocator);
    if (status != nullptr)
    {
        dbms_vector_ort_session_destroy(s);
        dbms_vector_ort_runtime_error(status, "allocator setup");
    }
}
 
/*
 * Fetch the name and tensor element type of one graph input/output.  The
 * name is allocated by the runtime allocator and returned as a std::string;
 * the raw buffer is always freed.
 */
void
dbms_vector_ort_io_info(const DbmsVectorOrtSession &s, bool is_input,
                        size_t index, std::string &name,
                        ONNXTensorElementDataType &type, bool &is_tensor)
{
    const OrtApi *api = dbms_vector_ort_api();
    OrtTypeInfo *type_info = nullptr;
    const OrtTensorTypeAndShapeInfo *tensor_info = nullptr;
    char *raw_name = nullptr;
    OrtStatus *status;
 
    if (is_input)
        status = api->SessionGetInputTypeInfo(s.session, index, &type_info);
    else
        status = api->SessionGetOutputTypeInfo(s.session, index, &type_info);
    if (status != nullptr)
        dbms_vector_ort_runtime_error(status, "model inspection");
 
    status = api->CastTypeInfoToTensorInfo(type_info, &tensor_info);
    if (status != nullptr)
    {
        api->ReleaseTypeInfo(type_info);
        dbms_vector_ort_runtime_error(status, "model inspection");
    }
 
    type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED;
    is_tensor = tensor_info != nullptr;
    if (is_tensor)
    {
        status = api->GetTensorElementType(tensor_info, &type);
        if (status != nullptr)
        {
            api->ReleaseTypeInfo(type_info);
            dbms_vector_ort_runtime_error(status, "model inspection");
        }
    }
 
    api->ReleaseTypeInfo(type_info);
 
    if (is_input)
        status = api->SessionGetInputName(s.session, index, s.allocator,
                                          &raw_name);
    else
        status = api->SessionGetOutputName(s.session, index, s.allocator,
                                           &raw_name);
    if (status != nullptr)
        dbms_vector_ort_runtime_error(status, "model inspection");
 
    name.assign(raw_name);
    s.allocator->Free(s.allocator, raw_name);
}
 
const JsonbValue *
dbms_vector_ort_metadata_field(Jsonb *metadata, const char *key,
                               JsonbValue *buffer)
{
    if (metadata == nullptr || !JsonContainerIsObject(&metadata->root))
        return nullptr;
 
    return getKeyJsonValueFromContainer(&metadata->root, key, strlen(key),
                                        buffer);
}
 
/*
 * Resolve and check the embedding contract:
 * - the DATA input: the graph input mapped by metadata "input"
 *   ({"<graph input name>": ["DATA"]}), or, without a mapping, the unique
 *   string-tensor input (Oracle 23ai parity: the tokenizer must be fused
 *   into the ONNX graph);
 * - the embedding output: the graph output named by metadata
 *   "embeddingOutput", or the unique output;
 * - the output must be a float tensor; when its shape is fully static the
 *   per-row width must fit the vector type (VECTOR_MAX_DIM).
 */
void
dbms_vector_ort_resolve_contract(DbmsVectorOrtSession &s, Jsonb *metadata)
{
    const OrtApi *api = dbms_vector_ort_api();
    size_t input_count = 0;
    size_t output_count = 0;
    OrtStatus *status;
 
    status = api->SessionGetInputCount(s.session, &input_count);
    if (status != nullptr)
        dbms_vector_ort_runtime_error(status, "model inspection");
    status = api->SessionGetOutputCount(s.session, &output_count);
    if (status != nullptr)
        dbms_vector_ort_runtime_error(status, "model inspection");
 
    if (input_count == 0)
        dbms_vector_ort_model_error(&s, "unsupported ONNX model: the model has no inputs",
                                    "Oracle error: ORA-20003 (EXCP_GU_ERR).");
    if (output_count == 0)
        dbms_vector_ort_model_error(&s, "unsupported ONNX model: the model has no outputs",
                                    "Oracle error: ORA-20003 (EXCP_GU_ERR).");
 
    JsonbValue map_buffer;
    const JsonbValue *input_map = dbms_vector_ort_metadata_field(metadata,
                                                                 "input",
                                                                 &map_buffer);
    bool have_map = input_map != nullptr && input_map->type == jbvBinary &&
        JsonContainerIsObject(input_map->val.binary.data);
 
    /* pass 1: the metadata-mapped input */
    bool found = false;
    if (have_map)
    {
        for (size_t i = 0; i < input_count && !found; i++)
        {
            std::string name;
            ONNXTensorElementDataType type;
            bool is_tensor;
 
            dbms_vector_ort_io_info(s, true, i, name, type, is_tensor);
 
            JsonbValue unused;
            if (getKeyJsonValueFromContainer(input_map->val.binary.data,
                                             name.c_str(), name.size(),
                                             &unused) == nullptr)
                continue;
 
            if (!is_tensor || type != ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING)
                dbms_vector_ort_model_error(
                    &s,
                    ("unsupported ONNX model: the input mapped by metadata (\""
                     + name + "\") must be a string tensor").c_str(),
                    "Oracle error: ORA-20003 (EXCP_GU_ERR).");
 
            s.input_name = name;
            found = true;
        }
    }
 
    /* pass 2 (no mapping): the unique string input */
    if (!found)
    {
        std::string candidate;
        size_t string_inputs = 0;
 
        for (size_t i = 0; i < input_count; i++)
        {
            std::string name;
            ONNXTensorElementDataType type;
            bool is_tensor;
 
            dbms_vector_ort_io_info(s, true, i, name, type, is_tensor);
 
            if (is_tensor && type == ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING)
            {
                string_inputs++;
                candidate = name;
            }
        }
 
        if (string_inputs == 0)
            dbms_vector_ort_model_error(
                &s,
                "unsupported ONNX model: no string input with a built-in tokenizer",
                "Oracle error: ORA-20003 (EXCP_GU_ERR).",
                "The model graph must contain the tokenizer (a string input, "
                "as produced by Olive-fused exports); models taking "
                "input_ids are not supported.");
 
        if (string_inputs > 1)
            dbms_vector_ort_model_error(
                &s,
                "unsupported ONNX model: multiple string inputs, the DATA input is ambiguous",
                "Oracle error: ORA-20003 (EXCP_GU_ERR).",
                "Specify the mapping in the model metadata, e.g. "
                "{\"input\":{\"<graph input>\":[\"DATA\"]}}.");
 
        s.input_name = candidate;
    }
 
    /* the embedding output */
    JsonbValue output_name_buffer;
    const JsonbValue *output_name = dbms_vector_ort_metadata_field(
        metadata, "embeddingOutput", &output_name_buffer);
    bool have_output_name = output_name != nullptr &&
        output_name->type == jbvString;
 
    std::string selected_output;
    bool output_found = false;
 
    for (size_t i = 0; i < output_count; i++)
    {
        std::string name;
        ONNXTensorElementDataType type;
        bool is_tensor;
 
        dbms_vector_ort_io_info(s, false, i, name, type, is_tensor);
 
        if (have_output_name)
        {
            std::string wanted(output_name->val.string.val,
                               output_name->val.string.len);
            if (name != wanted)
                continue;
        }
        else if (output_count > 1)
            dbms_vector_ort_model_error(
                &s,
                "unsupported ONNX model: multiple outputs, the embedding output is ambiguous",
                "Oracle error: ORA-20003 (EXCP_GU_ERR).",
                "Specify the output name in the model metadata, e.g. "
                "{\"embeddingOutput\":\"<graph output>\"}.");
 
        if (!is_tensor || type != ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT)
            dbms_vector_ort_model_error(
                &s,
                ("unsupported ONNX model: the embedding output (\"" + name +
                 "\") must be a float tensor").c_str(),
                "Oracle error: ORA-20003 (EXCP_GU_ERR).");
 
        selected_output = name;
        output_found = true;
        break;
    }
 
    if (!output_found)
        dbms_vector_ort_model_error(
            &s,
            "unsupported ONNX model: the metadata embeddingOutput does not "
            "match any graph output",
            "Oracle error: ORA-20003 (EXCP_GU_ERR).");
 
    s.output_name = selected_output;
 
    /*
     * Static shape check: when the whole shape is known, the per-row width
     * (everything after the leading batch dimension; the full size for a
     * rank-1 output) must fit the vector type.  Dynamic shapes are checked
     * at run time against the actual output.
     */
    OrtTypeInfo *type_info = nullptr;
    const OrtTensorTypeAndShapeInfo *tensor_info = nullptr;
    size_t selected_index = 0;
 
    /* the contract resolution above pinned the output name; find its index */
    for (size_t i = 0; i < output_count; i++)
    {
        std::string name;
        ONNXTensorElementDataType type;
        bool is_tensor;
 
        dbms_vector_ort_io_info(s, false, i, name, type, is_tensor);
        if (name == s.output_name)
        {
            selected_index = i;
            break;
        }
    }
 
    status = api->SessionGetOutputTypeInfo(s.session, selected_index,
                                           &type_info);
    if (status != nullptr)
        dbms_vector_ort_runtime_error(status, "model inspection");
 
    status = api->CastTypeInfoToTensorInfo(type_info, &tensor_info);
    if (status != nullptr)
    {
        api->ReleaseTypeInfo(type_info);
        dbms_vector_ort_runtime_error(status, "model inspection");
    }
 
    if (tensor_info != nullptr)
    {
        size_t dim_count = 0;
 
        status = api->GetDimensionsCount(tensor_info, &dim_count);
        if (status != nullptr)
        {
            api->ReleaseTypeInfo(type_info);
            dbms_vector_ort_runtime_error(status, "model inspection");
        }
 
        if (dim_count > 0)
        {
            int64_t *dims = (int64_t *) palloc(dim_count * sizeof(int64_t));
            bool all_static = true;
            int64_t width = 1;
 
            status = api->GetDimensions(tensor_info, dims, dim_count);
            if (status != nullptr)
            {
                pfree(dims);
                api->ReleaseTypeInfo(type_info);
                dbms_vector_ort_runtime_error(status, "model inspection");
            }
 
            for (size_t i = 0; i < dim_count; i++)
                if (dims[i] <= 0)
                    all_static = false;
 
            if (all_static)
            {
                for (size_t i = dim_count == 1 ? 0 : 1; i < dim_count; i++)
                    width *= dims[i];
 
                if (width > VECTOR_MAX_DIM)
                    dbms_vector_ort_model_error(
                        &s,
                        psprintf("unsupported ONNX model: the embedding "
                                 "width " INT64_FORMAT " exceeds the vector "
                                 "limit of %d dimensions",
                                 width, VECTOR_MAX_DIM),
                        "Oracle error: ORA-20003 (EXCP_GU_ERR).");
            }
 
            pfree(dims);
        }
    }
 
    api->ReleaseTypeInfo(type_info);
}
 
std::string
dbms_vector_ort_floats_to_text(const float *values, size_t count)
{
    StringInfoData buf;
 
    initStringInfo(&buf);
    appendStringInfoChar(&buf, '[');
 
    for (size_t i = 0; i < count; i++)
    {
        if (i > 0)
            appendStringInfoChar(&buf, ',');
        appendStringInfo(&buf, "%.8g", values[i]);
    }
 
    appendStringInfoChar(&buf, ']');
 
    std::string result(buf.data, buf.len);
    pfree(buf.data);
 
    return result;
}
 
} // namespace
 
bool
dbms_vector_onnx_available()
{
    return true;
}
 
void
dbms_vector_onnx_validate(bytea *model_data, Jsonb *metadata)
{
    DbmsVectorOrtSession session;
 
    dbms_vector_ort_session_create(model_data, session);
    dbms_vector_ort_resolve_contract(session, metadata);
    dbms_vector_ort_session_destroy(session);
}
 
/*
 * Run one batch on an existing session.  The session is NOT destroyed
 * here (neither on success nor on an error path): the one-shot wrapper
 * destroys its private session, the session cache keeps its entry alive.
 */
static std::vector<std::string>
dbms_vector_ort_run_session(DbmsVectorOrtSession &session,
                            const std::vector<std::string> &inputs)
{
    const OrtApi *api = dbms_vector_ort_api();
    OrtValue *input = nullptr;
    OrtValue *output = nullptr;
    OrtStatus *status;
 
    /* one string tensor of shape [batch] feeding the DATA input */
    int64_t shape[1] = { (int64_t) inputs.size() };
 
    status = api->CreateTensorAsOrtValue(session.allocator, shape, 1,
                                         ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING,
                                         &input);
    if (status != nullptr)
    {
        dbms_vector_ort_runtime_error(status, "input tensor creation");
    }
 
    {
        std::vector<const char *> batch;
        batch.reserve(inputs.size());
        for (const std::string &text : inputs)
            batch.push_back(text.c_str());
 
        status = api->FillStringTensor(input, batch.data(), batch.size());
        if (status != nullptr)
        {
            api->ReleaseValue(input);
            dbms_vector_ort_runtime_error(status, "input tensor fill");
        }
    }
 
    const char *input_names[1] = { session.input_name.c_str() };
    const char *output_names[1] = { session.output_name.c_str() };
 
    status = api->Run(session.session, nullptr, input_names, &input, 1,
                      output_names, 1, &output);
    if (status != nullptr)
    {
        api->ReleaseValue(input);
        dbms_vector_ort_runtime_error(status, "inference");
    }
 
    /* resolve the concrete output shape and read the embedding rows */
    std::vector<std::string> vectors;
    OrtTypeInfo *type_info = nullptr;
    const OrtTensorTypeAndShapeInfo *tensor_info = nullptr;
 
    status = api->GetTypeInfo(output, &type_info);
    if (status != nullptr)
    {
        api->ReleaseValue(output);
        api->ReleaseValue(input);
        dbms_vector_ort_runtime_error(status, "output inspection");
    }
 
    status = api->CastTypeInfoToTensorInfo(type_info, &tensor_info);
    if (status != nullptr || tensor_info == nullptr)
    {
        api->ReleaseTypeInfo(type_info);
        api->ReleaseValue(output);
        api->ReleaseValue(input);
        if (status != nullptr)
            dbms_vector_ort_runtime_error(status, "output inspection");
        ereport(ERROR,
                (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
                 errmsg("ONNX model returned a non-tensor output")));
    }
 
    {
        size_t dim_count = 0;
        int64_t total = 1;
        int64_t batch = (int64_t) inputs.size();
        int64_t width = 0;
 
        status = api->GetDimensionsCount(tensor_info, &dim_count);
        if (status != nullptr)
        {
            api->ReleaseTypeInfo(type_info);
            api->ReleaseValue(output);
            api->ReleaseValue(input);
            dbms_vector_ort_runtime_error(status, "output inspection");
        }
 
        int64_t *dims = (int64_t *) palloc(dim_count * sizeof(int64_t));
 
        status = api->GetDimensions(tensor_info, dims, dim_count);
        if (status != nullptr)
        {
            pfree(dims);
            api->ReleaseTypeInfo(type_info);
            api->ReleaseValue(output);
            api->ReleaseValue(input);
            dbms_vector_ort_runtime_error(status, "output inspection");
        }
 
        for (size_t i = 0; i < dim_count; i++)
            total *= dims[i];
 
        if (dim_count >= 2 && dims[0] == batch)
            width = total / batch;
        else if (dim_count == 1 && batch == 1)
            width = total;
        else
            width = -1;
 
        pfree(dims);
        api->ReleaseTypeInfo(type_info);
 
        if (width <= 0 || width > VECTOR_MAX_DIM)
        {
            api->ReleaseValue(output);
            api->ReleaseValue(input);
 
            ereport(ERROR,
                    (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
                     errmsg("ONNX model returned an unexpected output "
                            "shape for a batch of %zu inputs",
                            inputs.size()),
                     errdetail("Oracle error: ORA-20002 (EXCP_PROVIDER_ERR).")));
        }
 
        float *data = nullptr;
 
        status = api->GetTensorMutableData(output, (void **) &data);
        if (status != nullptr)
        {
            api->ReleaseValue(output);
            api->ReleaseValue(input);
            dbms_vector_ort_runtime_error(status, "output read");
        }
 
        vectors.reserve(inputs.size());
        for (size_t i = 0; i < inputs.size(); i++)
            vectors.push_back(dbms_vector_ort_floats_to_text(
                data + i * width, (size_t) width));
    }
 
    api->ReleaseValue(output);
    api->ReleaseValue(input);
 
    return vectors;
}
 
 
/*
 * Content digest of a stored model for the session cache key: FNV-1a over
 * the metadata text, the model size and the first 64 KiB + last 4 KiB of
 * the model bytes (models can be large; a partial digest is enough here -
 * the generation counter backstops DROP/LOAD races).
 */
static uint64_t
dbms_vector_onnx_model_digest(const bytea *model_data, Jsonb *metadata)
{
    uint64_t hash = 1469598103934665603ULL;
    char *meta_text = metadata != nullptr
        ? JsonbToCString(nullptr, &metadata->root, 0) : pstrdup("");
 
    auto mix = [&hash](const char *data, size_t len)
    {
        for (size_t i = 0; i < len; i++)
        {
            hash ^= (unsigned char) data[i];
            hash *= 1099511628211ULL;
        }
    };
 
    mix(meta_text, strlen(meta_text));
 
    char *bytes = (char *) VARDATA_ANY(model_data);
    Size size = VARSIZE_ANY_EXHDR(model_data);
    char size_text[32];
 
    snprintf(size_text, sizeof(size_text), "%zu", (size_t) size);
    mix(size_text, strlen(size_text));
 
    mix(bytes, size < 65536 ? size : 65536);
    if (size > 65536 + 4096)
        mix(bytes + size - 4096, 4096);
 
    pfree(meta_text);
 
    return hash;
}
 
/*
 * Per-backend session cache: at most a handful of entries (one per pin),
 * kept in malloc memory outside transaction contexts on purpose - the
 * OrtSession objects must outlive transactions, and the entries are
 * freed explicitly on invalidation.
 */
struct DbmsVectorSessionCacheEntry
{
    std::string owner;
    std::string model_name;
    uint64_t digest;
    uint64_t generation;
    DbmsVectorOrtSession session;
};
 
static std::vector<DbmsVectorSessionCacheEntry *> dbms_vector_session_cache;
 
static void
dbms_vector_session_cache_discard(size_t index)
{
    DbmsVectorSessionCacheEntry *entry = dbms_vector_session_cache[index];
 
    dbms_vector_ort_session_destroy(entry->session);
    delete entry;
    dbms_vector_session_cache.erase(dbms_vector_session_cache.begin() +
                                    (ssize_t) index);
}
 
static void
dbms_vector_session_cache_gc()
{
    uint64_t generation = dbms_vector_onnx_generation();
 
    for (size_t i = dbms_vector_session_cache.size(); i > 0; i--)
        if (dbms_vector_session_cache[i - 1]->generation != generation)
            dbms_vector_session_cache_discard(i - 1);
}
 
static DbmsVectorSessionCacheEntry *
dbms_vector_session_cache_find(const char *owner, const char *model_name,
                               uint64_t digest)
{
    dbms_vector_session_cache_gc();
 
    for (DbmsVectorSessionCacheEntry *entry : dbms_vector_session_cache)
        if (entry->owner == owner && entry->model_name == model_name &&
            entry->digest == digest)
            return entry;
 
    return nullptr;
}
 
void
dbms_vector_onnx_pin(const char *owner, const char *model_name,
                     const bytea *model_data, Jsonb *metadata)
{
    DbmsVectorOrtSession session;
    uint64_t digest = dbms_vector_onnx_model_digest(model_data, metadata);
    uint64_t generation = dbms_vector_onnx_generation();
 
    /* Re-pinning the same content is a cheap no-op. */
    DbmsVectorSessionCacheEntry *existing =
        dbms_vector_session_cache_find(owner, model_name, digest);
    if (existing != nullptr)
    {
        elog(DEBUG1, "DBMS_VECTOR.INMEMORY_ONNX_MODEL: model %s.%s is "
                     "already pinned in this backend", owner, model_name);
        return;
    }
 
    dbms_vector_ort_session_create(model_data, session);
    dbms_vector_ort_resolve_contract(session, metadata);
 
    auto *entry = new DbmsVectorSessionCacheEntry();
    entry->owner = owner;
    entry->model_name = model_name;
    entry->digest = digest;
    entry->generation = generation;
    entry->session = session;
 
    dbms_vector_session_cache.push_back(entry);
 
    elog(DEBUG1, "DBMS_VECTOR.INMEMORY_ONNX_MODEL: model %s.%s pinned in "
                 "this backend", owner, model_name);
}
 
std::vector<std::string>
dbms_vector_onnx_run_cached(const char *owner, const char *model_name,
                            const bytea *model_data, Jsonb *metadata,
                            const std::vector<std::string> &inputs)
{
    uint64_t digest = dbms_vector_onnx_model_digest(model_data, metadata);
    DbmsVectorSessionCacheEntry *entry =
        dbms_vector_session_cache_find(owner, model_name, digest);
 
    if (entry != nullptr)
    {
        elog(DEBUG1, "DBMS_VECTOR: ONNX session cache hit for model "
                     "%s.%s", owner, model_name);
        return dbms_vector_ort_run_session(entry->session, inputs);
    }
 
    return dbms_vector_onnx_run(model_data, metadata, inputs);
}
 
std::vector<std::string>
dbms_vector_onnx_run(const bytea *model_data, Jsonb *metadata,
                     const std::vector<std::string> &inputs)
{
    DbmsVectorOrtSession session;
    std::vector<std::string> vectors;
 
    dbms_vector_ort_session_create(model_data, session);
 
    PG_TRY();
    {
        dbms_vector_ort_resolve_contract(session, metadata);
        vectors = dbms_vector_ort_run_session(session, inputs);
    }
    PG_CATCH();
    {
        dbms_vector_ort_session_destroy(session);
        PG_RE_THROW();
    }
    PG_END_TRY();
 
    dbms_vector_ort_session_destroy(session);
 
    return vectors;
}
#else /* !USE_ONNXRUNTIME */
 
bool
dbms_vector_onnx_available()
{
    return false;
}
 
/*
 * Without --with-onnxruntime the caller never reaches these: the provider
 * dispatch raises the deferred-inference error first.  Keep trivial bodies
 * so the translation unit stays linkable.
 */
void
dbms_vector_onnx_validate(bytea *model_data, Jsonb *metadata)
{
    (void) model_data;
    (void) metadata;
}
 
std::vector<std::string>
dbms_vector_onnx_run(const bytea *model_data, Jsonb *metadata,
                     const std::vector<std::string> &inputs)
{
    (void) model_data;
    (void) metadata;
    (void) inputs;
 
    return {};
}
 
std::vector<std::string>
dbms_vector_onnx_run_cached(const char *owner, const char *model_name,
                            const bytea *model_data, Jsonb *metadata,
                            const std::vector<std::string> &inputs)
{
    (void) owner;
    (void) model_name;
 
    return dbms_vector_onnx_run(model_data, metadata, inputs);
}
 
void
dbms_vector_onnx_pin(const char *owner, const char *model_name,
                     const bytea *model_data, Jsonb *metadata)
{
    /* Unreachable: the SQL facade gates on runtime availability first. */
    (void) owner;
    (void) model_name;
    (void) model_data;
    (void) metadata;
}
 
#endif /* USE_ONNXRUNTIME */