How to use pn.state.on_session_destroyed

It happens as sessions are being unloaded from memory. I’ve encountered the same bug numerous times:

[BUG] background thread stops when session is destroyed, leading to weird errors - Panel - HoloViz Discourse

'Exception' is not defined - lol

pn.state.on_session_destroyed callback also doesn’t work when you use lifecycle hooks in a separate file (even though it’s in the state’s callbacks). However, the on_session_destroyed callback does get called from within the app_hooks.py file :man_shrugging:

Extra FYI:
The session unloading seems to happen more aggressively when using --num-threads
This is actually a nice bug (feature? :grin: ) as you can get around memory leaks. Even better if you periodically restart your cluster workers to release memory back to the OS:
image

Haven’t had issues with memory leaks since.

Ah, btw - this also makes watcher callbacks fail. Can only let them fail silently as sessions are being unloaded.

image

2 Likes