#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 #include #include 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" * ({"": ["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\":{\"\":[\"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\":\"\"}."); 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 dbms_vector_ort_run_session(DbmsVectorOrtSession &session, const std::vector &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 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 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 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 dbms_vector_onnx_run_cached(const char *owner, const char *model_name, const bytea *model_data, Jsonb *metadata, const std::vector &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 dbms_vector_onnx_run(const bytea *model_data, Jsonb *metadata, const std::vector &inputs) { DbmsVectorOrtSession session; std::vector 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 dbms_vector_onnx_run(const bytea *model_data, Jsonb *metadata, const std::vector &inputs) { (void) model_data; (void) metadata; (void) inputs; return {}; } std::vector dbms_vector_onnx_run_cached(const char *owner, const char *model_name, const bytea *model_data, Jsonb *metadata, const std::vector &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 */