Cleanup fail with "invalid context" error

Hi. I’m running into issues trying to clean up when exiting application. Invoking rtContextDestroy causes error code 1280, with the following error text:
Invalid context (Details: Function “RTresult _rtContextDestroy(RTcontext)” caught exception: Encountered a CUDA error: cudaDriver().CuCtxGetCurrent( &context ) returned (4): Deinitialized

I’ve already confirmed that the context is created only once throughout the lifetime of the application, and it’s not destroyed multiple times.
I tried running rtDeviceGetDeviceCount when exiting, just out of curiosity, and it segfaults.
If I destroy the context earlier in the application (instead of upon exit), everything seems fine.

Anybody have any idea what might be happening?

I wish I had an example code to post, but for some reason I can’t reproduce the same problem with smaller applications or with any of SDK examples.
I’m using Ubuntu 16.04, Optix 5.1, display driver 396.45 if that helps.

I noticed (via lsof) that when the application is exiting, had already been unloaded before rtContextDestroy is invoked. Could that have anything to do with it? If so, what would cause it to unload cudart before context is destroyed?

Not sure what could be destroying the CUDA context earlier. Is this a plugin environment or do you have full control over the application? The primary CUDA context, which OptiX uses, is shared by everything in the current process. Is it possible that another thread (or plugin) in the same process is cleaning up first?