diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..ff344a0 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,6 @@ +.git +node_modules +build +prebuilds +tests/data +tools/w2v-to-json diff --git a/.github/workflows/prebuild.yml b/.github/workflows/prebuild.yml new file mode 100644 index 0000000..0435f1a --- /dev/null +++ b/.github/workflows/prebuild.yml @@ -0,0 +1,135 @@ +# Builds the N-API prebuilds and tests them on every supported Node version. +# +# - linux-x64 / linux-arm64: built inside public.ecr.aws/lambda/nodejs:22 +# (the bot-api Lambda runtime) via the Dockerfile, then checked against the +# Lambda glibc / libstdc++ symbol versions. +# - darwin-arm64 / darwin-x64: built with prebuildify on macOS runners. +# +# The `prebuilds` artifact of a green run holds prebuilds/-/ +# for all four targets; commit it before publishing. Nothing is published here. +# +# DRAFT: written alongside the 5.0.0 port, never run yet. + +name: prebuild + +on: + workflow_dispatch: + pull_request: + push: + tags: ['v*'] + +permissions: + contents: read + +# 4.0.1 NAN linux-x64 prebuild, used as the reference by tests/equivalence-test.js. +env: + REFERENCE_COMMIT: dd317b0 + +jobs: + build-linux: + strategy: + fail-fast: false + matrix: + include: + - arch: x64 + platform: linux/amd64 + runner: ubuntu-24.04 + - arch: arm64 + platform: linux/arm64 + runner: ubuntu-24.04-arm + runs-on: ${{ matrix.runner }} + steps: + - uses: actions/checkout@v4 + - uses: docker/setup-buildx-action@v3 + # Builds in the Lambda image and runs the smoke tests there (see Dockerfile). + - name: Build prebuild in the Lambda nodejs:22 image + run: > + docker buildx build --platform ${{ matrix.platform }} --target prebuilds + --output type=local,dest=prebuilds . + - name: Check glibc / libstdc++ symbol versions + run: ./scripts/check-prebuild-symbols.sh + - uses: actions/upload-artifact@v4 + with: + name: prebuild-linux-${{ matrix.arch }} + path: prebuilds/ + if-no-files-found: error + + build-darwin: + strategy: + fail-fast: false + matrix: + include: + - arch: arm64 + runner: macos-15 + - arch: x64 + runner: macos-15-intel + runs-on: ${{ matrix.runner }} + env: + MACOSX_DEPLOYMENT_TARGET: '11.0' + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - run: npm ci --ignore-scripts + - run: npx prebuildify --napi --strip + - name: Check architecture + run: file prebuilds/darwin-${{ matrix.arch }}/*.node + - uses: actions/upload-artifact@v4 + with: + name: prebuild-darwin-${{ matrix.arch }} + path: prebuilds/ + if-no-files-found: error + + test: + needs: [build-linux, build-darwin] + strategy: + fail-fast: false + matrix: + runner: [ubuntu-24.04, ubuntu-24.04-arm, macos-15, macos-15-intel] + node: [22, 24, 26] + runs-on: ${{ matrix.runner }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # the equivalence test reads the 4.0.1 prebuild from history + # Node 22 first, only to keep its path for the equivalence test: the 4.0.1 + # NAN reference only loads on Node 22 (ABI 127). + - uses: actions/setup-node@v4 + with: + node-version: 22 + - run: echo "REFERENCE_NODE=$(command -v node)" >> "$GITHUB_ENV" + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + - run: node --version && npm ci --ignore-scripts + - uses: actions/download-artifact@v4 + with: + pattern: prebuild-* + path: prebuilds + merge-multiple: true + - name: Make sure the prebuild (not a local compile) is what gets loaded + run: | + rm -rf build + node -e "const p = require('node-gyp-build').path('.'); console.log(p); if (!p.includes('/prebuilds/')) process.exit(1)" + - run: make test + - name: Equivalence with the 4.0.1 NAN binding (linux-x64 only) + if: matrix.runner == 'ubuntu-24.04' + run: | + git show "$REFERENCE_COMMIT:prebuilds/linux-x64/@calldesk+annoy-node.node" > "$RUNNER_TEMP/annoy-4.0.1.node" + make equivalence-test REFERENCE_BINDING="$RUNNER_TEMP/annoy-4.0.1.node" REFERENCE_NODE="$REFERENCE_NODE" + + collect: + needs: test + runs-on: ubuntu-24.04 + steps: + - uses: actions/download-artifact@v4 + with: + pattern: prebuild-* + path: prebuilds + merge-multiple: true + - run: find prebuilds -type f -exec ls -l {} + + - uses: actions/upload-artifact@v4 + with: + name: prebuilds + path: prebuilds/ diff --git a/.npmignore b/.npmignore index bc7b9d1..ec1ca62 100644 --- a/.npmignore +++ b/.npmignore @@ -7,3 +7,4 @@ tests/data/*.db tools/w2v-to-json build .npmignore +tools diff --git a/Dockerfile b/Dockerfile index 4e8ba1f..a6f7209 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,25 +1,38 @@ -FROM public.ecr.aws/lambda/nodejs:22 - -ENV LAMBDA_ENV=true +# Builds the Linux N-API prebuild inside the AWS Lambda nodejs:22 image +# (Amazon Linux 2023: glibc 2.34, GCC 11), so the binary only needs symbols +# the Lambda runtime provides. One build per architecture: +# +# docker buildx build --platform linux/amd64 --target prebuilds --output type=local,dest=prebuilds . +# docker buildx build --platform linux/arm64 --target prebuilds --output type=local,dest=prebuilds . +# +# (npm run prebuild:linux runs both, then scripts/check-prebuild-symbols.sh.) +# The result is prebuilds/linux-/@calldesk+annoy-node.napi.node, which +# node-gyp-build loads on any Node version with N-API >= 8. + +FROM public.ecr.aws/lambda/nodejs:22 AS build ENTRYPOINT [] - WORKDIR /build -# Install build tools (Python required by node-gyp) -RUN dnf install -y gcc gcc-c++ make python3 && \ +# node-gyp needs Python, make and a C++ compiler; prebuildify --strip needs binutils. +RUN dnf install -y gcc gcc-c++ make python3 binutils && \ dnf clean all -# Copy files -COPY package*.json ./ -COPY . . - -# Install dependencies without running install script (no prebuilds yet) +COPY package.json package-lock.json ./ RUN npm ci --ignore-scripts -# Compile using local Node 22 headers, then place in prebuilds directory -RUN npx node-gyp rebuild && \ - mkdir -p prebuilds/linux-x64 && \ - cp build/Release/addon.node prebuilds/linux-x64/@calldesk+annoy-node.node - -CMD ["echo", "Linux prebuild created"] +COPY binding.gyp addon.cc annoyindexwrapper.cc annoyindexwrapper.h annoylib.h kissrandom.h index.js ./ +RUN npx prebuildify --napi --strip && \ + rm -rf build + +# Smoke-test the prebuild (loaded through index.js / node-gyp-build, build/ +# removed above) in the runtime it targets. +COPY tests ./tests +RUN mkdir -p tests/data +RUN node tests/smalltest.js && \ + node tests/smalltest-manhattan.js && \ + node tests/wrong-input-test.js && \ + node tests/undefined-behaviour-test.js + +FROM scratch AS prebuilds +COPY --from=build /build/prebuilds/ / diff --git a/Makefile b/Makefile index 591b5f0..7c0dbd8 100644 --- a/Makefile +++ b/Makefile @@ -6,11 +6,30 @@ TESTDATADIR = tests/data build-wrapper: node-gyp rebuild +.PHONY: test big-test equivalence-test check-prebuilds + test: tests/data/text8-vector.json node tests/smalltest.js node tests/worker-thread-test.js node tests/smalltest-manhattan.js node tests/basictests.js basic-config.js + node tests/wrong-input-test.js + node tests/typed-array-test.js + node tests/undefined-behaviour-test.js + node --expose-gc tests/leak-test.js + node tests/external-memory-test.js + npm run test:types + +# Compares the binding under test with the 4.0.1 NAN prebuild (Node 22 only): +# make equivalence-test REFERENCE_BINDING=/path/to/4.0.1.node REFERENCE_NODE=/path/to/node22 +REFERENCE_NODE ?= $(shell command -v node) +equivalence-test: + @test -n "$(REFERENCE_BINDING)" || (echo "set REFERENCE_BINDING=<4.0.1 addon.node>" && exit 1) + ANNOY_REFERENCE_BINDING="$(REFERENCE_BINDING)" ANNOY_REFERENCE_NODE="$(REFERENCE_NODE)" node tests/equivalence-test.js + +# Fails if a prebuild needs a glibc / libstdc++ newer than the Lambda nodejs:22 image. +check-prebuilds: + ./scripts/check-prebuild-symbols.sh big-test: tests/data/GoogleNews-vectors-negative300.json node tests/basictests.js very-big-config.js diff --git a/README.md b/README.md index 855fd2c..1930f71 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ annoy-node Node bindings for [Annoy](https://github.com/spotify/annoy), an efficient Approximate Nearest Neighbors implementation written in C++. -**Version 4.0.1** (@calldesk fork): upgraded `nan` to `^2.27.0` for Node 22+ compatibility. Ships prebuilts for `darwin-arm64` and `linux-x64` targeting Node 22 — no build tools required on install. +**Version 5.0.0** (@calldesk fork): the binding is written against [N-API](https://nodejs.org/api/n-api.html) through [node-addon-api](https://github.com/nodejs/node-addon-api) (`NAPI_VERSION=10`, the latest stable Node-API) instead of NAN. One binary per platform loads on every Node.js release with Node-API 10 (Node >= 22.14; tested on 22, 24 and 26). The package only serves bot-api, which follows the AWS Lambda Node.js runtime, so it targets the current Node-API rather than older Node releases; nothing is compiled on install where a prebuild exists. JS API, results and the on-disk index format are unchanged from 4.0.1 (see "Compatibility with 4.x" below), with two additions: numeric typed arrays are accepted as vectors, and index memory is reported to V8. Status: Tests pass, including one that loads 3 million vectors, but API coverage is not complete. Run on OS X and Linux with Node 8, 10, and 12. Not tried on Windows yet. Support for Node 6.3 and 4.6 ended at version 2.0.1 of this package. @@ -30,17 +30,34 @@ There are a few minor differences in behavior: Installation ------------ - npm install annoy + npm install @calldesk/annoy-node -This package ships prebuilts for `darwin-arm64` and `linux-x64` (Node 22). No compiler or Python required on these platforms. +Prebuilds ship for: -To rebuild prebuilts after a Node version change: +| Platform | Built in | Notes | +|---|---|---| +| `linux-x64` | `public.ecr.aws/lambda/nodejs:22` (amd64) | glibc >= 2.14 | +| `linux-arm64` | `public.ecr.aws/lambda/nodejs:22` (arm64) | glibc >= 2.17 | +| `darwin-arm64`, `darwin-x64` | GitHub Actions macOS runners | built by `.github/workflows/prebuild.yml` (its `prebuilds` artifact) | - # darwin-arm64 (run on Apple Silicon, Node 22) - npm run build:prebuilt +Elsewhere (Windows, musl/Alpine, other architectures) `npm install` falls back to compiling with node-gyp, which needs Python and a C++ toolchain. - # linux-x64 (via Docker, matches Lambda environment) - npm run docker:build +### How prebuilds are built + +The Linux prebuilds are compiled inside the AWS Lambda `nodejs:22` image (Amazon Linux 2023, glibc 2.34) so they never need a newer glibc or libstdc++ than the Lambda runtime. Never commit a `.node` file compiled on a workstation: a recent distribution links against symbols the Lambda does not have (e.g. `sqrtf@GLIBC_2.43`). + + npm run prebuild:linux # linux-x64 + linux-arm64 via Docker buildx (arm64 under QEMU), then the symbol check + npm run check:prebuilds # fails if a Linux prebuild needs > GLIBC_2.34 or > GLIBCXX_3.4.33 + +Both Docker builds run the smoke tests inside the Lambda image. The darwin prebuilds (and all four, with tests on Node 22/24/26) are built by the `prebuild` GitHub Actions workflow: download its `prebuilds` artifact into `prebuilds/` before publishing. + +### Compatibility with 4.x + +- Same class, methods, argument coercion, defaults, return values and errors; `tests/wrong-input-test.js` passes against both the 4.0.1 NAN binary and 5.0.0. +- Bit-identical results and `.annoy` files: `tests/equivalence-test.js` compares 5.0.0 with the 4.0.1 prebuild (`make equivalence-test REFERENCE_BINDING=... REFERENCE_NODE=`). Indexes saved by either version load in the other. +- **Behaviour change: typed arrays are accepted as vectors.** `addItem` and `getNNsByVector` take a `Float32Array` (copied directly, no per-component conversion) or any other numeric typed array, with the same results as the equivalent `Array` (`tests/typed-array-test.js`). 4.0.1 ignored them: `addItem` added nothing and `getNNsByVector` returned `undefined`. BigInt arrays are still ignored. On 5000 vectors of 200 dimensions, `addItem` with `Float32Array` takes 2.6 ms instead of 46.6 ms with arrays, and `getNNsByVector` saves ~8 µs per query. +- **Index memory is reported to V8** (`napi_adjust_external_memory`): the heap nodes of a built index or the mapped file of a loaded one. The GC now collects indexes that are no longer referenced; with 4.0.1 a process loading a fresh index per request kept every dropped mapping until an unrelated GC (`tests/external-memory-test.js`: 1000 loads of a 4 MB index keep ~20 alive instead of ~360). +- Inputs that were undefined behaviour in 4.0.1 are now defined (`tests/undefined-behaviour-test.js`): asking for more neighbours than available returns only the real results (4.0.1 padded with garbage), querying an index without trees returns empty arrays (4.0.1 crashed), short vectors are zero-padded, and exceptions thrown while coercing arguments propagate to JS (4.0.1 aborted the process). Usage ----- @@ -79,10 +96,10 @@ Usage Development ------------ - npm install -g node-gyp - node-gyp rebuild + npm ci + npx node-gyp rebuild # local build in build/Release, preferred over prebuilds by node-gyp-build -Run `eslint .` and `make prettier` before committing. +Remove `build/` to test the prebuilds again. Run `eslint .` and `make prettier` before committing. Tests ----- @@ -92,7 +109,13 @@ Run tests with `make test`. You can also run tests individually: - This is a short baseline test: `node tests/smalltest.js` -- This is a test that uses 70K 200-dimension vectors: `node tests/basictests.js` +- This is a test that uses 70K 200-dimension vectors: `node tests/basictests.js basic-config.js` +- TypeScript declarations (`index.d.ts`, 5.0.0): `npm run test:types` compiles `tests/types.ts` under `--strict`; misuse (unknown metric, non-numeric vector, wrong result type) must fail to type-check +- Typed array vectors (5.0.0): `node tests/typed-array-test.js` +- External memory reporting (5.0.0): `node tests/external-memory-test.js` +- API contract and wrong input, identical to 4.0.1: `node tests/wrong-input-test.js` (set `ANNOY_BINDING=` to run it against another binary) +- Native memory is released: `node --expose-gc tests/leak-test.js` +- Equivalence with 4.0.1: `make equivalence-test REFERENCE_BINDING=<4.0.1 linux-x64 .node> REFERENCE_NODE=` (the 4.0.1 file is in git history at commit `dd317b0`) There is also a `big-test` target that is not a dependency of the `test` target. It loads about 3 million 300-dimension vectors. It takes about six minutes to run on good-for-2016 hardware. Before you can run it, you need to download [GoogleNews-vectors-negative300.bin](https://drive.google.com/file/d/0B7XkCwpI5KDYNlNUTTlSS21pQmM/edit?usp=sharing) to `tests/data`. diff --git a/addon.cc b/addon.cc index d676a98..eb41a35 100644 --- a/addon.cc +++ b/addon.cc @@ -1,10 +1,10 @@ -#include +#include #include "annoyindexwrapper.h" -void InitAll(v8::Local exports) { - AnnoyIndexWrapper::Init(exports); +// Context-aware by construction (NODE_API_MODULE): the addon keeps no +// per-process JS state, so it can be loaded in several worker threads. +Napi::Object InitAll(Napi::Env env, Napi::Object exports) { + return AnnoyIndexWrapper::Init(env, exports); } -NODE_MODULE_INIT() { - InitAll(exports); -} +NODE_API_MODULE(addon, InitAll) diff --git a/annoyindexwrapper.cc b/annoyindexwrapper.cc index 825856e..e4f63a1 100644 --- a/annoyindexwrapper.cc +++ b/annoyindexwrapper.cc @@ -1,315 +1,345 @@ #include "annoyindexwrapper.h" #include "kissrandom.h" +#include +#include #include -using namespace v8; -using namespace Nan; +namespace { -Nan::Persistent AnnoyIndexWrapper::constructor; +// Marks objects constructed by this class, so that prototype methods can +// reject any other receiver (napi_type_tag_object, N-API 8). +const napi_type_tag kAnnoyTypeTag = {0x5c1b0f3e9d2a4c71ULL, 0xa6e84d02b7f3195cULL}; -AnnoyIndexWrapper::AnnoyIndexWrapper(int dimensions, const char *metricString) : - annoyDimensions(dimensions) { +const napi_property_attributes kMethodAttributes = static_cast( + napi_writable | napi_enumerable | napi_configurable); - if (strcmp(metricString, "Angular") == 0) { - annoyIndex = new AnnoyIndex(dimensions); - } - else if (strcmp(metricString, "Manhattan") == 0) { - annoyIndex = new AnnoyIndex(dimensions); - } - else { - annoyIndex = new AnnoyIndex(dimensions); +// 4.0.1 read integers as `int x = undefined ? default : ToNumber(v)`, i.e. a +// double truncated to int. Keep the exact same conversion. +double numberOr(const Napi::Value& value, double defaultValue) { + return value.IsUndefined() ? defaultValue : value.ToNumber().DoubleValue(); +} + +// Converts the first `count` elements of a typed array to float, as +// ToNumber then a float cast would for the same values in an Array. +template +void copyTypedArray(const T* data, size_t count, std::vector& vec) { + for (size_t i = 0; i < count; ++i) { + vec[i] = static_cast(static_cast(data[i])); } } -AnnoyIndexWrapper::~AnnoyIndexWrapper() { - delete annoyIndex; +// Node-API 10: an internalized string, which V8 uses as a property key without +// converting it on every Set. +Napi::Value propertyKey(Napi::Env env, const char* name) { + napi_value key; + NAPI_THROW_IF_FAILED(env, node_api_create_property_key_utf8(env, name, NAPI_AUTO_LENGTH, &key), + Napi::Value()); + return Napi::Value(env, key); } -void AnnoyIndexWrapper::Init(v8::Local exports) { - Nan::HandleScope scope; - - // Prepare constructor template - v8::Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("Annoy").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(2); - - // Prototype - // Nan::SetPrototypeMethod(tpl, "value", GetValue); - // Nan::SetPrototypeMethod(tpl, "plusOne", PlusOne); - // Nan::SetPrototypeMethod(tpl, "multiply", Multiply); - Nan::SetPrototypeMethod(tpl, "addItem", AddItem); - Nan::SetPrototypeMethod(tpl, "build", Build); - Nan::SetPrototypeMethod(tpl, "save", Save); - Nan::SetPrototypeMethod(tpl, "load", Load); - Nan::SetPrototypeMethod(tpl, "unload", Unload); - Nan::SetPrototypeMethod(tpl, "getItem", GetItem); - Nan::SetPrototypeMethod(tpl, "getNNsByVector", GetNNSByVector); - Nan::SetPrototypeMethod(tpl, "getNNsByItem", GetNNSByItem); - Nan::SetPrototypeMethod(tpl, "getNItems", GetNItems); - Nan::SetPrototypeMethod(tpl, "getDistance", GetDistance); - - constructor.Reset(Nan::GetFunction(tpl).ToLocalChecked()); - Nan::Set(exports, Nan::New("Annoy").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked()); +} // namespace + +Napi::Object AnnoyIndexWrapper::Init(Napi::Env env, Napi::Object exports) { + Napi::Function ctor = DefineClass(env, "Annoy", {}); + + // Same names, order and attributes (writable, enumerable, configurable) as + // Nan::SetPrototypeMethod produced in 4.0.1. + Napi::Object proto = ctor.Get("prototype").As(); + proto.DefineProperties({ + Napi::PropertyDescriptor::Value("addItem", Napi::Function::New(env, "addItem"), kMethodAttributes), + Napi::PropertyDescriptor::Value("build", Napi::Function::New(env, "build"), kMethodAttributes), + Napi::PropertyDescriptor::Value("save", Napi::Function::New(env, "save"), kMethodAttributes), + Napi::PropertyDescriptor::Value("load", Napi::Function::New(env, "load"), kMethodAttributes), + Napi::PropertyDescriptor::Value("unload", Napi::Function::New(env, "unload"), kMethodAttributes), + Napi::PropertyDescriptor::Value("getItem", Napi::Function::New(env, "getItem"), kMethodAttributes), + Napi::PropertyDescriptor::Value("getNNsByVector", Napi::Function::New(env, "getNNsByVector"), kMethodAttributes), + Napi::PropertyDescriptor::Value("getNNsByItem", Napi::Function::New(env, "getNNsByItem"), kMethodAttributes), + Napi::PropertyDescriptor::Value("getNItems", Napi::Function::New(env, "getNItems"), kMethodAttributes), + Napi::PropertyDescriptor::Value("getDistance", Napi::Function::New(env, "getDistance"), kMethodAttributes), + }); + + exports.Set("Annoy", ctor); + return exports; } -void AnnoyIndexWrapper::New(const Nan::FunctionCallbackInfo& info) { +Napi::Value AnnoyIndexWrapper::OnCalledAsFunction(const Napi::CallbackInfo& info) { + return info.Env().Undefined(); +} - if (info.IsConstructCall()) { - // Invoked as constructor: `new AnnoyIndexWrapper(...)` - double dimensions = info[0]->IsUndefined() ? 0 : info[0]->NumberValue(Nan::GetCurrentContext()).FromJust(); - Local metricString; +AnnoyIndexWrapper::AnnoyIndexWrapper(const Napi::CallbackInfo& info) + : Napi::ObjectWrap(info) { + // Coerce both arguments before allocating anything: if a coercion throws, + // nothing has to be released. + double dimensions = numberOr(info[0], 0); + std::string metric; + if (!info[1].IsUndefined()) { + metric = info[1].ToString().Utf8Value(); + } - if (!info[1]->IsUndefined()) { - Nan::MaybeLocal s = Nan::To(info[1]); - if (!s.IsEmpty()) { - metricString = s.ToLocalChecked(); - } - } + annoyDimensions = (int)dimensions; + // strcmp on the C string, as 4.0.1 did (stops at an embedded NUL). + if (strcmp(metric.c_str(), "Angular") == 0) { + annoyIndex.reset(new AnnoyIndex(annoyDimensions)); + } else if (strcmp(metric.c_str(), "Manhattan") == 0) { + annoyIndex.reset(new AnnoyIndex(annoyDimensions)); + } else { + annoyIndex.reset(new AnnoyIndex(annoyDimensions)); + } + + info.This().As().TypeTag(&kAnnoyTypeTag); +} + +AnnoyIndexWrapper* AnnoyIndexWrapper::Receiver(const Napi::CallbackInfo& info) { + Napi::Value self = info.This(); + if (!self.IsObject() || !self.As().CheckTypeTag(&kAnnoyTypeTag)) { + throw Napi::TypeError::New(info.Env(), "Illegal invocation"); + } + return Unwrap(self.As()); +} - AnnoyIndexWrapper* obj = new AnnoyIndexWrapper( - (int)dimensions, *Nan::Utf8String(metricString) - ); - obj->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); +std::vector AnnoyIndexWrapper::newVector() const { + // Zero-filled: 4.0.1 left components missing from a short JS array + // uninitialised. Never empty, so data() is always a valid pointer. + return std::vector(annoyDimensions > 0 ? annoyDimensions : 1, 0.0f); +} + +void AnnoyIndexWrapper::syncExternalMemory(Napi::Env env) { + int64_t current = static_cast(annoyIndex->get_memory_size()); + int64_t change = current - reportedExternalMemory; + if (change != 0) { + Napi::MemoryManagement::AdjustExternalMemory(env, change); + reportedExternalMemory = current; } } -void AnnoyIndexWrapper::AddItem(const Nan::FunctionCallbackInfo& info) { - // Get out object. - AnnoyIndexWrapper* obj = ObjectWrap::Unwrap(info.Holder()); - // Get out index. - int index = info[0]->IsUndefined() ? 1 : info[0]->NumberValue(Nan::GetCurrentContext()).FromJust(); - // Get out array. - float vec[obj->getDimensions()]; - if (getFloatArrayParam(info, 1, vec)) { - obj->annoyIndex->add_item(index, vec); +void AnnoyIndexWrapper::Finalize(Napi::Env env) { + // Runs before the destructor frees the index. Raw call, status ignored: the + // environment may be tearing down, and a failure here must not abort. + if (reportedExternalMemory != 0) { + int64_t ignored; + napi_adjust_external_memory(env, -reportedExternalMemory, &ignored); + reportedExternalMemory = 0; } } -void AnnoyIndexWrapper::Build(const Nan::FunctionCallbackInfo& info) { - // Get out object. - AnnoyIndexWrapper* obj = ObjectWrap::Unwrap(info.Holder()); - // Get out numberOfTrees. - int numberOfTrees = info[0]->IsUndefined() ? 1 : info[0]->NumberValue(Nan::GetCurrentContext()).FromJust(); - // printf("%s\n", "Calling build"); +Napi::Value AnnoyIndexWrapper::AddItem(const Napi::CallbackInfo& info) { + AnnoyIndexWrapper* obj = Receiver(info); + int index = numberOr(info[0], 1); + std::vector vec = obj->newVector(); + if (obj->getFloatArrayParam(info, 1, vec)) { + obj->annoyIndex->add_item(index, vec.data()); + // The node array grows geometrically: this reports only on reallocation. + obj->syncExternalMemory(info.Env()); + } + return info.Env().Undefined(); +} + +Napi::Value AnnoyIndexWrapper::Build(const Napi::CallbackInfo& info) { + AnnoyIndexWrapper* obj = Receiver(info); + int numberOfTrees = numberOr(info[0], 1); obj->annoyIndex->build(numberOfTrees); + obj->syncExternalMemory(info.Env()); + return info.Env().Undefined(); } -void AnnoyIndexWrapper::Save(const Nan::FunctionCallbackInfo& info) { +Napi::Value AnnoyIndexWrapper::Save(const Napi::CallbackInfo& info) { + AnnoyIndexWrapper* obj = Receiver(info); bool result = false; - - // Get out object. - AnnoyIndexWrapper* obj = ObjectWrap::Unwrap(info.Holder()); - // Get out file path. - if (!info[0]->IsUndefined()) { - Nan::MaybeLocal maybeStr = Nan::To(info[0]); - v8::Local str; - if (maybeStr.ToLocal(&str)) { - result = obj->annoyIndex->save(*Nan::Utf8String(str)); - } + if (!info[0].IsUndefined()) { + std::string path = info[0].ToString().Utf8Value(); + result = obj->annoyIndex->save(path.c_str()); } - info.GetReturnValue().Set(Nan::New(result)); + // save() unloads the heap nodes and maps the saved file instead. + obj->syncExternalMemory(info.Env()); + return Napi::Boolean::New(info.Env(), result); } -void AnnoyIndexWrapper::Load(const Nan::FunctionCallbackInfo& info) { +Napi::Value AnnoyIndexWrapper::Load(const Napi::CallbackInfo& info) { + AnnoyIndexWrapper* obj = Receiver(info); bool result = false; - // Get out object. - AnnoyIndexWrapper* obj = ObjectWrap::Unwrap(info.Holder()); - // Get out file path. - if (!info[0]->IsUndefined()) { - Nan::MaybeLocal maybeStr = Nan::To(info[0]); - v8::Local str; - if (maybeStr.ToLocal(&str)) { - result = obj->annoyIndex->load(*Nan::Utf8String(str)); - } + if (!info[0].IsUndefined()) { + std::string path = info[0].ToString().Utf8Value(); + result = obj->annoyIndex->load(path.c_str()); } - info.GetReturnValue().Set(Nan::New(result)); + obj->syncExternalMemory(info.Env()); + return Napi::Boolean::New(info.Env(), result); } -void AnnoyIndexWrapper::Unload(const Nan::FunctionCallbackInfo& info) { - AnnoyIndexWrapper* obj = ObjectWrap::Unwrap(info.Holder()); +Napi::Value AnnoyIndexWrapper::Unload(const Napi::CallbackInfo& info) { + AnnoyIndexWrapper* obj = Receiver(info); obj->annoyIndex->unload(); + obj->syncExternalMemory(info.Env()); + return info.Env().Undefined(); } -void AnnoyIndexWrapper::GetItem(const Nan::FunctionCallbackInfo& info) { - Nan::HandleScope scope; - - // Get out object. - AnnoyIndexWrapper* obj = ObjectWrap::Unwrap(info.Holder()); +Napi::Value AnnoyIndexWrapper::GetItem(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + AnnoyIndexWrapper* obj = Receiver(info); + int index = numberOr(info[0], 1); - // Get out index. - int index = info[0]->IsUndefined() ? 1 : info[0]->NumberValue(Nan::GetCurrentContext()).FromJust(); + std::vector vec = obj->newVector(); + obj->annoyIndex->get_item(index, vec.data()); - // Get the vector. - int length = obj->getDimensions(); - float vec[length]; - obj->annoyIndex->get_item(index, vec); - - // Allocate the return array. - Local results = Nan::New(length); + int length = obj->annoyDimensions > 0 ? obj->annoyDimensions : 0; + Napi::Array results = Napi::Array::New(env, length); for (int i = 0; i < length; ++i) { - // printf("Adding to array: %f\n", vec[i]); - Nan::Set(results, i, Nan::New(vec[i])); + results.Set(static_cast(i), Napi::Number::New(env, vec[i])); } - - info.GetReturnValue().Set(results); + return results; } -void AnnoyIndexWrapper::GetDistance(const Nan::FunctionCallbackInfo& info) { - // Get out object. - AnnoyIndexWrapper* obj = ObjectWrap::Unwrap(info.Holder()); - - // Get out indexes. - int indexA = info[0]->IsUndefined() ? 0 : info[0]->NumberValue(Nan::GetCurrentContext()).FromJust(); - int indexB = info[1]->IsUndefined() ? 0 : info[1]->NumberValue(Nan::GetCurrentContext()).FromJust(); - - // Return the distances. - info.GetReturnValue().Set(obj->annoyIndex->get_distance(indexA, indexB)); +Napi::Value AnnoyIndexWrapper::GetDistance(const Napi::CallbackInfo& info) { + AnnoyIndexWrapper* obj = Receiver(info); + int indexA = numberOr(info[0], 0); + int indexB = numberOr(info[1], 0); + return Napi::Number::New(info.Env(), obj->annoyIndex->get_distance(indexA, indexB)); } -void AnnoyIndexWrapper::GetNNSByVector(const Nan::FunctionCallbackInfo& info) { - Nan::HandleScope scope; +Napi::Value AnnoyIndexWrapper::GetNNSByVector(const Napi::CallbackInfo& info) { + AnnoyIndexWrapper* obj = Receiver(info); + // Same evaluation order as 4.0.1: n, search_k, include_distances, vector. int numberOfNeighbors, searchK; bool includeDistances; getSupplementaryGetNNsParams(info, numberOfNeighbors, searchK, includeDistances); - // Get out object. - AnnoyIndexWrapper* obj = ObjectWrap::Unwrap(info.Holder()); - // Get out array. - float vec[obj->getDimensions()]; - if (!getFloatArrayParam(info, 0, vec)) { - return; + std::vector vec = obj->newVector(); + if (!obj->getFloatArrayParam(info, 0, vec)) { + return info.Env().Undefined(); } std::vector nnIndexes; std::vector distances; - std::vector *distancesPtr = nullptr; - - if (includeDistances) { - distancesPtr = &distances; - } - - // Make the call. - obj->annoyIndex->get_nns_by_vector( - vec, numberOfNeighbors, searchK, &nnIndexes, distancesPtr - ); - - setNNReturnValues(numberOfNeighbors, includeDistances, nnIndexes, distances, info); + obj->annoyIndex->get_nns_by_vector(vec.data(), numberOfNeighbors, searchK, &nnIndexes, + includeDistances ? &distances : nullptr); + return nnResult(info.Env(), numberOfNeighbors, includeDistances, nnIndexes, distances); } -void AnnoyIndexWrapper::GetNNSByItem(const Nan::FunctionCallbackInfo& info) { - Nan::HandleScope scope; - - // Get out object. - AnnoyIndexWrapper* obj = ObjectWrap::Unwrap(info.Holder()); - - if (info[0]->IsUndefined()) { - return; +Napi::Value AnnoyIndexWrapper::GetNNSByItem(const Napi::CallbackInfo& info) { + AnnoyIndexWrapper* obj = Receiver(info); + if (info[0].IsUndefined()) { + return info.Env().Undefined(); } - // Get out params. - int index = info[0]->NumberValue(Nan::GetCurrentContext()).FromJust(); + int index = info[0].ToNumber().DoubleValue(); int numberOfNeighbors, searchK; bool includeDistances; getSupplementaryGetNNsParams(info, numberOfNeighbors, searchK, includeDistances); std::vector nnIndexes; std::vector distances; - std::vector *distancesPtr = nullptr; - - if (includeDistances) { - distancesPtr = &distances; - } - - // Make the call. - obj->annoyIndex->get_nns_by_item( - index, numberOfNeighbors, searchK, &nnIndexes, distancesPtr - ); - - setNNReturnValues(numberOfNeighbors, includeDistances, nnIndexes, distances, info); + obj->annoyIndex->get_nns_by_item(index, numberOfNeighbors, searchK, &nnIndexes, + includeDistances ? &distances : nullptr); + return nnResult(info.Env(), numberOfNeighbors, includeDistances, nnIndexes, distances); } -void AnnoyIndexWrapper::getSupplementaryGetNNsParams( - const Nan::FunctionCallbackInfo& info, - int& numberOfNeighbors, int& searchK, bool& includeDistances) { - - v8::Local context = Nan::GetCurrentContext(); - - // Get out number of neighbors. - numberOfNeighbors = info[1]->IsUndefined() ? 1 : info[1]->NumberValue(context).FromJust(); - - // Get out searchK. - searchK = info[2]->IsUndefined() ? -1 : info[2]->NumberValue(context).FromJust(); - - // Get out include distances flag. - includeDistances = info[3]->IsUndefined() ? false : Nan::To(info[3]).FromJust(); +Napi::Value AnnoyIndexWrapper::GetNItems(const Napi::CallbackInfo& info) { + AnnoyIndexWrapper* obj = Receiver(info); + return Napi::Number::New(info.Env(), obj->annoyIndex->get_n_items()); } -void AnnoyIndexWrapper::setNNReturnValues( - int numberOfNeighbors, bool includeDistances, - const std::vector& nnIndexes, const std::vector& distances, - const Nan::FunctionCallbackInfo& info) { - - // Allocate the neighbors array. - Local jsNNIndexes = Nan::New(numberOfNeighbors); - for (int i = 0; i < numberOfNeighbors; ++i) { - // printf("Adding to neighbors array: %d\n", nnIndexes[i]); - Nan::Set(jsNNIndexes, i, Nan::New(nnIndexes[i])); - } - - Local jsResultObject; - Local jsDistancesArray; - - if (includeDistances) { - // Allocate the distances array. - jsDistancesArray = Nan::New(numberOfNeighbors); - for (int i = 0; i < numberOfNeighbors; ++i) { - // printf("Adding to distances array: %f\n", distances[i]); - Nan::Set(jsDistancesArray, i, Nan::New(distances[i])); - } +void AnnoyIndexWrapper::getSupplementaryGetNNsParams(const Napi::CallbackInfo& info, + int& numberOfNeighbors, int& searchK, + bool& includeDistances) { + numberOfNeighbors = numberOr(info[1], 1); + searchK = numberOr(info[2], -1); + includeDistances = info[3].IsUndefined() ? false : info[3].ToBoolean().Value(); +} - jsResultObject = Nan::New(); - Nan::Set(jsResultObject, Nan::New("neighbors").ToLocalChecked(), jsNNIndexes); - Nan::Set(jsResultObject, Nan::New("distances").ToLocalChecked(), jsDistancesArray); +// 4.0.1 sized the result arrays with the requested neighbour count n +// (v8::Array::New gives length 0 for n <= 0) and read past the end of +// nnIndexes/distances when Annoy returned fewer results (fewer items than n, +// or an index without trees). The length is now min(max(n, 0), results): +// identical whenever 4.0.1 was defined, real results only otherwise. +// (Annoy itself returns every item for a negative n, hence the clamp.) +Napi::Value AnnoyIndexWrapper::nnResult(Napi::Env env, int numberOfNeighbors, + bool includeDistances, + const std::vector& nnIndexes, + const std::vector& distances) { + size_t length = numberOfNeighbors > 0 ? static_cast(numberOfNeighbors) : 0; + if (nnIndexes.size() < length) length = nnIndexes.size(); + if (includeDistances && distances.size() < length) length = distances.size(); + + Napi::Array jsNNIndexes = Napi::Array::New(env, length); + for (size_t i = 0; i < length; ++i) { + jsNNIndexes.Set(static_cast(i), Napi::Number::New(env, nnIndexes[i])); } - else { - jsResultObject = jsNNIndexes.As(); + if (!includeDistances) { + return jsNNIndexes; } - info.GetReturnValue().Set(jsResultObject); -} - -void AnnoyIndexWrapper::GetNItems(const Nan::FunctionCallbackInfo& info) { - // Get out object. - AnnoyIndexWrapper* obj = ObjectWrap::Unwrap(info.Holder()); - Local count = Nan::New(obj->annoyIndex->get_n_items()); - info.GetReturnValue().Set(count); + Napi::Array jsDistances = Napi::Array::New(env, length); + for (size_t i = 0; i < length; ++i) { + jsDistances.Set(static_cast(i), Napi::Number::New(env, distances[i])); + } + Napi::Object result = Napi::Object::New(env); + result.Set(propertyKey(env, "neighbors"), jsNNIndexes); + result.Set(propertyKey(env, "distances"), jsDistances); + return result; } -// Returns true if it was able to get items out of the array. false, if not. -bool AnnoyIndexWrapper::getFloatArrayParam( - const Nan::FunctionCallbackInfo& info, int paramIndex, float *vec) { - - bool succeeded = false; - - Local val; - if (info[paramIndex]->IsArray()) { - // TODO: Make sure it really is OK to use Local instead of Handle here. - Local jsArray = Local::Cast(info[paramIndex]); - Local val; - for (unsigned int i = 0; i < jsArray->Length(); i++) { - val = Nan::Get(jsArray, i).ToLocalChecked(); - // printf("Adding item to array: %f\n", (float)val->NumberValue(Nan::GetCurrentContext()).FromJust()); - vec[i] = (float)val->NumberValue(Nan::GetCurrentContext()).FromJust(); +// Returns true if info[paramIndex] is a JS Array or a numeric typed array, +// after copying its elements into vec. Array elements are each coerced with +// ToNumber; like 4.0.1, every element is coerced, including those beyond the +// index dimensions, which are not stored (4.0.1 wrote them past the end of a +// stack buffer). Typed arrays are read directly (new in 5.0.0). +bool AnnoyIndexWrapper::getFloatArrayParam(const Napi::CallbackInfo& info, size_t paramIndex, + std::vector& vec) const { + Napi::Value value = info[paramIndex]; + const uint32_t dimensions = annoyDimensions > 0 ? static_cast(annoyDimensions) : 0; + + // 5.0.0: numeric typed arrays are read straight from their backing store, + // without one N-API call per component (4.0.1 ignored them). Same rules as + // for an Array: missing components stay 0, extra components are ignored. + if (value.IsTypedArray()) { + Napi::TypedArray typed = value.As(); + size_t length = typed.ElementLength(); + size_t count = length < dimensions ? length : dimensions; + switch (typed.TypedArrayType()) { + case napi_float32_array: { + const float* data = value.As().Data(); + std::memcpy(vec.data(), data, count * sizeof(float)); + return true; + } + case napi_float64_array: + copyTypedArray(value.As().Data(), count, vec); + return true; + case napi_int8_array: + copyTypedArray(value.As().Data(), count, vec); + return true; + case napi_uint8_array: + case napi_uint8_clamped_array: + copyTypedArray(static_cast(typed.ArrayBuffer().Data()) + typed.ByteOffset(), count, vec); + return true; + case napi_int16_array: + copyTypedArray(value.As().Data(), count, vec); + return true; + case napi_uint16_array: + copyTypedArray(value.As().Data(), count, vec); + return true; + case napi_int32_array: + copyTypedArray(value.As().Data(), count, vec); + return true; + case napi_uint32_array: + copyTypedArray(value.As().Data(), count, vec); + return true; + default: + // BigInt64Array / BigUint64Array (and any future type): not numbers, + // treated as before, like any non-Array value. + return false; } - succeeded = true; } - return succeeded; -} - -int AnnoyIndexWrapper::getDimensions() { - return annoyDimensions; + if (!value.IsArray()) { + return false; + } + Napi::Array jsArray = value.As(); + // Length is re-read on every iteration, as in 4.0.1. + for (uint32_t i = 0; i < jsArray.Length(); i++) { + float component = (float)jsArray.Get(i).ToNumber().DoubleValue(); + if (i < dimensions) { + vec[i] = component; + } + } + return true; } - diff --git a/annoyindexwrapper.h b/annoyindexwrapper.h index f00b4ed..00a3219 100644 --- a/annoyindexwrapper.h +++ b/annoyindexwrapper.h @@ -1,43 +1,63 @@ #ifndef ANNOYINDEXWRAPPER_H #define ANNOYINDEXWRAPPER_H -#include +#include +#include #include "annoylib.h" -class AnnoyIndexWrapper : public Nan::ObjectWrap { +// JS class `Annoy`: wraps one AnnoyIndex. +// +// The JS-visible contract (argument coercion, defaults, return values, errors) +// is the one of the 4.0.1 NAN wrapper; tests/wrong-input-test.js pins it. +class AnnoyIndexWrapper : public Napi::ObjectWrap { public: - static void Init(v8::Local exports); - int getDimensions(); - AnnoyIndexInterface *annoyIndex; + static Napi::Object Init(Napi::Env env, Napi::Object exports); + + // Called by ObjectWrap for `new Annoy(dimensions, metric)`. + explicit AnnoyIndexWrapper(const Napi::CallbackInfo& info); + + // `Annoy(...)` without `new` returns undefined, as in 4.0.1. + static Napi::Value OnCalledAsFunction(const Napi::CallbackInfo& info); + + // Returns the external memory still reported for this index to V8, before + // the index is freed with the wrapper. + void Finalize(Napi::Env env) override; private: - explicit AnnoyIndexWrapper(int dimensions, const char *metricString); - virtual ~AnnoyIndexWrapper(); - - static void New(const Nan::FunctionCallbackInfo& info); - static void AddItem(const Nan::FunctionCallbackInfo& info); - static void Build(const Nan::FunctionCallbackInfo& info); - static void Save(const Nan::FunctionCallbackInfo& info); - static void Load(const Nan::FunctionCallbackInfo& info); - static void Unload(const Nan::FunctionCallbackInfo& info); - static void GetItem(const Nan::FunctionCallbackInfo& info); - static void GetNNSByVector(const Nan::FunctionCallbackInfo& info); - static void GetNNSByItem(const Nan::FunctionCallbackInfo& info); - static void GetNItems(const Nan::FunctionCallbackInfo& info); - static void GetDistance(const Nan::FunctionCallbackInfo& info); - - static Nan::Persistent constructor; - static bool getFloatArrayParam(const Nan::FunctionCallbackInfo& info, - int paramIndex, float *vec); - static void setNNReturnValues( - int numberOfNeighbors, bool includeDistances, - const std::vector& nnIndexes, const std::vector& distances, - const Nan::FunctionCallbackInfo& info); - static void getSupplementaryGetNNsParams( - const Nan::FunctionCallbackInfo& info, - int& numberOfNeighbors, int& searchK, bool& includeDistances); + // Prototype methods. They are static and look up their receiver themselves + // (see Receiver) so that a call on a foreign `this` throws the same + // TypeError as the V8 signature check NAN relied on. + static Napi::Value AddItem(const Napi::CallbackInfo& info); + static Napi::Value Build(const Napi::CallbackInfo& info); + static Napi::Value Save(const Napi::CallbackInfo& info); + static Napi::Value Load(const Napi::CallbackInfo& info); + static Napi::Value Unload(const Napi::CallbackInfo& info); + static Napi::Value GetItem(const Napi::CallbackInfo& info); + static Napi::Value GetNNSByVector(const Napi::CallbackInfo& info); + static Napi::Value GetNNSByItem(const Napi::CallbackInfo& info); + static Napi::Value GetNItems(const Napi::CallbackInfo& info); + static Napi::Value GetDistance(const Napi::CallbackInfo& info); + + static AnnoyIndexWrapper* Receiver(const Napi::CallbackInfo& info); + bool getFloatArrayParam(const Napi::CallbackInfo& info, size_t paramIndex, + std::vector& vec) const; + static void getSupplementaryGetNNsParams(const Napi::CallbackInfo& info, + int& numberOfNeighbors, int& searchK, + bool& includeDistances); + static Napi::Value nnResult(Napi::Env env, int numberOfNeighbors, bool includeDistances, + const std::vector& nnIndexes, + const std::vector& distances); + std::vector newVector() const; + // Reports the change in the index memory (heap nodes or mmap'd file) to V8 + // as external memory, so the GC weighs it and collects dropped indexes. + void syncExternalMemory(Napi::Env env); int annoyDimensions; + // Bytes currently reported to V8 through napi_adjust_external_memory. + int64_t reportedExternalMemory = 0; + // Owned; freed (heap nodes or mmap'd file) when the JS object is collected + // or the environment (main thread or worker) is torn down. + std::unique_ptr> annoyIndex; }; #endif diff --git a/annoylib.h b/annoylib.h index 293ee64..271b42b 100644 --- a/annoylib.h +++ b/annoylib.h @@ -824,6 +824,9 @@ class AnnoyIndexInterface { virtual void get_item(S item, T* v) const = 0; virtual void set_seed(int q) = 0; virtual bool on_disk_build(const char* filename, char** error=NULL) = 0; + // calldesk addition: bytes held by the node array (heap or mmap), so the + // Node binding can report them to V8 as external memory. + virtual size_t get_memory_size() const = 0; }; template @@ -867,6 +870,14 @@ template unload(); } + // calldesk addition. Mirrors what unload() releases: a loaded index maps + // _n_nodes nodes, an in-memory or on-disk build owns _nodes_size nodes. + size_t get_memory_size() const { + if (!_nodes) return 0; + S nodes = (_fd && !_on_disk) ? _n_nodes : _nodes_size; + return _s * (size_t)nodes; + } + int get_f() const { return _f; } diff --git a/binding.gyp b/binding.gyp index c781c2f..63c8c98 100644 --- a/binding.gyp +++ b/binding.gyp @@ -4,8 +4,26 @@ "target_name": "addon", "sources": [ "addon.cc", "annoyindexwrapper.cc" ], "include_dirs": [ - "= 22.14 / 23.6). + "defines": [ "NAPI_VERSION=10", "NAPI_CPP_EXCEPTIONS", "NODE_ADDON_API_DISABLE_DEPRECATED" ], + "cflags!": [ "-fno-exceptions" ], + "cflags_cc!": [ "-fno-exceptions" ], + # No fused multiply-add: GCC contracts a*b+c into FMA on arm64 but not on + # x86-64 (no FMA in the baseline ISA), which changes float rounding, so the + # same index gave different distances and trees on each architecture. + "cflags_cc": [ "-ffp-contract=off" ], + "xcode_settings": { + "OTHER_CPLUSPLUSFLAGS": [ "-ffp-contract=off" ], + "GCC_ENABLE_CPP_EXCEPTIONS": "YES", + "CLANG_CXX_LIBRARY": "libc++", + "MACOSX_DEPLOYMENT_TARGET": "11.0" + }, + "msvs_settings": { + "VCCLCompilerTool": { "ExceptionHandling": 1 } + } } ] } diff --git a/index.d.ts b/index.d.ts new file mode 100644 index 0000000..011b9dc --- /dev/null +++ b/index.d.ts @@ -0,0 +1,81 @@ +/** + * Annoy (Approximate Nearest Neighbors Oh Yeah) native N-API binding. + * + * Indexes are built in memory (`addItem` then `build`) or memory-mapped from a file (`load`). + * Their memory is reported to V8, so dropped indexes are collected. + */ + +declare class Annoy { + /** + * @param dimensions - Number of components of each vector. + * @param metric - Distance; anything else than `Angular` or `Manhattan` is Euclidean. + */ + constructor(dimensions: number, metric?: Annoy.AnnoyMetric); + + /** Adds (or replaces) item `index`. */ + addItem(index: number, vector: Annoy.AnnoyVector): void; + + /** Builds a forest of `trees` trees (default 1). Items cannot be added afterwards. */ + build(trees?: number): void; + + /** Saves the index to `path`, then maps it. Returns false on failure. */ + save(path: string): boolean; + + /** Memory-maps the index saved at `path`. Returns false on failure. */ + load(path: string): boolean; + + /** Frees the index (heap nodes or mapping). */ + unload(): void; + + /** Vector of item `index` (default 1). */ + getItem(index?: number): number[]; + + /** + * The `n` nearest neighbours of `vector` (at most the number of items). + * @param searchK - Nodes to inspect (default -1: n x trees); more is slower and more precise. + */ + getNNsByVector(vector: Annoy.AnnoyVector, n: number, searchK?: number, includeDistances?: false): number[]; + getNNsByVector(vector: Annoy.AnnoyVector, n: number, searchK: number, includeDistances: true): Annoy.AnnoyNeighbors; + getNNsByVector(vector: Annoy.AnnoyVector, n: number, searchK?: number, includeDistances?: boolean): number[] | Annoy.AnnoyNeighbors; + + /** The `n` nearest neighbours of item `index`. */ + getNNsByItem(index: number, n: number, searchK?: number, includeDistances?: false): number[]; + getNNsByItem(index: number, n: number, searchK: number, includeDistances: true): Annoy.AnnoyNeighbors; + getNNsByItem(index: number, n: number, searchK?: number, includeDistances?: boolean): number[] | Annoy.AnnoyNeighbors; + + /** Number of items in the index. */ + getNItems(): number; + + /** Distance between items `a` and `b`, with the index metric. */ + getDistance(a: number, b: number): number; +} + +declare namespace Annoy { + /** Distance used by the index. Any other value builds a Euclidean index. */ + export type AnnoyMetric = 'Angular' | 'Euclidean' | 'Manhattan'; + + /** + * A vector: a JS array of numbers, or a numeric typed array (read directly, without + * per-component conversion; `Float32Array` is copied as is). Missing components are 0, + * extra components are ignored. + */ + export type AnnoyVector = + | readonly number[] + | Float32Array + | Float64Array + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array; + + /** Neighbours with their distances (`includeDistances: true`). */ + export interface AnnoyNeighbors { + neighbors: number[]; + distances: number[]; + } +} + +export = Annoy; diff --git a/package-lock.json b/package-lock.json index 6078628..d42bba4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,29 +1,33 @@ { "name": "@calldesk/annoy-node", - "version": "4.0.1", + "version": "5.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@calldesk/annoy-node", - "version": "4.0.1", + "version": "5.0.0", "hasInstallScript": true, "license": "MIT", "dependencies": { - "bindings": "^1.2.1", - "level": "^6.0.0", - "nan": "^2.27.0", + "node-addon-api": "^8.9.2", "node-gyp-build": "^4.8.4" }, "devDependencies": { "assert-no-error": "^1.0.0", + "bindings": "^1.2.1", "d3-queue": "^3.0.3", + "level": "^6.0.0", "level-sublevel": "^6.6.4", "ndjson": "^1.5.0", "node-worker-threads-pool": "^1.5.1", "prebuildify": "^6.0.1", "tape": "^5.6.6", - "through2": "^2.0.1" + "through2": "^2.0.1", + "typescript": "^5.9.3" + }, + "engines": { + "node": ">=22.14.0" } }, "node_modules/@ljharb/resumer": { @@ -51,6 +55,7 @@ "version": "6.2.2", "resolved": "https://registry.npmjs.org/abstract-leveldown/-/abstract-leveldown-6.2.2.tgz", "integrity": "sha512-/a+Iwj0rn//CX0EJOasNyZJd2o8xur8Ce9C57Sznti/Ilt/cb6Qd8/k98A4ZOklXgTG+iAYYUs1OTG0s1eH+zQ==", + "dev": true, "dependencies": { "level-concat-iterator": "~2.0.0", "level-supports": "~1.0.0", @@ -159,7 +164,8 @@ "node_modules/bindings": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.2.1.tgz", - "integrity": "sha1-FK1hE4EtLTfXLme0ystLtyZQXxE=" + "integrity": "sha1-FK1hE4EtLTfXLme0ystLtyZQXxE=", + "dev": true }, "node_modules/bl": { "version": "4.1.0", @@ -329,6 +335,7 @@ "version": "5.3.0", "resolved": "https://registry.npmjs.org/deferred-leveldown/-/deferred-leveldown-5.3.0.tgz", "integrity": "sha512-a59VOT+oDy7vtAbLRCZwWgxu2BaCfd5Hk7wxJd48ei7I+nsg8Orlb9CLG0PMZienk9BSUKgeAqkO2+Lw+1+Ukw==", + "dev": true, "dependencies": { "abstract-leveldown": "~6.2.1", "inherits": "^2.0.3" @@ -378,6 +385,7 @@ "version": "6.3.0", "resolved": "https://registry.npmjs.org/encoding-down/-/encoding-down-6.3.0.tgz", "integrity": "sha512-QKrV0iKR6MZVJV08QY0wp1e7vF6QbhnbQhb07bwpEyuz4uZiZgPlEGdkCROuFkUwdxlFaiPIhjyarH1ee/3vhw==", + "dev": true, "dependencies": { "abstract-leveldown": "^6.2.1", "inherits": "^2.0.3", @@ -402,6 +410,7 @@ "version": "0.1.7", "resolved": "https://registry.npmjs.org/errno/-/errno-0.1.7.tgz", "integrity": "sha512-MfrRBDWzIWifgq6tJj60gkAwtLNb6sQPlcFrSOflcP1aFmmruKQ2wRnze/8V6kgyz7H3FF8Npzv78mZ7XLLflg==", + "dev": true, "dependencies": { "prr": "~1.0.1" }, @@ -770,7 +779,8 @@ "node_modules/immediate": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.2.3.tgz", - "integrity": "sha1-0UD6j2FGWb1lQSMwl92qwlzdmRw=" + "integrity": "sha1-0UD6j2FGWb1lQSMwl92qwlzdmRw=", + "dev": true }, "node_modules/inflight": { "version": "1.0.6", @@ -786,6 +796,7 @@ "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true, "license": "ISC" }, "node_modules/internal-slot": { @@ -1067,6 +1078,7 @@ "version": "6.0.0", "resolved": "https://registry.npmjs.org/level/-/level-6.0.0.tgz", "integrity": "sha512-3oAi7gXLLNr7pHj8c4vbI6lHkXf35m8qb7zWMrNTrOax6CXBVggQAwL1xnC/1CszyYrW3BsLXsY5TMgTxtKfFA==", + "dev": true, "hasInstallScript": true, "dependencies": { "level-js": "^5.0.0", @@ -1082,6 +1094,7 @@ "version": "9.0.1", "resolved": "https://registry.npmjs.org/level-codec/-/level-codec-9.0.1.tgz", "integrity": "sha512-ajFP0kJ+nyq4i6kptSM+mAvJKLOg1X5FiFPtLG9M5gCEZyBmgDi3FkDrvlMkEzrUn1cWxtvVmrvoS4ASyO/q+Q==", + "dev": true, "engines": { "node": ">=6" } @@ -1090,6 +1103,7 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/level-concat-iterator/-/level-concat-iterator-2.0.1.tgz", "integrity": "sha512-OTKKOqeav2QWcERMJR7IS9CUo1sHnke2C0gkSmcR7QuEtFNLLzHQAvnMw8ykvEcv0Qtkg0p7FOwP1v9e5Smdcw==", + "dev": true, "engines": { "node": ">=6" } @@ -1098,6 +1112,7 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/level-errors/-/level-errors-2.0.1.tgz", "integrity": "sha512-UVprBJXite4gPS+3VznfgDSU8PTRuVX0NXwoWW50KLxd2yw4Y1t2JUR5In1itQnudZqRMT9DlAM3Q//9NCjCFw==", + "dev": true, "dependencies": { "errno": "~0.1.1" }, @@ -1109,6 +1124,7 @@ "version": "4.0.2", "resolved": "https://registry.npmjs.org/level-iterator-stream/-/level-iterator-stream-4.0.2.tgz", "integrity": "sha512-ZSthfEqzGSOMWoUGhTXdX9jv26d32XJuHz/5YnuHZzH6wldfWMOVwI9TBtKcya4BKTyTt3XVA0A3cF3q5CY30Q==", + "dev": true, "dependencies": { "inherits": "^2.0.4", "readable-stream": "^3.4.0", @@ -1122,6 +1138,7 @@ "version": "3.4.0", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.4.0.tgz", "integrity": "sha512-jItXPLmrSR8jmTRmRWJXCnGJsfy85mB3Wd/uINMXA65yrnFo0cPClFIUWzo2najVNSl+mx7/4W8ttlLWJe99pQ==", + "dev": true, "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", @@ -1135,6 +1152,7 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dev": true, "dependencies": { "safe-buffer": "~5.2.0" } @@ -1143,6 +1161,7 @@ "version": "4.0.2", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "dev": true, "engines": { "node": ">=0.4" } @@ -1151,6 +1170,7 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/level-js/-/level-js-5.0.0.tgz", "integrity": "sha512-BIevs/NlfX1DCbuzt8+p2LCumiuDf6IHq5ehktqmcJVRxzfVdc6lXV2FB5cGkTYg4KAr7WfVkeUBAiTgevy19g==", + "dev": true, "dependencies": { "abstract-leveldown": "~6.2.1", "immediate": "~3.2.3", @@ -1162,6 +1182,7 @@ "version": "5.1.0", "resolved": "https://registry.npmjs.org/level-packager/-/level-packager-5.1.0.tgz", "integrity": "sha512-3pbJmDgGvp/lUQNULPoYQZtUbhMI8KoViYDw7Sa0kWl1mPeHWWJF7T/9upWI/NTMuEikkEE/cd6wBvmrW1+ZnQ==", + "dev": true, "dependencies": { "encoding-down": "^6.3.0", "levelup": "^4.3.2" @@ -1257,6 +1278,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/level-supports/-/level-supports-1.0.1.tgz", "integrity": "sha512-rXM7GYnW8gsl1vedTJIbzOrRv85c/2uCMpiiCzO2fndd06U/kUXEEU9evYn4zFggBOg36IsBW8LzqIpETwwQzg==", + "dev": true, "dependencies": { "xtend": "^4.0.2" }, @@ -1268,6 +1290,7 @@ "version": "4.0.2", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "dev": true, "engines": { "node": ">=0.4" } @@ -1276,6 +1299,7 @@ "version": "5.4.1", "resolved": "https://registry.npmjs.org/leveldown/-/leveldown-5.4.1.tgz", "integrity": "sha512-3lMPc7eU3yj5g+qF1qlALInzIYnkySIosR1AsUKFjL9D8fYbTLuENBAeDRZXIG4qeWOAyqRItOoLu2v2avWiMA==", + "dev": true, "hasInstallScript": true, "dependencies": { "abstract-leveldown": "~6.2.1", @@ -1290,6 +1314,7 @@ "version": "4.1.1", "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.1.1.tgz", "integrity": "sha512-dSq1xmcPDKPZ2EED2S6zw/b9NKsqzXRE6dVr8TVQnI3FJOTteUMuqF3Qqs6LZg+mLGYJWqQzMbIjMtJqTv87nQ==", + "dev": true, "license": "MIT", "bin": { "node-gyp-build": "bin.js", @@ -1301,6 +1326,7 @@ "version": "4.3.2", "resolved": "https://registry.npmjs.org/levelup/-/levelup-4.3.2.tgz", "integrity": "sha512-cRTjU4ktWo59wf13PHEiOayHC3n0dOh4i5+FHr4tv4MX9+l7mqETicNq3Aj07HKlLdk0z5muVoDL2RD+ovgiyA==", + "dev": true, "dependencies": { "deferred-leveldown": "~5.3.0", "level-errors": "~2.0.0", @@ -1321,7 +1347,8 @@ "node_modules/ltgt": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ltgt/-/ltgt-2.1.3.tgz", - "integrity": "sha1-EIUaBtmWS5cReEQcI8nlJpjuzjQ=" + "integrity": "sha1-EIUaBtmWS5cReEQcI8nlJpjuzjQ=", + "dev": true }, "node_modules/minimatch": { "version": "3.1.2", @@ -1351,16 +1378,11 @@ "dev": true, "license": "MIT" }, - "node_modules/nan": { - "version": "2.27.0", - "resolved": "https://registry.npmjs.org/nan/-/nan-2.27.0.tgz", - "integrity": "sha512-hC+0LidcL3XE4rp1C4H54KujgXKzbfyTngZTwBByQxsOxCEKZT0MPQ4hOKUH2jU1OYstqdDH4onyHPDzcV0XdQ==", - "license": "MIT" - }, "node_modules/napi-macros": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/napi-macros/-/napi-macros-2.0.0.tgz", - "integrity": "sha512-A0xLykHtARfueITVDernsAWdtIMbOJgKgcluwENp3AlsKN/PloyO10HtmoqnFAQAcxPkgZN7wdfPfEd0zNGxbg==" + "integrity": "sha512-A0xLykHtARfueITVDernsAWdtIMbOJgKgcluwENp3AlsKN/PloyO10HtmoqnFAQAcxPkgZN7wdfPfEd0zNGxbg==", + "dev": true }, "node_modules/ndjson": { "version": "1.5.0", @@ -1400,6 +1422,15 @@ "node": ">=10" } }, + "node_modules/node-addon-api": { + "version": "8.9.2", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz", + "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==", + "license": "MIT", + "engines": { + "node": "^18 || ^20 || >= 21" + } + }, "node_modules/node-gyp-build": { "version": "4.8.4", "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz", @@ -1495,6 +1526,7 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/opencollective-postinstall/-/opencollective-postinstall-2.0.2.tgz", "integrity": "sha512-pVOEP16TrAO2/fjej1IdOyupJY8KDUM1CvsaScRbw6oddvpQoOfGk4ywha0HKKVAD6RkW4x6Q+tNBwhf3Bgpuw==", + "dev": true, "bin": { "opencollective-postinstall": "index.js" } @@ -1551,7 +1583,8 @@ "node_modules/prr": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/prr/-/prr-1.0.1.tgz", - "integrity": "sha1-0/wRS6BplaRexok/SEzrHXj19HY=" + "integrity": "sha1-0/wRS6BplaRexok/SEzrHXj19HY=", + "dev": true }, "node_modules/pull-cat": { "version": "1.1.11", @@ -1719,7 +1752,8 @@ "node_modules/safe-buffer": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.0.tgz", - "integrity": "sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg==" + "integrity": "sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg==", + "dev": true }, "node_modules/safe-regex-test": { "version": "1.0.0", @@ -2057,6 +2091,20 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, "node_modules/typewise": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/typewise/-/typewise-1.0.3.tgz", @@ -2096,7 +2144,8 @@ "node_modules/util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", + "dev": true }, "node_modules/which-boxed-primitive": { "version": "1.0.2", @@ -2158,6 +2207,7 @@ "version": "4.0.1", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true, "engines": { "node": ">=0.4" } diff --git a/package.json b/package.json index 10905a6..6f2d149 100644 --- a/package.json +++ b/package.json @@ -1,16 +1,23 @@ { "name": "@calldesk/annoy-node", - "version": "4.0.1", + "version": "5.0.0", "description": "Node bindings for Annoy, an efficient Approximate Nearest Neighbors implementation written in C++.", "main": "index.js", + "types": "index.d.ts", + "engines": { + "node": ">=22.14.0" + }, "gypfile": true, "scripts": { "install": "node-gyp-build", "build": "node-gyp rebuild", - "build:prebuilt": "npx prebuildify --target 22.0.0 --strip", - "docker:build": "docker build --platform linux/amd64 -t annoy-node-builder . && docker run --name temp-annoy-builder annoy-node-builder && docker cp temp-annoy-builder:/build/prebuilds/. ./prebuilds/ && docker rm temp-annoy-builder", - "docker:clean": "docker rm -f temp-annoy-builder 2>/dev/null || true", - "test": "make test" + "build:prebuilt": "prebuildify --napi --strip", + "prebuild:linux": "npm run prebuild:linux-x64 && npm run prebuild:linux-arm64 && npm run check:prebuilds", + "prebuild:linux-x64": "docker buildx build --platform linux/amd64 --target prebuilds --output type=local,dest=prebuilds .", + "prebuild:linux-arm64": "docker buildx build --platform linux/arm64 --target prebuilds --output type=local,dest=prebuilds .", + "check:prebuilds": "./scripts/check-prebuild-symbols.sh", + "test": "make test", + "test:types": "tsc --noEmit --strict --module commonjs --moduleResolution node --target es2020 tests/types.ts" }, "repository": { "type": "git", @@ -35,19 +42,20 @@ "registry": "https://calldesk-974442180126.d.codeartifact.eu-west-1.amazonaws.com/npm/calldesk-repository/" }, "dependencies": { - "bindings": "^1.2.1", - "level": "^6.0.0", - "nan": "^2.27.0", + "node-addon-api": "^8.9.2", "node-gyp-build": "^4.8.4" }, "devDependencies": { "assert-no-error": "^1.0.0", + "bindings": "^1.2.1", "d3-queue": "^3.0.3", + "level": "^6.0.0", "level-sublevel": "^6.6.4", "ndjson": "^1.5.0", "node-worker-threads-pool": "^1.5.1", "prebuildify": "^6.0.1", "tape": "^5.6.6", - "through2": "^2.0.1" + "through2": "^2.0.1", + "typescript": "^5.9.3" } } diff --git a/prebuilds/darwin-arm64/@calldesk+annoy-node.node b/prebuilds/darwin-arm64/@calldesk+annoy-node.node old mode 100755 new mode 100644 index 70eea4d..3bb57d7 Binary files a/prebuilds/darwin-arm64/@calldesk+annoy-node.node and b/prebuilds/darwin-arm64/@calldesk+annoy-node.node differ diff --git a/prebuilds/darwin-x64/@calldesk+annoy-node.node b/prebuilds/darwin-x64/@calldesk+annoy-node.node new file mode 100644 index 0000000..72f6e0f Binary files /dev/null and b/prebuilds/darwin-x64/@calldesk+annoy-node.node differ diff --git a/prebuilds/linux-arm64/@calldesk+annoy-node.node b/prebuilds/linux-arm64/@calldesk+annoy-node.node new file mode 100755 index 0000000..318b5a8 Binary files /dev/null and b/prebuilds/linux-arm64/@calldesk+annoy-node.node differ diff --git a/prebuilds/linux-x64/@calldesk+annoy-node.node b/prebuilds/linux-x64/@calldesk+annoy-node.node index cfd6bfd..c8afc91 100755 Binary files a/prebuilds/linux-x64/@calldesk+annoy-node.node and b/prebuilds/linux-x64/@calldesk+annoy-node.node differ diff --git a/scripts/check-prebuild-symbols.sh b/scripts/check-prebuild-symbols.sh new file mode 100755 index 0000000..d1457d8 --- /dev/null +++ b/scripts/check-prebuild-symbols.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Fails if a Linux prebuild requires a glibc or libstdc++ symbol version newer +# than what the AWS Lambda nodejs:22 runtime (Amazon Linux 2023) provides. +# +# usage: scripts/check-prebuild-symbols.sh [file.node ...] +# (default: every prebuilds/linux-*/**/*.node) +set -euo pipefail + +MAX_GLIBC=${MAX_GLIBC:-2.34} +MAX_GLIBCXX=${MAX_GLIBCXX:-3.4.33} + +if [ "$#" -gt 0 ]; then + files=("$@") +else + cd "$(dirname "$0")/.." + mapfile -t files < <(find prebuilds -path 'prebuilds/linux-*' -name '*.node' | sort) +fi + +if [ "${#files[@]}" -eq 0 ]; then + echo "no Linux prebuilds found" >&2 + exit 1 +fi + +# version_gt A B: true if version A > version B +version_gt() { + [ "$1" != "$2" ] && [ "$(printf '%s\n%s\n' "$1" "$2" | sort -V | tail -n1)" = "$1" ] +} + +status=0 +for f in "${files[@]}"; do + # objdump -T: dynamic symbol table; the version column holds e.g. GLIBC_2.14 + versions=$(objdump -T "$f" | grep -oE '\b(GLIBC|GLIBCXX|CXXABI)_[0-9][0-9.]*' | sort -u -V || true) + max_glibc=$(grep '^GLIBC_' <<<"$versions" | sed 's/^GLIBC_//' | sort -V | tail -n1) + max_glibcxx=$(grep '^GLIBCXX_' <<<"$versions" | sed 's/^GLIBCXX_//' | sort -V | tail -n1) + bad=() + if [ -n "$max_glibc" ] && version_gt "$max_glibc" "$MAX_GLIBC"; then + bad+=("GLIBC_$max_glibc > GLIBC_$MAX_GLIBC") + fi + if [ -n "$max_glibcxx" ] && version_gt "$max_glibcxx" "$MAX_GLIBCXX"; then + bad+=("GLIBCXX_$max_glibcxx > GLIBCXX_$MAX_GLIBCXX") + fi + if [ "${#bad[@]}" -gt 0 ]; then + echo "FAIL $f: ${bad[*]}" + objdump -T "$f" | grep -E "GLIBC_|GLIBCXX_" | while read -r line; do + v=$(grep -oE '(GLIBC|GLIBCXX)_[0-9.]+' <<<"$line" | head -n1) + case "$v" in + GLIBC_*) version_gt "${v#GLIBC_}" "$MAX_GLIBC" && echo " $line" ;; + GLIBCXX_*) version_gt "${v#GLIBCXX_}" "$MAX_GLIBCXX" && echo " $line" ;; + esac + done || true + status=1 + else + echo "ok $f: max GLIBC_${max_glibc:-none}, GLIBCXX_${max_glibcxx:-none} (limits GLIBC_$MAX_GLIBC, GLIBCXX_$MAX_GLIBCXX)" + fi +done +exit $status diff --git a/tests/equivalence-test.js b/tests/equivalence-test.js new file mode 100644 index 0000000..6ab498f --- /dev/null +++ b/tests/equivalence-test.js @@ -0,0 +1,128 @@ +/* global __dirname process */ + +// Equivalence between the 4.0.1 NAN binding and the binding under test. +// +// ANNOY_REFERENCE_BINDING=/path/to/annoy-4.0.1-linux-x64.node \ +// ANNOY_REFERENCE_NODE=/path/to/node22/bin/node \ +// node tests/equivalence-test.js +// +// The reference is a NAN build for one Node ABI (22), so it runs in a child +// process under ANNOY_REFERENCE_NODE (default: the current node). The binding +// under test runs under the current node; it defaults to whatever index.js +// loads (node-gyp-build), override with ANNOY_BINDING. +// +// For 12 indexes (Angular/Euclidean/Manhattan x 3/16/64/200 dimensions, +// 3000 items, 10 trees) it requires, with no tolerance: +// 1. identical neighbour ids and distances, items and getDistance values +// from indexes built by each binding; +// 2. byte-identical .annoy files; +// 3. an index saved by one binding, loaded by the other, gives the same +// results as the original (both directions). + +var test = require('tape'); +var fs = require('fs'); +var os = require('os'); +var path = require('path'); +var crypto = require('crypto'); +var childProcess = require('child_process'); +var cases = require('./equivalence/cases'); + +var referenceBinding = process.env.ANNOY_REFERENCE_BINDING; +var referenceNode = process.env.ANNOY_REFERENCE_NODE || process.execPath; +var bindingUnderTest = + process.env.ANNOY_BINDING || require('node-gyp-build').path(path.join(__dirname, '..')); +var runner = path.join(__dirname, 'equivalence', 'runner.js'); + +function run(node, args) { + var r = childProcess.spawnSync(node, [runner].concat(args), { encoding: 'utf8' }); + if (r.status !== 0) { + throw new Error(node + ' ' + args.join(' ') + ' failed (' + (r.status === null ? r.signal : r.status) + '):\n' + r.stderr); + } +} + +function read(dir, name, mode) { + return JSON.parse(fs.readFileSync(path.join(dir, name + '.' + mode + '.json'), 'utf8')); +} + +function sha256(file) { + return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex'); +} + +// Walks two JSON values in parallel, counts compared leaves and collects +// mismatches. Numbers are compared with Object.is (exact, NaN-safe). +function compare(expected, actual, where, stats) { + if (typeof expected === 'number' || typeof actual === 'number') { + stats.compared++; + if (!Object.is(expected, actual)) stats.mismatches.push(where + ': ' + expected + ' !== ' + actual); + return; + } + if (Array.isArray(expected) || Array.isArray(actual)) { + if (!Array.isArray(expected) || !Array.isArray(actual) || expected.length !== actual.length) { + stats.mismatches.push(where + ': shape differs'); + return; + } + for (var i = 0; i < expected.length; i++) compare(expected[i], actual[i], where + '[' + i + ']', stats); + return; + } + if (expected && typeof expected === 'object') { + var keys = Object.keys(expected); + if (!actual || typeof actual !== 'object' || keys.join() !== Object.keys(actual).join()) { + stats.mismatches.push(where + ': keys differ'); + return; + } + keys.forEach(function(k) { + compare(expected[k], actual[k], where + '.' + k, stats); + }); + return; + } + stats.compared++; + if (expected !== actual) stats.mismatches.push(where + ': ' + expected + ' !== ' + actual); +} + +test('equivalence with the 4.0.1 NAN binding', { skip: !referenceBinding }, function(t) { + var work = fs.mkdtempSync(path.join(os.tmpdir(), 'annoy-equivalence-')); + var dirs = { + refBuild: path.join(work, 'ref-build'), + newBuild: path.join(work, 'new-build'), + refLoadsNew: path.join(work, 'ref-loads-new'), + newLoadsRef: path.join(work, 'new-loads-ref') + }; + try { + t.comment('reference: ' + referenceBinding + ' under ' + referenceNode); + t.comment('under test: ' + bindingUnderTest + ' under ' + process.execPath + ' (' + process.version + ')'); + run(referenceNode, ['build', referenceBinding, dirs.refBuild]); + run(process.execPath, ['build', bindingUnderTest, dirs.newBuild]); + run(referenceNode, ['load', referenceBinding, dirs.refLoadsNew, dirs.newBuild]); + run(process.execPath, ['load', bindingUnderTest, dirs.newLoadsRef, dirs.refBuild]); + + var totals = { compared: 0, mismatches: 0, neighbourLists: 0 }; + cases.all().forEach(function(c) { + var expected = read(dirs.refBuild, c.name, 'build'); + t.equal(expected.nItems, c.nItems, c.name + ': reference index has every item'); + [ + ['new build', read(dirs.newBuild, c.name, 'build')], + ['reference loading new file', read(dirs.refLoadsNew, c.name, 'load')], + ['new loading reference file', read(dirs.newLoadsRef, c.name, 'load')] + ].forEach(function(pair) { + var stats = { compared: 0, mismatches: [] }; + compare(expected, pair[1], c.name, stats); + totals.compared += stats.compared; + totals.mismatches += stats.mismatches.length; + t.deepEqual(stats.mismatches.slice(0, 5), [], c.name + ' / ' + pair[0] + ': ' + stats.compared + ' values identical'); + }); + totals.neighbourLists += 3 * (expected.byItem.length + expected.byVector.length) * 3; + t.equal( + sha256(path.join(dirs.newBuild, c.name + '.annoy')), + sha256(path.join(dirs.refBuild, c.name + '.annoy')), + c.name + ': .annoy files are byte-identical' + ); + }); + t.comment( + 'compared ' + totals.compared + ' values (' + totals.neighbourLists + ' neighbour lists) across ' + + cases.all().length + ' indexes, ' + totals.mismatches + ' mismatches' + ); + } finally { + fs.rmSync(work, { recursive: true, force: true }); + } + t.end(); +}); diff --git a/tests/equivalence/cases.js b/tests/equivalence/cases.js new file mode 100644 index 0000000..1ed703f --- /dev/null +++ b/tests/equivalence/cases.js @@ -0,0 +1,74 @@ +// Deterministic test cases shared by runner.js and the equivalence test. + +var METRICS = ['Angular', 'Euclidean', 'Manhattan']; +var DIMENSIONS = [3, 16, 64, 200]; +var N_ITEMS = 3000; + +// mulberry32: small seeded PRNG, identical on every Node version. +function prng(seed) { + var a = seed >>> 0; + return function() { + a = (a + 0x6d2b79f5) >>> 0; + var t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function vectors(seed, count, dimensions) { + var rand = prng(seed); + var out = []; + for (var i = 0; i < count; i++) { + var v = new Array(dimensions); + for (var d = 0; d < dimensions; d++) v[d] = rand() * 2 - 1; + out.push(v); + } + return out; +} + +function all() { + var out = []; + DIMENSIONS.forEach(function(dimensions, di) { + METRICS.forEach(function(metric, mi) { + out.push({ + name: metric.toLowerCase() + '-' + dimensions + 'd', + seed: 1000 + di * 10 + mi, + metric: metric, + dimensions: dimensions, + nItems: N_ITEMS, + trees: 10, + k: 25, + searchK: 500, + nQueries: 100 + }); + }); + }); + return out; +} + +function items(c) { + return vectors(c.seed, c.nItems, c.dimensions); +} + +function queryVectors(c) { + return vectors(c.seed + 500000, c.nQueries, c.dimensions); +} + +function queryItems(c) { + var rand = prng(c.seed + 900000); + var out = []; + for (var i = 0; i < c.nQueries; i++) out.push(Math.floor(rand() * c.nItems)); + return out; +} + +function distancePairs(c) { + var rand = prng(c.seed + 700000); + var out = []; + for (var i = 0; i < c.nQueries; i++) { + out.push([Math.floor(rand() * c.nItems), Math.floor(rand() * c.nItems)]); + } + return out; +} + +module.exports = { all: all, items: items, queryVectors: queryVectors, queryItems: queryItems, distancePairs: distancePairs }; diff --git a/tests/equivalence/runner.js b/tests/equivalence/runner.js new file mode 100644 index 0000000..870551c --- /dev/null +++ b/tests/equivalence/runner.js @@ -0,0 +1,72 @@ +/* global process */ + +// Builds and queries deterministic random Annoy indexes with one binding and +// writes every result to JSON, so that two bindings (possibly running under +// different Node versions) can be compared value by value. +// +// node runner.js build +// build, save to /.annoy, query, write /.build.json +// node runner.js load +// load /.annoy, query, write /.load.json +// +// JSON numbers round-trip doubles exactly, and every float Annoy returns is +// widened to a double, so comparing the parsed JSON is an exact comparison. + +var fs = require('fs'); +var path = require('path'); +var cases = require('./cases'); + +var mode = process.argv[2]; +var bindingPath = process.argv[3]; +var outDir = process.argv[4]; +var indexDir = process.argv[5]; + +if ((mode !== 'build' && mode !== 'load') || !bindingPath || !outDir || (mode === 'load' && !indexDir)) { + console.error('usage: runner.js build | load '); + process.exit(2); +} + +var Annoy = require(path.resolve(bindingPath)).Annoy; +fs.mkdirSync(outDir, { recursive: true }); + +cases.all().forEach(function(c) { + var index = new Annoy(c.dimensions, c.metric); + var annoyFile; + if (mode === 'build') { + var items = cases.items(c); + items.forEach(function(v, i) { + index.addItem(i, v); + }); + index.build(c.trees); + annoyFile = path.join(outDir, c.name + '.annoy'); + if (!index.save(annoyFile)) throw new Error('save failed: ' + annoyFile); + } else { + annoyFile = path.join(indexDir, c.name + '.annoy'); + if (!index.load(annoyFile)) throw new Error('load failed: ' + annoyFile); + } + + var result = { case: c.name, nItems: index.getNItems(), byItem: [], byVector: [], distances: [], items: [] }; + cases.queryItems(c).forEach(function(q) { + result.byItem.push({ + q: q, + withDistances: index.getNNsByItem(q, c.k, -1, true), + ids: index.getNNsByItem(q, c.k, -1, false), + searchK: index.getNNsByItem(q, c.k, c.searchK, true) + }); + }); + cases.queryVectors(c).forEach(function(v) { + result.byVector.push({ + withDistances: index.getNNsByVector(v, c.k, -1, true), + ids: index.getNNsByVector(v, c.k, -1, false), + searchK: index.getNNsByVector(v, c.k, c.searchK, true) + }); + }); + cases.distancePairs(c).forEach(function(p) { + result.distances.push(index.getDistance(p[0], p[1])); + }); + cases.queryItems(c).forEach(function(q) { + result.items.push(index.getItem(q)); + }); + index.unload(); + fs.writeFileSync(path.join(outDir, c.name + '.' + mode + '.json'), JSON.stringify(result)); +}); diff --git a/tests/external-memory-test.js b/tests/external-memory-test.js new file mode 100644 index 0000000..a6fb6fc --- /dev/null +++ b/tests/external-memory-test.js @@ -0,0 +1,69 @@ +/* global process */ +// The index memory (heap nodes or mmap'd file) is reported to V8 as external +// memory, so that the GC weighs indexes that are no longer referenced and +// collects them. +// +// Without it (4.0.1), V8 only sees a small JS wrapper per index: loading a +// fresh index for every request, as bot-api does on each Think, keeps every +// dropped mapping alive until an unrelated GC, and RSS grows with the number +// of loads. process.memoryUsage().external does not include this accounting +// on recent V8 versions, so the test checks the effect: RSS stays bounded. +// +// node tests/external-memory-test.js +var test = require('tape'); +var fs = require('fs'); +var os = require('os'); +var path = require('path'); +var Annoy = require('./load-binding')(); + +var DIMENSIONS = 200; +var ITEMS = 5000; +var LOADS = 1000; + +var file = path.join(os.tmpdir(), 'annoy-external-memory-' + process.pid + '.ann'); + +function vector(seed) { + var v = []; + for (var d = 0; d < DIMENSIONS; d++) v.push(Math.sin(seed * 31 + d)); + return v; +} + +test('dropped indexes are collected: RSS stays bounded under load churn', function(t) { + var index = new Annoy(DIMENSIONS, 'Angular'); + for (var i = 0; i < ITEMS; i++) index.addItem(i, vector(i)); + index.build(10); + t.ok(index.save(file), 'saved'); + index.unload(); + var fileSize = fs.statSync(file).size; + var query = vector(-1); + + var rssBefore = process.memoryUsage().rss; + var peak = 0; + var n = 0; + + // Load, query and drop one index per turn, yielding to the event loop + // like a request handler does (ObjectWrap finalizers run after the GC). + (function next() { + if (n === LOADS) { + fs.unlinkSync(file); + var leakedLoads = peak / fileSize; + t.ok( + leakedLoads < LOADS / 4, + 'peak RSS growth ' + Math.round(peak / 1048576) + ' MB is the size of ' + + leakedLoads.toFixed(0) + ' indexes, out of ' + LOADS + ' loaded' + ); + t.end(); + return; + } + var loaded = new Annoy(DIMENSIONS, 'Angular'); + loaded.load(file); + loaded.getNNsByVector(query, 5, 2000, true); + loaded = null; + n++; + setImmediate(function() { + var growth = process.memoryUsage().rss - rssBefore; + if (growth > peak) peak = growth; + next(); + }); + })(); +}); diff --git a/tests/leak-test.js b/tests/leak-test.js new file mode 100644 index 0000000..5007165 --- /dev/null +++ b/tests/leak-test.js @@ -0,0 +1,139 @@ +/* global __dirname process global */ + +// Native memory is released when Annoy objects are collected, and when a +// worker thread that owns indexes exits. Run with --expose-gc. +// +// Each round allocates far more native memory than the allowed RSS growth, +// so a missing finalizer / destructor fails the test. + +var test = require('tape'); +var fs = require('fs'); +var os = require('os'); +var path = require('path'); +var Worker = require('worker_threads').Worker; +var Annoy = require('./load-binding')(); + +if (typeof global.gc !== 'function') { + console.error('run with node --expose-gc'); + process.exit(2); +} + +var DIMS = 64; +var ITEMS = 4000; + +function fill(index) { + var v = new Array(DIMS); + for (var i = 0; i < ITEMS; i++) { + for (var d = 0; d < DIMS; d++) v[d] = Math.sin(i * 31 + d); + index.addItem(i, v); + } +} + +function tick() { + return new Promise(function(resolve) { + setImmediate(resolve); + }); +} + +// N-API finalizers may be deferred to the next event-loop turn after a GC. +async function settle() { + for (var i = 0; i < 5; i++) { + global.gc(); + await tick(); + } +} + +function rssMB() { + return process.memoryUsage().rss / (1024 * 1024); +} + +function mappedCount(file) { + if (process.platform !== 'linux') return 0; + return fs + .readFileSync('/proc/self/maps', 'utf8') + .split('\n') + .filter(function(line) { + return line.indexOf(file) !== -1; + }).length; +} + +test('built indexes are freed when collected', async function(t) { + // One round: 20 indexes x 4000 items x 64 floats, plus 10 trees each, + // ~2.5 MB of native memory per index -> ~50 MB per round. + async function round() { + for (var i = 0; i < 20; i++) { + var index = new Annoy(DIMS, i % 2 ? 'Angular' : 'Euclidean'); + fill(index); + index.build(10); + } + await settle(); + } + await round(); + await round(); + var baseline = rssMB(); + for (var r = 0; r < 20; r++) await round(); // ~1 GB allocated in total + var growth = rssMB() - baseline; + t.ok(growth < 100, 'RSS growth after ~1 GB of indexes: ' + growth.toFixed(1) + ' MB'); + t.end(); +}); + +test('loaded (mmap) indexes are unmapped when collected', async function(t) { + var file = path.join(os.tmpdir(), 'annoy-leak-' + process.pid + '.annoy'); + var src = new Annoy(DIMS, 'Angular'); + fill(src); + src.build(10); + t.ok(src.save(file)); + src.unload(); + try { + (function() { + for (var i = 0; i < 200; i++) { + var loaded = new Annoy(DIMS, 'Angular'); + loaded.load(file); + } + })(); + await settle(); + t.equal(mappedCount(file), 0, 'no mapping of the index file remains'); + } finally { + fs.unlinkSync(file); + } + t.end(); +}); + +test('indexes owned by an exiting worker are freed', async function(t) { + function runWorker() { + return new Promise(function(resolve, reject) { + var w = new Worker( + [ + 'const Annoy = require(' + JSON.stringify(path.join(__dirname, 'load-binding')) + ')();', + 'const keep = [];', + 'for (let n = 0; n < 10; n++) {', + ' const a = new Annoy(' + DIMS + ', "Euclidean");', + ' const v = new Array(' + DIMS + ');', + ' for (let i = 0; i < ' + ITEMS + '; i++) { for (let d = 0; d < ' + DIMS + '; d++) v[d] = Math.cos(i + d); a.addItem(i, v); }', + ' a.build(10);', + ' keep.push(a);', // still reachable when the worker exits + '}', + 'require("worker_threads").parentPort.postMessage(keep.reduce((s, a) => s + a.getNItems(), 0));' + ].join('\n'), + { eval: true } + ); + var count; + w.on('message', function(m) { + count = m; + }); + w.on('error', reject); + w.on('exit', function() { + resolve(count); + }); + }); + } + t.equal(await runWorker(), 10 * ITEMS, 'worker built its indexes'); + await runWorker(); + await settle(); + var baseline = rssMB(); + for (var i = 0; i < 20; i++) await runWorker(); // ~500 MB of indexes + await settle(); + var growth = rssMB() - baseline; + t.ok(growth < 100, 'RSS growth after 20 workers: ' + growth.toFixed(1) + ' MB'); + t.end(); +}); diff --git a/tests/load-binding.js b/tests/load-binding.js new file mode 100644 index 0000000..18e1f97 --- /dev/null +++ b/tests/load-binding.js @@ -0,0 +1,14 @@ +/* global process */ + +// Returns the Annoy class under test. +// +// By default this is the package entry point (index.js, loaded through +// node-gyp-build). Set ANNOY_BINDING to the path of a raw .node file (for +// example the 4.0.1 NAN prebuild) to run the same assertions against another +// binary. A raw addon exports { Annoy }, index.js exports Annoy directly. +module.exports = function loadAnnoy() { + if (process.env.ANNOY_BINDING) { + return require(process.env.ANNOY_BINDING).Annoy; + } + return require('../index'); +}; diff --git a/tests/typed-array-test.js b/tests/typed-array-test.js new file mode 100644 index 0000000..955df99 --- /dev/null +++ b/tests/typed-array-test.js @@ -0,0 +1,70 @@ +// 5.0.0: numeric typed arrays are accepted as vectors by addItem and +// getNNsByVector, read straight from their backing store (4.0.1 ignored them). +// They give the same results as the equivalent JS Array. +// +// node tests/typed-array-test.js +var test = require('tape'); +var Annoy = require('./load-binding')(); + +var ITEMS = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 1, 1]]; + +function indexFrom(toVector) { + var a = new Annoy(3, 'Euclidean'); + ITEMS.forEach(function(v, i) { + a.addItem(i, toVector(v)); + }); + a.build(10); + return a; +} + +test('addItem stores typed arrays like arrays', function(t) { + var reference = indexFrom(function(v) { return v; }); + [Float32Array, Float64Array, Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array] + .forEach(function(Type) { + var a = indexFrom(function(v) { return new Type(v); }); + t.equal(a.getNItems(), ITEMS.length, Type.name + ': every item added'); + t.deepEqual(a.getItem(1), reference.getItem(1), Type.name + ': same stored vector'); + t.deepEqual(a.getNNsByVector([1, 2, 3], 4, -1, true), reference.getNNsByVector([1, 2, 3], 4, -1, true), + Type.name + ': same neighbours and distances'); + }); + t.end(); +}); + +test('getNNsByVector accepts typed arrays', function(t) { + var a = indexFrom(function(v) { return v; }); + [Float32Array, Float64Array, Int32Array].forEach(function(Type) { + t.deepEqual(a.getNNsByVector(new Type([1, 2, 3]), 2, -1, true), a.getNNsByVector([1, 2, 3], 2, -1, true), + Type.name + ': same result as the array'); + }); + t.end(); +}); + +test('length mismatches follow the Array rules', function(t) { + var a = new Annoy(3, 'Euclidean'); + a.addItem(0, new Float32Array([1, 2])); // missing component stays 0 + a.addItem(1, new Float32Array([4, 5, 6, 7])); // extra component ignored + t.deepEqual(a.getItem(0), [1, 2, 0], 'short vector padded with 0'); + t.deepEqual(a.getItem(1), [4, 5, 6], 'long vector truncated'); + t.end(); +}); + +test('typed array views use their own window of the buffer', function(t) { + var a = new Annoy(3, 'Euclidean'); + var buffer = new Float32Array([9, 9, 1, 2, 3, 9]).buffer; + a.addItem(0, new Float32Array(buffer, 2 * 4, 3)); + var bytes = new Uint8Array([0, 0, 7, 8, 9]); + a.addItem(1, bytes.subarray(2)); + t.deepEqual(a.getItem(0), [1, 2, 3], 'Float32Array view with an offset'); + t.deepEqual(a.getItem(1), [7, 8, 9], 'Uint8Array subarray'); + t.end(); +}); + +test('BigInt arrays are still ignored', function(t) { + var a = new Annoy(3, 'Euclidean'); + t.equal(a.addItem(0, new BigInt64Array([1n, 2n, 3n])), undefined); + t.equal(a.getNItems(), 0, 'not added'); + a.addItem(0, [1, 2, 3]); + a.build(1); + t.equal(a.getNNsByVector(new BigUint64Array([1n, 2n, 3n]), 1), undefined, 'getNNsByVector -> undefined'); + t.end(); +}); diff --git a/tests/types.ts b/tests/types.ts new file mode 100644 index 0000000..a3b0d1b --- /dev/null +++ b/tests/types.ts @@ -0,0 +1,33 @@ +// Type-level test of index.d.ts: compiles with `tsc --noEmit --strict`, and every +// `@ts-expect-error` line must fail to type-check. Not executed. +import Annoy = require('..'); + +const index = new Annoy(3, 'Angular'); +index.addItem(0, [1, 2, 3]); +index.addItem(1, new Float32Array([4, 5, 6])); +index.addItem(2, Object.freeze([7, 8, 9])); +index.build(10); +const saved: boolean = index.save('/tmp/index.ann'); +const loaded: boolean = new Annoy(3).load('/tmp/index.ann'); +const ids: number[] = index.getNNsByVector([1, 2, 3], 2); +const withDistances: Annoy.AnnoyNeighbors = index.getNNsByVector(new Float32Array([1, 2, 3]), 2, -1, true); +const byItem: number[] = index.getNNsByItem(0, 2, 100, false); +const item: number[] = index.getItem(0); +const count: number = index.getNItems(); +const distance: number = index.getDistance(0, 1); +const maybe: number[] | Annoy.AnnoyNeighbors = index.getNNsByVector([1, 2, 3], 2, -1, Math.random() > 0.5); +void [saved, loaded, ids, withDistances, byItem, item, count, distance, maybe]; + +// @ts-expect-error unknown metric name +new Annoy(3, 'Cosine'); +// @ts-expect-error a vector is numeric +index.addItem(3, ['1', '2', '3']); +// @ts-expect-error BigInt arrays are not vectors +index.addItem(3, new BigInt64Array(3)); +// @ts-expect-error without distances the result is the id list +const wrong: Annoy.AnnoyNeighbors = index.getNNsByVector([1, 2, 3], 2); +// @ts-expect-error with distances the result is an object +const wrongIds: number[] = index.getNNsByItem(0, 2, -1, true); +// @ts-expect-error a path is a string +index.load(42); +void [wrong, wrongIds]; diff --git a/tests/undefined-behaviour-test.js b/tests/undefined-behaviour-test.js new file mode 100644 index 0000000..aa6aacb --- /dev/null +++ b/tests/undefined-behaviour-test.js @@ -0,0 +1,97 @@ +// Inputs on which the 4.0.1 NAN wrapper had undefined behaviour. 4.0.1 +// returned uninitialised memory or crashed the process on all of these, so +// there is no "old" value to match; 5.x defines them as below. This file only +// runs against the new binding. +// +// Observed on 4.0.1 (linux-x64, Node 22): +// - asking for more neighbours than the index can return gave arrays of the +// requested length padded with garbage ids/distances read past the end of +// a std::vector; +// - querying an index that was never built or loaded crashed (SIGSEGV); +// - a vector shorter than the dimensions read uninitialised stack memory for +// the missing components, a longer one wrote past a stack buffer. + +var test = require('tape'); +var Annoy = require('./load-binding')(); + +function threeItems() { + var a = new Annoy(3, 'Euclidean'); + a.addItem(0, [1, 2, 3]); + a.addItem(1, [4, 5, 6]); + a.addItem(2, [7, 8, 9]); + a.build(); + return a; +} + +test('more neighbours requested than available: only real results are returned', function(t) { + var a = threeItems(); + t.deepEqual(a.getNNsByVector([1, 2, 3], 10, -1, true), { + neighbors: [0, 1, 2], + distances: [0, 5.196152210235596, 10.392304420471191] + }); + t.deepEqual(a.getNNsByVector([1, 2, 3], 10), [0, 1, 2]); + t.deepEqual(a.getNNsByItem(0, 6, -1, false), [0, 1, 2]); + t.deepEqual(a.getNNsByItem(0, 6, -1, true).distances.length, 3); + t.end(); +}); + +test('querying an index that has no trees returns empty results', function(t) { + var u = new Annoy(3, 'Euclidean'); + t.deepEqual(u.getNNsByVector([1, 2, 3], 2, -1, true), { neighbors: [], distances: [] }); + t.deepEqual(u.getNNsByVector([1, 2, 3], 2), []); + var unloaded = threeItems(); + unloaded.unload(); + t.deepEqual(unloaded.getNNsByVector([1, 2, 3], 2), []); + t.end(); +}); + +test('short vectors are zero-padded, extra components are ignored', function(t) { + var a = threeItems(); + t.deepEqual(a.getNNsByVector([1, 2], 2, -1, true), { + neighbors: [0, 1], + distances: [3, 7.348469257354736] + }); + t.deepEqual(a.getNNsByVector([], 1, -1, true).neighbors, [0]); + t.deepEqual(a.getNNsByVector([1, 2, 3, 4, 5, 6, 7, 8], 2, -1, true), { + neighbors: [0, 1], + distances: [0, 5.196152210235596] + }); + + var b = new Annoy(3, 'Euclidean'); + b.addItem(0, [5]); + t.deepEqual(b.getItem(0), [5, 0, 0]); + b.addItem(1, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]); + t.deepEqual(b.getItem(1), [1, 2, 3]); + + var seen = []; + b.addItem(2, [1, 2, 3, { valueOf: () => (seen.push('extra'), 4) }]); + t.deepEqual(seen, ['extra'], 'extra components are still coerced, as in 4.0.1'); + t.end(); +}); + +test('errors thrown while coercing arguments propagate as JS exceptions', function(t) { + // 4.0.1 aborted the process (Maybe::FromJust on an empty value). + var a = threeItems(); + var boom = { + valueOf: function() { + throw new RangeError('boom'); + } + }; + [ + function() { new Annoy(boom); }, + function() { a.addItem(boom, [1, 2, 3]); }, + function() { a.addItem(0, [1, boom, 3]); }, + function() { a.getItem(boom); }, + function() { a.build(boom); }, + function() { a.getDistance(0, boom); }, + function() { a.getNNsByVector([1, 2, 3], boom); }, + function() { a.getNNsByVector([boom, 2, 3], 2); }, + function() { a.getNNsByItem(boom, 2); }, + function() { a.getNNsByItem(0, 2, boom); } + ].forEach(function(fn, i) { + t.throws(fn, /boom/, 'case ' + i); + }); + t.throws(function() { a.getNNsByItem(0, Symbol('n')); }, TypeError, 'Symbol -> TypeError'); + t.deepEqual(a.getNNsByVector([1, 2, 3], 2), [0, 1], 'index still usable afterwards'); + t.end(); +}); diff --git a/tests/wrong-input-test.js b/tests/wrong-input-test.js new file mode 100644 index 0000000..b20617a --- /dev/null +++ b/tests/wrong-input-test.js @@ -0,0 +1,313 @@ +/* global process */ + +// Pins the JS-visible contract of @calldesk/annoy-node 4.0.1 (the NAN +// binding): class shape, argument coercion, defaults and behaviour on wrong +// input. Every expectation below was observed on the 4.0.1 linux-x64 +// prebuild under Node 22, and this file must pass against both bindings: +// +// node tests/wrong-input-test.js # new binding +// ANNOY_BINDING=/path/to/4.0.1.node node tests/wrong-input-test.js +// +// Inputs for which 4.0.1 has undefined behaviour (garbage values, crashes) +// are not here: see tests/undefined-behaviour-test.js. + +var test = require('tape'); +var fs = require('fs'); +var os = require('os'); +var path = require('path'); +var Annoy = require('./load-binding')(); + +var METHODS = [ + 'addItem', + 'build', + 'save', + 'load', + 'unload', + 'getItem', + 'getNNsByVector', + 'getNNsByItem', + 'getNItems', + 'getDistance' +]; + +function tmpFile(name) { + return path.join(os.tmpdir(), 'annoy-wrong-input-' + process.pid + '-' + name); +} + +// 4 items in 3 dimensions, Euclidean, built the same way as the 4.0.1 probe. +function makeSmallIndex() { + var a = new Annoy(3, 'Euclidean'); + a.addItem(0, [1, 2, 3]); + a.addItem(1, 'not an array'); // ignored + a.addItem(1, ['4', '5', { valueOf: () => 6 }]); // elements coerced with ToNumber + a.addItem('2', [7, 8, 9]); // index coerced with ToNumber + a.addItem(3.9, [1, 1, 1]); // index truncated to 3 + a.build(); + return a; +} + +test('class shape', function(t) { + t.equal(typeof Annoy, 'function'); + t.equal(Annoy.name, 'Annoy'); + t.equal(Annoy.length, 0); + t.deepEqual(Object.keys(Annoy.prototype), METHODS, 'enumerable prototype methods, in order'); + t.deepEqual( + Object.getOwnPropertyNames(Annoy.prototype).sort(), + METHODS.concat('constructor').sort() + ); + METHODS.forEach(function(name) { + var d = Object.getOwnPropertyDescriptor(Annoy.prototype, name); + t.deepEqual( + { w: d.writable, e: d.enumerable, c: d.configurable, type: typeof d.value, name: d.value.name, length: d.value.length }, + { w: true, e: true, c: true, type: 'function', name: name, length: 0 }, + name + ' descriptor' + ); + }); + var ctor = Object.getOwnPropertyDescriptor(Annoy.prototype, 'constructor'); + t.equal(ctor.value, Annoy); + t.equal(ctor.enumerable, false); + var proto = Object.getOwnPropertyDescriptor(Annoy, 'prototype'); + t.deepEqual({ w: proto.writable, e: proto.enumerable, c: proto.configurable }, { w: true, e: false, c: false }); + t.deepEqual(Object.keys(Annoy), [], 'no enumerable static properties'); + var instance = new Annoy(3, 'Angular'); + t.ok(instance instanceof Annoy); + t.deepEqual(Object.keys(instance), [], 'instances have no own enumerable properties'); + t.equal(Object.prototype.toString.call(instance), '[object Object]'); + t.end(); +}); + +test('calling the constructor without new returns undefined', function(t) { + t.equal(Annoy(10, 'Angular'), undefined); + t.equal(Annoy(), undefined); + t.end(); +}); + +test('subclassing works', function(t) { + class Sub extends Annoy { + count() { + return this.getNItems(); + } + } + var s = new Sub(2); + s.addItem(0, [1, 1]); + t.equal(s.count(), 1); + t.ok(s instanceof Annoy); + t.ok(s instanceof Sub); + t.end(); +}); + +test('methods called on a non-Annoy receiver throw TypeError: Illegal invocation', function(t) { + var receivers = { + 'plain object': {}, + undefined: undefined, + null: null, + number: 42, + 'object inheriting from an instance': Object.create(new Annoy(3)) + }; + Object.keys(receivers).forEach(function(label) { + METHODS.forEach(function(name) { + t.throws( + function() { + Annoy.prototype[name].call(receivers[label], 0, [1, 2, 3]); + }, + function(err) { + return err instanceof TypeError && err.message === 'Illegal invocation'; + }, + name + ' on ' + label + ); + }); + }); + t.end(); +}); + +test('constructor metric selection and coercion', function(t) { + function distance(dims, metric, a, b) { + var x = metric === undefined ? new Annoy(dims) : new Annoy(dims, metric); + x.addItem(0, a); + x.addItem(1, b); + return x.getDistance(0, 1); + } + t.equal(distance(2, 'Euclidean', [0, 0], [3, 4]), 5); + t.equal(distance(2, 'Manhattan', [0, 0], [3, 4]), 7); + t.equal(distance(2, 'Angular', [1, 0], [0, 1]), 1.4142135381698608); + t.equal(distance(2, 'Angular', [1, 0], [2, 0]), 0, 'Angular ignores norm'); + t.equal(distance(2, 'angular', [1, 0], [2, 0]), 1, 'metric names are case-sensitive: falls back to Euclidean'); + t.equal(distance(2, undefined, [0, 0], [3, 4]), 5, 'default metric is Euclidean'); + t.equal(distance(2, 5, [0, 0], [3, 4]), 5, 'non-string metric is stringified, unknown -> Euclidean'); + t.equal(distance(2, null, [0, 0], [3, 4]), 5); + t.equal(distance(2, { toString: () => 'Manhattan' }, [0, 0], [3, 4]), 7, 'metric coerced with ToString'); + t.equal(distance('2', 'Euclidean', [0, 0], [3, 4]), 5, 'dimensions coerced with ToNumber'); + t.equal(distance({ valueOf: () => 2 }, 'Manhattan', [0, 0], [3, 4]), 7); + t.equal(distance(2.9, 'Manhattan', [0, 0], [3, 4]), 7, 'dimensions truncated'); + + var x = new Annoy('2', 'Euclidean'); + x.addItem(0, [3, 4]); + t.deepEqual(x.getItem(0), [3, 4]); + + t.throws( + function() { + new Annoy(2, Symbol('m')); + }, + function(err) { + return err instanceof TypeError && err.message === 'Cannot convert a Symbol value to a string'; + }, + 'Symbol metric throws TypeError' + ); + t.end(); +}); + +test('addItem, getItem and getNItems coercion', function(t) { + var a = new Annoy(3, 'Euclidean'); + t.equal(a.addItem(0, [1, 2, 3]), undefined, 'addItem returns undefined'); + t.equal(a.addItem(1, 'abc'), undefined, 'non-array vector ignored'); + t.equal(a.addItem(1), undefined, 'missing vector ignored'); + t.equal(a.addItem(1, { length: 3, 0: 1, 1: 2, 2: 3 }), undefined, 'array-like ignored'); + t.equal(a.getNItems(), 1); + a.addItem(1, ['4', '5', { valueOf: () => 6 }]); + t.deepEqual(a.getItem(1), [4, 5, 6]); + t.deepEqual(a.getItem(), [4, 5, 6], 'getItem() defaults to index 1'); + a.addItem('2', [7, 8, 9]); + a.addItem(3.9, [1, 1, 1]); + t.equal(a.getNItems(), 4); + t.deepEqual(a.getItem(3), [1, 1, 1]); + t.deepEqual(a.getItem('2'), [7, 8, 9]); + t.deepEqual(a.getItem(0.5), [1, 2, 3]); + t.deepEqual(a.getItem(0), [1, 2, 3]); + t.deepEqual(a.getItem(1), [4, 5, 6]); + t.equal(typeof a.getNItems(), 'number'); + t.equal(a.getItem(0.1).length, 3, 'getItem returns a dimension-length array'); + a.addItem(undefined, [2, 2, 2]); + t.deepEqual(a.getItem(1), [2, 2, 2], 'addItem(undefined, v) writes item 1'); + t.equal(a.build(), undefined, 'build returns undefined'); + t.equal(a.getNItems(), 4); + t.end(); +}); + +test('getDistance coercion', function(t) { + var a = makeSmallIndex(); + t.equal(a.getDistance(0, 1), 5.196152210235596); + t.equal(a.getDistance(), 0, 'getDistance() compares item 0 with itself'); + t.equal(a.getDistance('0', '2'), 10.392304420471191); + t.equal(a.getDistance(0, 2), 10.392304420471191); + t.equal(a.getDistance(2), a.getDistance(2, 0), 'missing second index defaults to 0'); + t.equal(typeof a.getDistance(0, 1), 'number'); + t.end(); +}); + +test('getNNsByVector / getNNsByItem argument handling', function(t) { + var a = makeSmallIndex(); + var all = { + neighbors: [0, 3, 1, 2], + distances: [0, 2.2360680103302, 5.196152210235596, 10.392304420471191] + }; + t.deepEqual(a.getNNsByVector([1, 2, 3], 4, -1, false), all.neighbors); + t.ok(Array.isArray(a.getNNsByVector([1, 2, 3], 4, -1, false))); + t.deepEqual(a.getNNsByVector([1, 2, 3], 4, -1, true), all); + t.deepEqual(Object.keys(a.getNNsByVector([1, 2, 3], 4, -1, true)), ['neighbors', 'distances']); + t.deepEqual(a.getNNsByVector([1, 2, 3]), [0], 'default n = 1'); + t.deepEqual(a.getNNsByVector([1, 2, 3], 2, undefined, 'yes'), { neighbors: [0, 3], distances: [0, 2.2360680103302] }, 'truthy includeDistances'); + t.deepEqual(a.getNNsByVector([1, 2, 3], 2, -1, 0), [0, 3], 'falsy includeDistances'); + t.deepEqual(a.getNNsByVector([1, 2, 3], 2, -1, null), [0, 3]); + t.deepEqual(a.getNNsByVector([1, 2, 3], '2', '-1', 1), { neighbors: [0, 3], distances: [0, 2.2360680103302] }, 'n and search_k coerced'); + t.deepEqual(a.getNNsByVector(['1', '2', '3'], 2), [0, 3], 'vector elements coerced'); + t.deepEqual(a.getNNsByVector([1, 2, 3], 2, 100), [0, 3], 'explicit search_k'); + t.equal(a.getNNsByVector('x', 2), undefined, 'non-array vector -> undefined'); + t.equal(a.getNNsByVector(), undefined, 'no vector -> undefined'); + t.deepEqual(a.getNNsByVector([1, 2, 3], 0, -1, true), { neighbors: [], distances: [] }, 'n = 0'); + t.deepEqual(a.getNNsByVector([1, 2, 3], 0), [], 'n = 0 without distances'); + t.deepEqual(a.getNNsByVector([1, 2, 3], -2, -1, true), { neighbors: [], distances: [] }, 'negative n'); + + t.deepEqual(a.getNNsByItem(0, 4, -1, true), all); + t.deepEqual(a.getNNsByItem(0, 4), all.neighbors); + t.deepEqual(a.getNNsByItem('0', '2'), [0, 3], 'index and n coerced'); + t.deepEqual(a.getNNsByItem(null, 2), [0, 3], 'null index -> 0'); + t.deepEqual(a.getNNsByItem(0), [0], 'default n = 1'); + t.equal(a.getNNsByItem(), undefined, 'missing index -> undefined'); + t.equal(a.getNNsByItem(undefined, 3, -1, true), undefined, 'undefined index -> undefined'); + t.end(); +}); + +test('coercion side effects run in the 4.0.1 order', function(t) { + var a = makeSmallIndex(); + var log = []; + function spy(name, value) { + return { + valueOf: function() { + log.push(name); + return value; + } + }; + } + a.getNNsByVector([spy('v0', 1), spy('v1', 2), spy('v2', 3)], spy('n', 2), spy('k', -1), true); + t.deepEqual(log, ['n', 'k', 'v0', 'v1', 'v2'], 'getNNsByVector: n, search_k, then vector'); + log = []; + a.getNNsByItem(spy('i', 0), spy('n', 2), spy('k', -1)); + t.deepEqual(log, ['i', 'n', 'k'], 'getNNsByItem: index, n, search_k'); + log = []; + a.getDistance(spy('a', 0), spy('b', 1)); + t.deepEqual(log, ['a', 'b']); + log = []; + var b = new Annoy(2); + b.addItem(spy('i', 0), [spy('x', 1), spy('y', 2)]); + t.deepEqual(log, ['i', 'x', 'y'], 'addItem: index then vector'); + t.end(); +}); + +test('save / load / unload', function(t) { + var a = makeSmallIndex(); + var file = tmpFile('ok.annoy'); + var viaToString = tmpFile('tostring.annoy'); + try { + t.equal(a.save(), false, 'save() without a path -> false'); + t.equal(a.save(undefined), false); + t.equal(a.save('/nonexistent-dir-annoy/x.annoy'), false, 'unwritable path -> false'); + t.throws( + function() { + a.save(Symbol('s')); + }, + function(err) { + return err instanceof TypeError && err.message === 'Cannot convert a Symbol value to a string'; + }, + 'Symbol path throws TypeError' + ); + t.equal(a.save(file), true); + t.equal(a.save({ toString: () => viaToString }), true, 'path coerced with ToString'); + t.ok(fs.existsSync(viaToString)); + + var b = new Annoy(3, 'Euclidean'); + t.equal(b.load(), false, 'load() without a path -> false'); + t.equal(b.load('/nonexistent-annoy-file.annoy'), false, 'missing file -> false'); + t.throws( + function() { + b.load(Symbol('s')); + }, + function(err) { + return err instanceof TypeError && err.message === 'Cannot convert a Symbol value to a string'; + } + ); + t.equal(b.load(file), true); + t.equal(b.getNItems(), 4); + t.deepEqual(b.getNNsByVector([1, 2, 3], 4, -1, true), a.getNNsByVector([1, 2, 3], 4, -1, true)); + t.equal(b.unload(), undefined, 'unload returns undefined'); + t.equal(b.getNItems(), 0, 'unloaded index is empty'); + t.equal(b.unload(), undefined, 'unload twice is harmless'); + t.equal(b.load({ toString: () => viaToString }), true); + t.equal(b.getNItems(), 4); + t.equal(typeof b.load(file), 'boolean'); + } finally { + [file, viaToString].forEach(function(f) { + if (fs.existsSync(f)) fs.unlinkSync(f); + }); + } + t.end(); +}); + +test('many instances can be created and collected', function(t) { + for (var i = 0; i < 2000; i++) { + var x = new Annoy(8, i % 2 ? 'Angular' : 'Manhattan'); + x.addItem(0, [1, 2, 3, 4, 5, 6, 7, 8]); + x.build(2); + } + t.pass('no crash'); + t.end(); +});