Skip to content
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

Enable FinalizationRegistry #3560

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft

Enable FinalizationRegistry #3560

wants to merge 4 commits into from

Conversation

ketanhwr
Copy link
Member

No description provided.

@@ -4,6 +4,82 @@

export default {
async fetch(req, env) {
return new Response("Hello World\n");
let resp = await fetch("https://example.com");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't forget to revert this sample back to its original state when this is done. Most likely it would make sense to have this as a separate example.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks like more of a test. Should it be converted to a wd-test?

@@ -2276,6 +2276,8 @@ class ExternalMemoryAdjustment final {
// Isolate<TypeWrapper>::Lock. Usually this is only done in top-level code, and the Lock is
// passed down to everyone else from there. See setup.h for details.

class V8System;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we should be exposing V8System like this. The intent of JSG is to abstract V8 specifics away as much as possible and this just exposes them more. If we have to expose something here, which I'm unsure about, then the functionality should be folded into a new jsg::Lock method... like js.pumpMessageLoop() so that the details of interfacing with the v8 APIS do not need to leak more out to other areas.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I agree. js.pumpMessageLoop() was the intended plan before I sent this out for review 😅

@@ -1431,7 +1431,7 @@ class ResourceWrapper {
// We do not allow use of WeakRef or FinalizationRegistry because they introduce
// non-deterministic behavior.
check(global->Delete(context, v8StrIntern(isolate, "WeakRef"_kj)));
check(global->Delete(context, v8StrIntern(isolate, "FinalizationRegistry"_kj)));
//check(global->Delete(context, v8StrIntern(isolate, "FinalizationRegistry"_kj)));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We'd be enabling WeakRef too right?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current plan is to only enable FinalizationRegistry, given the immediate memory cleanup benefits for wasm users. WeakRef is something we can probably think about as a followup.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there actually anything more needed to enable WeakRef? If it's just a matter of removing the line above, I think we should do it in this change.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes it should work by just removing the line, although @harrishancock was concerned about WeakRef giving immediate notification of GC collection instead of FinalizationRegistry which is more non-deterministic.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WeakRef does not give immediate notification thankfully. I suppose someone could poll it as quickly as possible to approximate immediate notification but thankfully it does not provide a notification api.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My concern isn't immediate notification, but lack of control over when notifications occur. With FinalizationRegistry, we can control exactly when finalization callbacks are scheduled. With WeakRef, we have no control over when they appear empty -- that's entirely up to the GC. So, if controlling the timing of GC observation is important for risk mitigation, then enabling WeakRef is strictly higher risk than enabling FinalizationRegistry.

That said, I'd love to just accept the risk and enable WeakRef and be done with it.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm good with accepting the risk as I thinks it is likely quite minimal. @kentonv ?

if (!isCurrentNull()) {
KJ_LOG(ERROR, "IoContext not-null before running PumpMessageLoop()");
} else {
worker->runInLockScope(lockType, [&](Worker::Lock& lock) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Taking a new lock here, immediately after releasing the previous one, is expensive. You should find a way to run PumpMessageLoop() just before releasing the previous lock instead.

jsg::Lock& js = lock;
auto& system = const_cast<jsg::V8System&>(js.getV8System());
KJ_DBG(js.v8Isolate);
while (v8::platform::PumpMessageLoop(&system.getDefaultPlatform(), js.v8Isolate, v8::platform::MessageLoopBehavior::kDoNotWait)) {}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It feels wrong for this code to be aware of the v8::Platform. Knowledge of how the platform is set up (and even the fact that we use the default platform) should be encapsulated inside JSG.

To that end, perhaps jsg::Lock should have a pumpMessageLoop() method, which internally calls v8::platform::PumpMessageLoop appropriately?

jsg::Lock& js = lock;
auto& system = const_cast<jsg::V8System&>(js.getV8System());
KJ_DBG(js.v8Isolate);
while (v8::platform::PumpMessageLoop(&system.getDefaultPlatform(), js.v8Isolate, v8::platform::MessageLoopBehavior::kDoNotWait)) {}
Copy link
Member

@kentonv kentonv Feb 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this actually the right time to call PumpMessageLoop -- at the end of every single ctx.run()?

Arguably it might be preferable if we invoked PumpMessageLoop asynchronously later on when we're not actively responding to a request.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that we likely need to find a better place for this. We can end up running ctx.run quite a few times during a request.

@@ -1431,7 +1431,7 @@ class ResourceWrapper {
// We do not allow use of WeakRef or FinalizationRegistry because they introduce
// non-deterministic behavior.
check(global->Delete(context, v8StrIntern(isolate, "WeakRef"_kj)));
check(global->Delete(context, v8StrIntern(isolate, "FinalizationRegistry"_kj)));
//check(global->Delete(context, v8StrIntern(isolate, "FinalizationRegistry"_kj)));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This probably needs a compat flag as I suspect there are people that check for the existence of these APIs and use them if they are available -- making them suddenly available would therefore cause such workers to start taking a new code path which could end up being broken.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah that was something on my mind as well, had a brief discussion with @mikenomitch about placing this behind a compat date/flag.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This makes me sad, but yes, compat flag absolutely needed. I've seen such checks in the wild a few times now.

Copy link
Member Author

@ketanhwr ketanhwr left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO: tests (was testing adhoc as of now)

jsWeakRef @73 :Bool
$compatEnableFlag("enable_weak_ref")
$compatDisableFlag("disable_weak_ref");
# Enables WeakRefs and FinalizationRegistry API. WebAssembly based projects often rely on this API for wasm memory cleanup
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we add a compatibility date as well (I think we should?)? How exactly do we decide what goes behind a date vs flag vs both?

@@ -1377,6 +1380,73 @@ kj::Promise<void> IoContext::startDeleteQueueSignalTask(IoContext* context) {
}
}

void IoContext::pumpMessageLoop() {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a some duplication here with IoContext::runImpl(), but ensuring there's no IoContext while reusing those functions would require specializing run(), runImpl() as well as runInContextScope() to pass through a flag indicating a null IoContext. runInContextScope() also runs the code using JSG_WITHIN_CONTEXT_SCOPE which I don't think is necessarily required to pump the message loop.

workerLock.logUncaughtException(UncaughtExceptionSource::INTERNAL,
jsg::JsValue(jsException), jsg::JsMessage(tryCatch.Message()));

jsg::throwTunneledException(workerLock.getIsolate(), jsException);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is copied over from runImpl() but I don't think it would be needed here since it runs after the request handler has run.. (but I don't fully understand the implications here)

@@ -271,7 +271,10 @@ struct WorkerdApi::Impl final {
auto version = getPythonBundleName(pythonRelease);
auto bundle = KJ_ASSERT_NONNULL(
fetchPyodideBundle(pythonConfig, version), "Failed to get Pyodide bundle");
auto context = lock.newContext<api::ServiceWorkerGlobalScope>(lock.v8Isolate);
jsg::NewContextOptions options{
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we enable this for python workers unconditionally or behind a flag as well? I think pyodide already has its own dummy FinalizationRegistry implementation
cc: @hoodmane

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.

4 participants