Reduce SQLAlchemy session scope to avoid stale data #2475
Merged
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 PR changes two things:
The change to request-local sessions inside CAPE-web is accomplished by calling
scoped_session().remove()
at the end of every web request. Whilst this bug didn't appear to affect anything critical, it did manifest itself in the task status views (API and UI) by ocassionally showing stale data after a task status had been updated on the backend.Using request-local sessions is the recommended approach inside web apps as noted in the SQLAlchemy docs:
The change to avoid stale data inside of the processor is achieved by removing the session after processing. The next task that runs in the same process will grab a new session and will be forced to pull new objects from the database, preventing any data inconsistencies.
This manifested itself in an issue where the task status fails to change to
reported
within theprocess
function if the same worker process had previously processed the same task. Although the function call is executed inside theprocess
function, SQLAlchemy does not issue an update statement to the database. This occurs because the task object is already present in the ORM cache from a previous job, with a status ofreported
.