fix(medcat-service): Add thread safety to medcat processor dependency #200
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This fixes a threading issue on startup causing multiple medcat processors to be created.
I think this will also fix #141 , though I'm not certain how to recreate that one. This keeps it with lazy initialization instead of on startup, which I'd generally prefer.
Previous Behaviour
New behaviour
Startup the service whilst loading it with 20 requests at the same time
It still enters get_medcat_processor 20 times, as they have yet to finish and store in the cache
It then enters get_medcat_processor_singleton but each thread hits the lock, so only the first one actually creates the processor
We end up with log lines like this, where only one processor is initialised and used
Notes
This documentation from lru_cache explains why this change is required:
So this is saying if I call /process 20 times in parallel, but there's nothing in the cache yet, all 20 get created.
The change in here still uses lru_cache so that subsequent calls dont have to lock. It's using a global tuple with settings as the key, so it is possible to later change the processor if settings changes - this means all the tests still work, though during regular use it should never trigger (if we trust lru_cache)