Skip to content

fix: make searchKnn memory-safe and exception-safe#363

Closed
andreinknv wants to merge 1 commit into
yoshoku:mainfrom
andreinknv:fix/searchknn-safety
Closed

fix: make searchKnn memory-safe and exception-safe#363
andreinknv wants to merge 1 commit into
yoshoku:mainfrom
andreinknv:fix/searchknn-safety

Conversation

@andreinknv

Copy link
Copy Markdown

Problem

searchKnn (both BruteforceSearch and HierarchicalNSW) had two
defects:

  1. Memory leak. The optional CustomFilterFunctor is allocated with
    new and freed only on the success path. The early error returns —
    array-length mismatch and k out of range — return without deleting
    it, leaking the functor on every rejected call that supplied a filter.
  2. Process abort. The call into hnswlib's searchKnn is not wrapped
    in try/catch. hnswlib throws std::runtime_error ("cand error")
    on a corrupt graph; the exception escapes the N-API method and aborts
    the process. Every other hnswlib call site in this file is already
    guarded.

Fix

Hold the functor in a std::unique_ptr so it is released on every exit
path, and wrap the searchKnn call so a hnswlib exception surfaces as a
thrown JavaScript Error.

Verification

npm test — 100/100 passing; native addon builds clean.

Note: this branch and feat/accept-float32array-input both touch
searchKnn; whichever merges first, the other needs only a trivial
textual rebase.

🤖 Generated with Claude Code

searchKnn (both classes) had two defects around its optional filter
functor and the call into hnswlib:

- The CustomFilterFunctor was heap-allocated with new and freed only
  on the success path. The early error returns — array-length
  mismatch and k out of range — leaked it.
- The call into hnswlib's searchKnn was unguarded. hnswlib throws
  std::runtime_error ("cand error") on a corrupt graph; the
  exception escaped the N-API method and aborted the process. Every
  other hnswlib call site here is already guarded.

Hold the functor in a std::unique_ptr so it is released on every
exit path, and wrap the search call so a hnswlib exception surfaces
as a thrown JavaScript Error.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@andreinknv andreinknv closed this by deleting the head repository May 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant