-
Notifications
You must be signed in to change notification settings - Fork 143
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix: JS: Improve error handling of batch addition #510
base: main-dev
Are you sure you want to change the base?
Conversation
This patch fixes the crash, but is there a better way? |
Crash if there is an error in batch addition. Example: ``` const usearch = require('usearch'); const index = new usearch.Index({ metric: 'l2sq', connectivity: 16, dimensions: 3 }); index.add(42n, new Float32Array([0.2, 0.6, 0.4])); index.add( [41n, 42n, 43n], [[0.1, 0.6, 0.4], [0.2, 0.6, 0.4], [0.3, 0.6, 0.4]] ) ``` `42n` is duplicated, which causes an error, but then it crash. It seems that it is not better to throw an exception during the process, so we changed it to throw it after it is completed.
aaf832a
to
b20a6e9
Compare
javascript/lib.cpp
Outdated
std::string error = ""; | ||
executor_stl_t executor; | ||
executor.fixed(tasks, [&](std::size_t /*thread_idx*/, std::size_t task_idx) { | ||
add_result_t result = native_->add(static_cast<default_key_t>(keys[task_idx]), | ||
vectors + task_idx * native_->dimensions()); | ||
if (!result) | ||
Napi::Error::New(ctx.Env(), result.error.release()).ThrowAsJavaScriptException(); | ||
error += "<key:" + std::to_string(keys[task_idx]) + " message:" + result.error.release() + ">"; | ||
}); | ||
if (error.size() > 0) | ||
Napi::Error::New(ctx.Env(), error).ThrowAsJavaScriptException(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is not thread-safe. You need a mutex
to safeguard the error string. Moreover, your solution may result in a heap allocation in the default string constructor. There should be a way to avoid it.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the review.
I understand that adding it to a string is not a good idea, but I would like to know if there is a better way to handle errors in such cases.
Would a Python implementation be helpful?
https://github.com/unum-cloud/usearch/blob/main/python/lib.cpp#L180-L211
Crash if there is an error in batch addition.
Example:
42n
is duplicated, which causes an error, but then it crash.It seems that it is not better to throw an exception during the process, so we changed it to throw it after it is completed.