refactor(diskann): decouple from libaio via dlopen (#532)
Co-authored-by: Zefeng Yin <yinzefeng.yzf@alibaba-inc.com>
This commit is contained in:
@@ -49,7 +49,6 @@ cc_directory(quantizer)
|
||||
cc_directory(utility)
|
||||
cc_directory(interface)
|
||||
cc_directory(mixed_reducer)
|
||||
cc_directory(plugin)
|
||||
|
||||
git_version(GIT_SRCS_VER ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
file(GLOB_RECURSE ALL_CORE_SRCS *.cc *.c *.h)
|
||||
@@ -63,17 +62,17 @@ endif()
|
||||
|
||||
# Always exclude algorithm/diskann implementation files from zvec_core.
|
||||
# The DiskAnn algorithm is provided by the separate core_knn_diskann library
|
||||
# (real on Linux x86_64, stub on other platforms). Including them here causes
|
||||
# duplicate symbols and missing -laio when test binaries link both zvec_core
|
||||
# (via zvec) and core_knn_diskann.
|
||||
|
||||
# (STATIC+SHARED, real on Linux x86_64, stub on other platforms). The static
|
||||
# variant is whole-archived into _zvec.so for the Python wheel; the shared
|
||||
# variant is used by C++ tools and tests. Including the sources here would
|
||||
# cause duplicate symbols.
|
||||
list(FILTER ALL_CORE_SRCS EXCLUDE REGEX ".*/algorithm/diskann/.*")
|
||||
if(NOT DISKANN_SUPPORTED)
|
||||
list(FILTER ALL_CORE_SRCS EXCLUDE REGEX ".*/interface/indexes/diskann_index\\.cc")
|
||||
endif()
|
||||
|
||||
set(ZVEC_CORE_LIBS zvec_ailego zvec_turbo sparsehash magic_enum rabitqlib)
|
||||
# The plugin loader uses dlopen/dlsym, so link libdl on Linux.
|
||||
# The DiskAnn runtime loader uses dlopen/dlsym, so link libdl on Linux.
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
list(APPEND ZVEC_CORE_LIBS ${CMAKE_DL_LIBS})
|
||||
endif()
|
||||
|
||||
@@ -23,7 +23,12 @@ else()
|
||||
|
||||
if(MSVC)
|
||||
# MSVC: STATIC-only stub to avoid creating an empty DLL with no exports
|
||||
# (MSVC linker fails to produce an import library when there are zero exports)
|
||||
# (MSVC linker fails to produce an import library when there are zero exports).
|
||||
# cc_library with STATIC-only creates target "core_knn_diskann" but NOT the
|
||||
# "core_knn_diskann_static" variant (that only happens with STATIC+SHARED).
|
||||
# The Python binding references core_knn_diskann_static on all platforms, so
|
||||
# create an ALIAS so the same target name works under MSVC as well.
|
||||
# ($<TARGET_FILE:> supports ALIAS targets since CMake 3.18.)
|
||||
cc_library(
|
||||
NAME core_knn_diskann
|
||||
STATIC STRICT ALWAYS_LINK
|
||||
@@ -32,6 +37,7 @@ else()
|
||||
INCS . ${PROJECT_ROOT_DIR}/src ${PROJECT_ROOT_DIR}/src/core ${PROJECT_ROOT_DIR}/src/core/algorithm
|
||||
VERSION "${PROXIMA_ZVEC_VERSION}"
|
||||
)
|
||||
add_library(core_knn_diskann_static ALIAS core_knn_diskann)
|
||||
else()
|
||||
cc_library(
|
||||
NAME core_knn_diskann
|
||||
|
||||
@@ -1,57 +1,34 @@
|
||||
include(${PROJECT_ROOT_DIR}/cmake/bazel.cmake)
|
||||
include(${PROJECT_ROOT_DIR}/cmake/option.cmake)
|
||||
|
||||
file(GLOB_RECURSE ALL_SRCS *.cc *.c)
|
||||
|
||||
# The DiskAnn plugin is loaded at runtime via zvec::LoadDiskAnnPlugin() with
|
||||
# RTLD_GLOBAL, so its undefined references to internal zvec symbols
|
||||
# (core_framework, core_knn_cluster, zvec_ailego, ...) are resolved at load
|
||||
# time against the hosting binary (_zvec.so for the Python extension, the
|
||||
# test executable for gtest, or libzvec_core for tools).
|
||||
# DiskAnn is compiled as a STATIC+SHARED library (matching the pattern used by
|
||||
# core_knn_hnsw, core_knn_cluster, etc.). The static variant
|
||||
# (core_knn_diskann_static) is whole-archived into _zvec.so for the Python
|
||||
# wheel, so no separate runtime .so is needed. The shared variant is used by
|
||||
# C++ tools and tests that link against it directly.
|
||||
#
|
||||
# As a consequence the plugin .so must NOT carry NEEDED entries for those
|
||||
# libs: otherwise the dynamic loader would try to resolve them from disk
|
||||
# before invoking dlopen's RTLD_GLOBAL symbol sharing, and the Python wheel
|
||||
# (which only ships _zvec.so + the plugin) would fail to load.
|
||||
#
|
||||
# We therefore link the plugin only against its system-level dependency
|
||||
# (libaio) and rely on the global include dirs plus -Wl,--unresolved-symbols
|
||||
# =ignore-all to let the linker build a shared library with unresolved
|
||||
# references to internal APIs.
|
||||
set(CORE_KNN_DISKANN_LIBS "")
|
||||
# libaio is loaded at runtime via dlopen()/dlsym() (see libaio_loader.h), so
|
||||
# we do NOT link against -laio. The only system-level link dependency is
|
||||
# ${CMAKE_DL_LIBS} for dlopen/dlsym/dlclose.
|
||||
set(CORE_KNN_DISKANN_LIBS core_framework core_knn_cluster)
|
||||
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|i686|i386")
|
||||
list(APPEND CORE_KNN_DISKANN_LIBS aio)
|
||||
list(APPEND CORE_KNN_DISKANN_LIBS ${CMAKE_DL_LIBS})
|
||||
endif()
|
||||
|
||||
if(NOT APPLE)
|
||||
set(CORE_KNN_DISKANN_LDFLAGS
|
||||
"-Wl,--exclude-libs,libparquet.a:libarrow.a:libarrow_bundled_dependencies.a")
|
||||
endif()
|
||||
|
||||
cc_library(
|
||||
NAME core_knn_diskann
|
||||
SHARED STRICT
|
||||
STATIC SHARED STRICT ALWAYS_LINK
|
||||
SRCS *.cc
|
||||
LIBS ${CORE_KNN_DISKANN_LIBS}
|
||||
INCS . ${PROJECT_ROOT_DIR}/src/core ${PROJECT_ROOT_DIR}/src/core/algorithm
|
||||
LDFLAGS "${CORE_KNN_DISKANN_LDFLAGS}"
|
||||
VERSION "${PROXIMA_ZVEC_VERSION}"
|
||||
)
|
||||
|
||||
# Internal zvec libs are referenced only for header availability; the actual
|
||||
# symbol resolution happens at dlopen time. Expose their public include dirs
|
||||
# without adding them as link dependencies.
|
||||
foreach(_dep zvec_ailego core_framework core_knn_cluster)
|
||||
if(TARGET ${_dep})
|
||||
target_include_directories(core_knn_diskann PRIVATE
|
||||
$<TARGET_PROPERTY:${_dep},INTERFACE_INCLUDE_DIRECTORIES>)
|
||||
add_dependencies(core_knn_diskann ${_dep})
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
# Allow the plugin to have unresolved symbols that will be satisfied at
|
||||
# dlopen(RTLD_NOW | RTLD_GLOBAL) time by the hosting binary.
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
target_link_options(core_knn_diskann PRIVATE
|
||||
"LINKER:--unresolved-symbols=ignore-all")
|
||||
endif()
|
||||
|
||||
# Rename the artifact to libzvec_diskann_plugin.so so it is clearly identified
|
||||
# as an optional plugin that users load at runtime via zvec::LoadDiskAnnPlugin().
|
||||
set_target_properties(core_knn_diskann PROPERTIES
|
||||
OUTPUT_NAME zvec_diskann_plugin
|
||||
)
|
||||
@@ -32,6 +32,8 @@ namespace core {
|
||||
int DiskAnnBuilder::init(const IndexMeta &meta, const ailego::Params ¶ms) {
|
||||
LOG_INFO("Begin DiskAnnBuilder::init");
|
||||
|
||||
log_diskann_io_backend();
|
||||
|
||||
params.get(PARAM_DISKANN_BUILDER_MAX_DEGREE, &max_degree_);
|
||||
params.get(PARAM_DISKANN_BUILDER_LIST_SIZE, &list_size_);
|
||||
params.get(PARAM_DISKANN_BUILDER_THREAD_COUNT, &build_thread_count_);
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include <ailego/io/io_backend_def.h>
|
||||
#include <zvec/ailego/io/io_backend.h>
|
||||
#include <zvec/core/framework/index_logger.h>
|
||||
|
||||
#define MAX_EVENTS 1024
|
||||
@@ -28,11 +30,36 @@ namespace core {
|
||||
#if (defined(__linux) || defined(__linux__))
|
||||
typedef struct io_event io_event_t;
|
||||
typedef struct iocb iocb_t;
|
||||
|
||||
// Ensures the I/O backend selection is logged exactly once per process,
|
||||
// regardless of which entry point (setup_io_ctx or register_thread)
|
||||
// triggers it first.
|
||||
static std::once_flag g_io_backend_log_once;
|
||||
#endif
|
||||
|
||||
void log_diskann_io_backend() {
|
||||
#if (defined(__linux) || defined(__linux__))
|
||||
auto &backend = ailego::IOBackend::Instance();
|
||||
if (backend.is_pread()) {
|
||||
LOG_WARN(
|
||||
"DiskAnn: no async I/O backend available. Install libaio (e.g. "
|
||||
"'apt-get install libaio1', or 'libaio1t64' on Ubuntu 24.04+) and "
|
||||
"retry. DiskAnn will fall back to synchronous pread() — performance "
|
||||
"will be degraded.");
|
||||
} else {
|
||||
LOG_INFO("DiskAnn: I/O backend '%s' loaded — async I/O enabled.",
|
||||
backend.name());
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
int setup_io_ctx(IOContext &ctx) {
|
||||
#if (defined(__linux) || defined(__linux__))
|
||||
int ret = io_setup(MAX_EVENTS, &ctx);
|
||||
std::call_once(g_io_backend_log_once, log_diskann_io_backend);
|
||||
if (ailego::IOBackend::Instance().is_pread()) {
|
||||
return 0;
|
||||
}
|
||||
int ret = LibAioLoader::Instance().io_setup(MAX_EVENTS, &ctx);
|
||||
|
||||
return ret;
|
||||
#else
|
||||
@@ -42,7 +69,10 @@ int setup_io_ctx(IOContext &ctx) {
|
||||
|
||||
int destroy_io_ctx(IOContext &ctx) {
|
||||
#if (defined(__linux) || defined(__linux__))
|
||||
int ret = io_destroy(ctx);
|
||||
if (ailego::IOBackend::Instance().is_pread()) {
|
||||
return 0;
|
||||
}
|
||||
int ret = LibAioLoader::Instance().io_destroy(ctx);
|
||||
|
||||
return ret;
|
||||
#else
|
||||
@@ -71,6 +101,9 @@ static int execute_io_pread(int fd, std::vector<AlignedRead> &read_reqs) {
|
||||
int execute_io(IOContext ctx, int fd, std::vector<AlignedRead> &read_reqs,
|
||||
uint64_t n_retries = 0) {
|
||||
#if (defined(__linux) || defined(__linux__))
|
||||
if (ailego::IOBackend::Instance().is_pread()) {
|
||||
return execute_io_pread(fd, read_reqs);
|
||||
}
|
||||
uint64_t iters = DiskAnnUtil::div_round_up(read_reqs.size(), MAX_EVENTS);
|
||||
|
||||
for (uint64_t iter = 0; iter < iters; iter++) {
|
||||
@@ -93,7 +126,8 @@ int execute_io(IOContext ctx, int fd, std::vector<AlignedRead> &read_reqs,
|
||||
size_t n_tries = 0;
|
||||
// Phase 1: io_submit with retry.
|
||||
while (true) {
|
||||
int ret = io_submit(ctx, (int64_t)n_ops, cbs.data());
|
||||
int ret =
|
||||
LibAioLoader::Instance().io_submit(ctx, (int64_t)n_ops, cbs.data());
|
||||
if (ret == (int)n_ops) {
|
||||
break;
|
||||
}
|
||||
@@ -111,8 +145,8 @@ int execute_io(IOContext ctx, int fd, std::vector<AlignedRead> &read_reqs,
|
||||
// Phase 2: io_getevents with retry (never re-submits).
|
||||
n_tries = 0;
|
||||
while (true) {
|
||||
int ret = io_getevents(ctx, (int64_t)n_ops, (int64_t)n_ops, evts.data(),
|
||||
nullptr);
|
||||
int ret = LibAioLoader::Instance().io_getevents(
|
||||
ctx, (int64_t)n_ops, (int64_t)n_ops, evts.data(), nullptr);
|
||||
if (ret == (int)n_ops) {
|
||||
break;
|
||||
}
|
||||
@@ -188,16 +222,19 @@ void LinuxAlignedFileReader::register_thread() {
|
||||
|
||||
IOContext ctx = nullptr;
|
||||
|
||||
int ret = io_setup(MAX_EVENTS, &ctx);
|
||||
if (ret != 0) {
|
||||
std::call_once(g_io_backend_log_once, log_diskann_io_backend);
|
||||
if (ailego::IOBackend::Instance().is_pread()) {
|
||||
lk.unlock();
|
||||
return;
|
||||
}
|
||||
int ret = LibAioLoader::Instance().io_setup(MAX_EVENTS, &ctx);
|
||||
if (ret != 0) {
|
||||
if (ret == -EAGAIN) {
|
||||
LOG_ERROR(
|
||||
"io_setup failed with EAGAIN: Consider increasing "
|
||||
"/proc/sys/fs/aio-max-nr");
|
||||
} else {
|
||||
LOG_ERROR("io_setup failed; returned: %d, %s", ret, ::strerror(-ret));
|
||||
;
|
||||
}
|
||||
} else {
|
||||
LOG_INFO("allocating ctx: %lu", (uint64_t)ctx);
|
||||
@@ -226,7 +263,10 @@ void LinuxAlignedFileReader::deregister_thread() {
|
||||
}
|
||||
|
||||
// io_destroy is a syscall; keep it outside the lock to avoid blocking others
|
||||
io_destroy(ctx);
|
||||
if (ailego::IOBackend::Instance().available() !=
|
||||
ailego::IOBackendType::kPread) {
|
||||
LibAioLoader::Instance().io_destroy(ctx);
|
||||
}
|
||||
LOG_INFO("returned ctx from thread");
|
||||
#endif
|
||||
}
|
||||
@@ -234,9 +274,13 @@ void LinuxAlignedFileReader::deregister_thread() {
|
||||
void LinuxAlignedFileReader::deregister_all_threads() {
|
||||
#if (defined(__linux) || defined(__linux__))
|
||||
std::unique_lock<std::mutex> lk(ctx_mut);
|
||||
bool aio_available = ailego::IOBackend::Instance().available() !=
|
||||
ailego::IOBackendType::kPread;
|
||||
for (auto x = ctx_map.begin(); x != ctx_map.end(); x++) {
|
||||
IOContext ctx = x->second;
|
||||
io_destroy(ctx);
|
||||
if (aio_available) {
|
||||
LibAioLoader::Instance().io_destroy(ctx);
|
||||
}
|
||||
}
|
||||
ctx_map.clear();
|
||||
#endif
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
#include <fcntl.h>
|
||||
|
||||
#if (defined(__linux) || defined(__linux__))
|
||||
#include <libaio.h>
|
||||
#include <ailego/io/libaio_loader.h> // dlopen-based libaio wrapper
|
||||
#endif
|
||||
|
||||
#include <unistd.h>
|
||||
@@ -39,6 +39,10 @@ typedef uint32_t IOContext;
|
||||
int setup_io_ctx(IOContext &ctx);
|
||||
int destroy_io_ctx(IOContext &ctx);
|
||||
|
||||
// Log the current DiskAnn I/O backend status (async vs. synchronous pread).
|
||||
// Probes the backend on first call. No-op on non-Linux platforms.
|
||||
void log_diskann_io_backend();
|
||||
|
||||
struct AlignedRead {
|
||||
uint64_t offset;
|
||||
uint64_t len;
|
||||
|
||||
@@ -25,6 +25,8 @@ DiskAnnSearcher::DiskAnnSearcher() {}
|
||||
DiskAnnSearcher::~DiskAnnSearcher() {}
|
||||
|
||||
int DiskAnnSearcher::init(const ailego::Params &search_params) {
|
||||
log_diskann_io_backend();
|
||||
|
||||
search_params.get(PARAM_DISKANN_SEARCHER_LIST_SIZE, &list_size_);
|
||||
search_params.get(PARAM_DISKANN_SEARCHER_CACHE_NODE_NUM, &cache_nodes_num_);
|
||||
return 0;
|
||||
|
||||
@@ -28,6 +28,9 @@ DiskAnnStreamer::~DiskAnnStreamer() {}
|
||||
int DiskAnnStreamer::init(const IndexMeta &meta,
|
||||
const ailego::Params &search_params) {
|
||||
meta_ = meta;
|
||||
|
||||
log_diskann_io_backend();
|
||||
|
||||
search_params.get(PARAM_DISKANN_SEARCHER_LIST_SIZE, &list_size_);
|
||||
search_params.get(PARAM_DISKANN_SEARCHER_CACHE_NODE_NUM, &cache_nodes_num_);
|
||||
return 0;
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
include(${PROJECT_ROOT_DIR}/cmake/bazel.cmake)
|
||||
include(${PROJECT_ROOT_DIR}/cmake/option.cmake)
|
||||
|
||||
set(CORE_INTERFACE_LIBS zvec_ailego core_framework sparsehash magic_enum rabitqlib)
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
list(APPEND CORE_INTERFACE_LIBS ${CMAKE_DL_LIBS})
|
||||
endif()
|
||||
|
||||
cc_library(
|
||||
NAME core_interface STATIC STRICT ALWAYS_LINK
|
||||
SRCS *.cc indexes/*.cc
|
||||
INCS . ${PROJECT_ROOT_DIR}/src/ ${PROJECT_ROOT_DIR}/src/core
|
||||
LIBS zvec_ailego core_framework core_plugin sparsehash magic_enum rabitqlib
|
||||
LIBS ${CORE_INTERFACE_LIBS}
|
||||
VERSION "${PROXIMA_ZVEC_VERSION}"
|
||||
)
|
||||
|
||||
@@ -16,61 +16,12 @@
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <zvec/core/interface/index.h>
|
||||
#include <zvec/plugin/diskann_plugin.h>
|
||||
#include "algorithm/diskann/diskann_params.h"
|
||||
#include "holder_builder.h"
|
||||
|
||||
namespace zvec::core_interface {
|
||||
|
||||
namespace {
|
||||
|
||||
// Implicitly bring the DiskAnn runtime online on first use. This keeps the
|
||||
// DiskAnn index an ordinary public API (users just instantiate a
|
||||
// DiskAnnIndexParam) while still letting the rest of the library — HNSW,
|
||||
// IVF, Flat, Vamana — run on hosts that happen to lack libaio. On such
|
||||
// hosts only DiskAnn fails, with a clear, actionable error message, and
|
||||
// every other index type stays fully functional.
|
||||
int EnsureDiskAnnRuntimeReady() {
|
||||
static std::once_flag once;
|
||||
static int cached_result = 0;
|
||||
std::call_once(once, []() {
|
||||
const int status = ::zvec::LoadDiskAnnPlugin();
|
||||
if (status == kDiskAnnPluginOk) {
|
||||
cached_result = 0;
|
||||
return;
|
||||
}
|
||||
switch (status) {
|
||||
case kDiskAnnPluginLibAioMissing:
|
||||
LOG_ERROR(
|
||||
"DiskAnn requires libaio at runtime, but it was not found on this "
|
||||
"host. Install it (e.g. 'apt-get install libaio1' on "
|
||||
"Debian/Ubuntu, "
|
||||
"or 'libaio1t64' on Ubuntu 24.04+) and retry.");
|
||||
break;
|
||||
case kDiskAnnPluginUnsupportedPlatform:
|
||||
LOG_ERROR("DiskAnn is only supported on Linux x86_64.");
|
||||
break;
|
||||
case kDiskAnnPluginDlopenFailed:
|
||||
default:
|
||||
LOG_ERROR("Failed to initialize the DiskAnn runtime (status=%d).",
|
||||
status);
|
||||
break;
|
||||
}
|
||||
cached_result = core::IndexError_Runtime;
|
||||
});
|
||||
return cached_result;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int DiskAnnIndex::CreateAndInitStreamer(const BaseIndexParam ¶m) {
|
||||
// Fail fast and cleanly if the DiskAnn runtime cannot be brought up on
|
||||
// this host (most commonly: libaio is missing). The rest of zvec keeps
|
||||
// running; only DiskAnn is unusable.
|
||||
if (int rc = EnsureDiskAnnRuntimeReady(); rc != 0) {
|
||||
return rc;
|
||||
}
|
||||
|
||||
if (is_sparse_) {
|
||||
LOG_ERROR("Failed to create streamer. Sparse is not Supported.");
|
||||
return core::IndexError_Unsupported;
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
##
|
||||
## Copyright (C) The Software Authors. All rights reserved.
|
||||
##
|
||||
## \file CMakeLists.txt
|
||||
## \brief Build script for the zvec internal plugin-loading glue library.
|
||||
## Lives inside the main zvec_core artifact and provides the
|
||||
## implicit DiskAnn runtime bring-up used by DiskAnnIndex on first
|
||||
## use. These APIs are NOT part of the public user surface: users
|
||||
## simply instantiate ``DiskAnnIndexParam`` / ``DiskAnnIndex`` and
|
||||
## the runtime (``libzvec_diskann_plugin.so``) is loaded behind
|
||||
## the scenes.
|
||||
##
|
||||
|
||||
include(${PROJECT_ROOT_DIR}/cmake/bazel.cmake)
|
||||
include(${PROJECT_ROOT_DIR}/cmake/option.cmake)
|
||||
|
||||
set(CORE_PLUGIN_LIBS zvec_ailego core_framework)
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
list(APPEND CORE_PLUGIN_LIBS ${CMAKE_DL_LIBS})
|
||||
endif()
|
||||
|
||||
cc_library(
|
||||
NAME core_plugin
|
||||
STATIC STRICT ALWAYS_LINK
|
||||
SRCS *.cc
|
||||
LIBS ${CORE_PLUGIN_LIBS}
|
||||
INCS . ${PROJECT_ROOT_DIR}/src/core
|
||||
VERSION "${PROXIMA_ZVEC_VERSION}"
|
||||
)
|
||||
@@ -1,322 +0,0 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <zvec/core/framework/index_logger.h>
|
||||
#include <zvec/plugin/diskann_plugin.h>
|
||||
|
||||
#if defined(__linux__) || defined(__linux) || defined(__APPLE__)
|
||||
#include <dlfcn.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#if defined(__linux__) || defined(__linux)
|
||||
#include <limits.h>
|
||||
#endif
|
||||
|
||||
namespace zvec {
|
||||
|
||||
namespace {
|
||||
|
||||
#if defined(__linux__) || defined(__linux)
|
||||
constexpr const char *kPluginFileName = "libzvec_diskann_plugin.so";
|
||||
// Candidate soname list. On Ubuntu 24.04 the libaio package was renamed with
|
||||
// the t64 suffix (64-bit time_t transition), so we probe both spellings.
|
||||
constexpr const char *kLibAioSoNames[] = {
|
||||
"libaio.so.1",
|
||||
"libaio.so.1t64",
|
||||
};
|
||||
constexpr bool kPlatformSupportsDiskAnnPlugin = true;
|
||||
#elif defined(__APPLE__)
|
||||
[[maybe_unused]] constexpr const char *kPluginFileName =
|
||||
"libzvec_diskann_plugin.dylib";
|
||||
constexpr bool kPlatformSupportsDiskAnnPlugin = false;
|
||||
#else
|
||||
[[maybe_unused]] constexpr const char *kPluginFileName =
|
||||
"zvec_diskann_plugin.dll";
|
||||
constexpr bool kPlatformSupportsDiskAnnPlugin = false;
|
||||
#endif
|
||||
|
||||
// Global plugin handle. Nullptr means "not loaded".
|
||||
std::atomic<void *> g_plugin_handle{nullptr};
|
||||
std::mutex g_plugin_mutex;
|
||||
|
||||
#if defined(__linux__) || defined(__linux)
|
||||
|
||||
// Resolve the directory containing the currently running executable, so we
|
||||
// can look for the plugin next to it regardless of the working directory.
|
||||
std::string GetExecutableDir() {
|
||||
char buf[PATH_MAX];
|
||||
ssize_t n = ::readlink("/proc/self/exe", buf, sizeof(buf) - 1);
|
||||
if (n <= 0) {
|
||||
return {};
|
||||
}
|
||||
buf[n] = '\0';
|
||||
std::string path(buf);
|
||||
auto slash = path.find_last_of('/');
|
||||
if (slash == std::string::npos) {
|
||||
return {};
|
||||
}
|
||||
return path.substr(0, slash);
|
||||
}
|
||||
|
||||
// Resolve the directory containing the shared object that hosts this
|
||||
// function. For Python wheels this is the directory of
|
||||
// ``_zvec.cpython-*.so``; for regular C++ binaries it is the directory of
|
||||
// ``libzvec_core.so``. In either case the DiskAnn plugin is shipped
|
||||
// alongside, so this is the most reliable lookup location.
|
||||
//
|
||||
// NOTE: we pass the address of an *exported* function (LoadDiskAnnPlugin)
|
||||
// rather than one in this anonymous namespace, because dladdr() on a symbol
|
||||
// with internal linkage can report the main executable instead of the
|
||||
// hosting shared object when the translation unit is whole-archived into
|
||||
// another .so.
|
||||
std::string ResolveHostingSoDir() {
|
||||
::Dl_info info{};
|
||||
if (::dladdr(reinterpret_cast<void *>(&::zvec::LoadDiskAnnPlugin), &info) ==
|
||||
0 ||
|
||||
info.dli_fname == nullptr) {
|
||||
return {};
|
||||
}
|
||||
std::string path(info.dli_fname);
|
||||
auto slash = path.find_last_of('/');
|
||||
if (slash == std::string::npos) {
|
||||
return {};
|
||||
}
|
||||
return path.substr(0, slash);
|
||||
}
|
||||
|
||||
// Full path of the shared object that hosts LoadDiskAnnPlugin, or empty
|
||||
// string on failure.
|
||||
std::string ResolveHostingSoPath() {
|
||||
::Dl_info info{};
|
||||
if (::dladdr(reinterpret_cast<void *>(&::zvec::LoadDiskAnnPlugin), &info) ==
|
||||
0 ||
|
||||
info.dli_fname == nullptr) {
|
||||
return {};
|
||||
}
|
||||
return std::string(info.dli_fname);
|
||||
}
|
||||
|
||||
// Promote the hosting shared object (e.g. the Python extension module
|
||||
// ``_zvec.cpython-*.so``) to the global symbol scope. Python loads C
|
||||
// extensions with RTLD_LOCAL by default, which means their C++ symbols are
|
||||
// invisible to subsequently dlopen(RTLD_GLOBAL)ed libraries. Without this
|
||||
// promotion, the DiskAnn plugin's undefined references to zvec:: symbols
|
||||
// cannot be resolved against the already-loaded host module and dlopen
|
||||
// fails with messages like:
|
||||
//
|
||||
// undefined symbol: _ZN4zvec6ailego6Logger10LEVEL_INFOE
|
||||
//
|
||||
// Using RTLD_NOLOAD re-opens the existing image without loading it again,
|
||||
// while RTLD_GLOBAL merges its symbols into the global scope. This is a
|
||||
// no-op for hosts that were already loaded with RTLD_GLOBAL.
|
||||
void PromoteHostingSoToGlobal() {
|
||||
const std::string host = ResolveHostingSoPath();
|
||||
if (host.empty()) {
|
||||
return;
|
||||
}
|
||||
// When LoadDiskAnnPlugin is statically linked into the main executable,
|
||||
// dladdr resolves to the executable itself. The main exe's symbols are
|
||||
// already in the global scope by definition, so skip promotion.
|
||||
const std::string exe_path = GetExecutableDir();
|
||||
if (!exe_path.empty()) {
|
||||
char exe_buf[PATH_MAX];
|
||||
ssize_t n = ::readlink("/proc/self/exe", exe_buf, sizeof(exe_buf) - 1);
|
||||
if (n > 0) {
|
||||
exe_buf[n] = '\0';
|
||||
// Compare resolved real paths to handle relative vs absolute.
|
||||
char host_real[PATH_MAX];
|
||||
char exe_real[PATH_MAX];
|
||||
if (::realpath(host.c_str(), host_real) != nullptr &&
|
||||
::realpath(exe_buf, exe_real) != nullptr &&
|
||||
std::string(host_real) == std::string(exe_real)) {
|
||||
// Host IS the main executable; symbols are already global.
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
void *h = ::dlopen(host.c_str(), RTLD_NOW | RTLD_GLOBAL | RTLD_NOLOAD);
|
||||
if (h == nullptr) {
|
||||
const char *err = ::dlerror();
|
||||
LOG_WARN("Could not promote host '%s' to RTLD_GLOBAL: %s", host.c_str(),
|
||||
err ? err : "unknown");
|
||||
return;
|
||||
}
|
||||
// We purposely keep the handle refcount incremented for the life of the
|
||||
// process: there is no safe point at which to dlclose() it, and doing so
|
||||
// would only decrement the count anyway (the image remains mapped because
|
||||
// Python still holds its own reference).
|
||||
(void)h;
|
||||
}
|
||||
|
||||
// Build the list of candidate paths for the plugin.
|
||||
std::vector<std::string> BuildCandidatePaths(const std::string &explicit_path) {
|
||||
std::vector<std::string> candidates;
|
||||
if (!explicit_path.empty()) {
|
||||
candidates.push_back(explicit_path);
|
||||
return candidates;
|
||||
}
|
||||
|
||||
// Helper that pushes both ``<dir>/<plugin>`` and ``<dir>/../lib/<plugin>``
|
||||
// to handle the conventional CMake build layout where executables live in
|
||||
// ``bin/`` while shared objects (including this plugin) live in ``lib/``.
|
||||
auto push_dir_candidates = [&candidates](const std::string &dir) {
|
||||
if (dir.empty()) {
|
||||
return;
|
||||
}
|
||||
candidates.push_back(dir + "/" + kPluginFileName);
|
||||
candidates.push_back(dir + "/../lib/" + kPluginFileName);
|
||||
};
|
||||
|
||||
// 1. Directory of the library that hosts LoadDiskAnnPlugin (e.g. the
|
||||
// Python extension module or libzvec_core). This works for Python,
|
||||
// C++ embedding, and most packaging layouts.
|
||||
const std::string own_dir = ResolveHostingSoDir();
|
||||
push_dir_candidates(own_dir);
|
||||
// 2. Directory of the running executable. Useful for self-contained C++
|
||||
// tools that drop the plugin next to their binary, as well as for the
|
||||
// standard CMake bin/lib split (handled by ``../lib/`` above).
|
||||
const std::string exe_dir = GetExecutableDir();
|
||||
if (!exe_dir.empty() && exe_dir != own_dir) {
|
||||
push_dir_candidates(exe_dir);
|
||||
}
|
||||
// 3. Fallback: rely on the dynamic linker's default search path
|
||||
// (RPATH / LD_LIBRARY_PATH / /etc/ld.so.conf).
|
||||
candidates.emplace_back(kPluginFileName);
|
||||
return candidates;
|
||||
}
|
||||
|
||||
#endif // linux
|
||||
|
||||
} // namespace
|
||||
|
||||
bool IsLibAioAvailable() {
|
||||
#if defined(__linux__) || defined(__linux)
|
||||
const char *kRequiredSymbols[] = {"io_setup", "io_submit", "io_getevents",
|
||||
"io_destroy"};
|
||||
for (const char *soname : kLibAioSoNames) {
|
||||
// RTLD_LAZY keeps the cost low; we only need to know whether the library
|
||||
// is resolvable and exposes the symbols DiskAnn actually calls.
|
||||
void *handle = ::dlopen(soname, RTLD_LAZY);
|
||||
if (handle == nullptr) {
|
||||
continue;
|
||||
}
|
||||
bool ok = true;
|
||||
for (const char *sym : kRequiredSymbols) {
|
||||
if (::dlsym(handle, sym) == nullptr) {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
::dlclose(handle);
|
||||
if (ok) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool IsDiskAnnPluginLoaded() {
|
||||
return g_plugin_handle.load(std::memory_order_acquire) != nullptr;
|
||||
}
|
||||
|
||||
int LoadDiskAnnPlugin(const std::string &path) {
|
||||
if (!kPlatformSupportsDiskAnnPlugin) {
|
||||
LOG_ERROR(
|
||||
"DiskAnn plugin is not supported on this platform; it is only "
|
||||
"available on Linux x86_64 with libaio.");
|
||||
return kDiskAnnPluginUnsupportedPlatform;
|
||||
}
|
||||
|
||||
#if defined(__linux__) || defined(__linux)
|
||||
// Fast path: already loaded.
|
||||
if (g_plugin_handle.load(std::memory_order_acquire) != nullptr) {
|
||||
return kDiskAnnPluginOk;
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(g_plugin_mutex);
|
||||
if (g_plugin_handle.load(std::memory_order_relaxed) != nullptr) {
|
||||
return kDiskAnnPluginOk;
|
||||
}
|
||||
|
||||
if (!IsLibAioAvailable()) {
|
||||
LOG_ERROR(
|
||||
"libaio is not available on this host; the DiskAnn runtime cannot be "
|
||||
"activated. Install libaio1 (e.g. 'apt-get install libaio1', or "
|
||||
"'libaio1t64' on Ubuntu 24.04+) and retry. This does not affect "
|
||||
"other index types (HNSW, IVF, Flat, Vamana).");
|
||||
return kDiskAnnPluginLibAioMissing;
|
||||
}
|
||||
|
||||
const std::vector<std::string> candidates = BuildCandidatePaths(path);
|
||||
// Ensure the hosting module's C++ symbols (zvec::*) are visible to the
|
||||
// plugin at dlopen time. See PromoteHostingSoToGlobal() for the rationale.
|
||||
PromoteHostingSoToGlobal();
|
||||
void *handle = nullptr;
|
||||
std::string last_error;
|
||||
for (const std::string &candidate : candidates) {
|
||||
// RTLD_GLOBAL so the plugin's factory registrations (which live in the
|
||||
// plugin's own static-init code) can reference symbols from the main
|
||||
// library, and any callers that later dlsym against the process can see
|
||||
// the plugin's symbols.
|
||||
handle = ::dlopen(candidate.c_str(), RTLD_NOW | RTLD_GLOBAL);
|
||||
if (handle != nullptr) {
|
||||
LOG_INFO("Loaded DiskAnn plugin from: %s", candidate.c_str());
|
||||
break;
|
||||
}
|
||||
const char *err = ::dlerror();
|
||||
last_error = err ? err : "unknown dlopen error";
|
||||
LOG_DEBUG("dlopen(%s) failed: %s", candidate.c_str(), last_error.c_str());
|
||||
}
|
||||
|
||||
if (handle == nullptr) {
|
||||
LOG_ERROR("Failed to load DiskAnn plugin; last error: %s",
|
||||
last_error.c_str());
|
||||
return kDiskAnnPluginDlopenFailed;
|
||||
}
|
||||
|
||||
g_plugin_handle.store(handle, std::memory_order_release);
|
||||
return kDiskAnnPluginOk;
|
||||
#else
|
||||
(void)path;
|
||||
return kDiskAnnPluginUnsupportedPlatform;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool UnloadDiskAnnPlugin() {
|
||||
#if defined(__linux__) || defined(__linux)
|
||||
std::lock_guard<std::mutex> lock(g_plugin_mutex);
|
||||
void *handle = g_plugin_handle.exchange(nullptr, std::memory_order_acq_rel);
|
||||
if (handle == nullptr) {
|
||||
return false;
|
||||
}
|
||||
if (::dlclose(handle) != 0) {
|
||||
const char *err = ::dlerror();
|
||||
LOG_WARN("dlclose for DiskAnn plugin returned non-zero: %s",
|
||||
err ? err : "unknown");
|
||||
}
|
||||
return true;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
Reference in New Issue
Block a user