-
Notifications
You must be signed in to change notification settings - Fork 11
feat: per-task database sessions to prevent session state leakage #637
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
Closed
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Addresses 'session in prepared state' errors by creating isolated database sessions for each task execution instead of sharing a global scoped session. Changes: - Add TaskSessionManager and create_task_session() to database/engine.py - Update BaseCodecovTask.run() to create per-task sessions with proper cleanup - Update apply_async() and route_task() to use temporary routing sessions - Add set_test_session_factory() for test session injection - Update test utilities and mocks to work with new session architecture This is a minimal change that relies on existing fallback patterns in services (db_session = obj.get_db_session() if db_session is None). Objects queried via the task session will naturally use it.
0946d17 to
9017e23
Compare
- Always cleanup test session factory (prevent test pollution) - Add try-except to routing session cleanup (prevent connection leaks) - Handle SoftTimeLimitExceeded during commit (known edge case)
InterfaceError signals transient connection issues and should be retried rather than silently failing (consistent with DataError, IntegrityError, SQLAlchemyError handling).
- Reset test session factory at start of hook_session (defensive cleanup) - Mock rollback() to prevent interfering with test savepoints - Remove broken mocker.stopall override approach - Simplify cleanup logic
The TASK_CORE_RUNTIME metric is documented as excluding db commits, so the commit() call should be outside the timer block.
- Remove problematic in_transaction() and rollback() mocks - Mock wrap_up_task_session to prevent cleanup interference - Keep only necessary mocks: close(), commit() -> flush()
- Fix method name (was wrap_up_task_session, should be _cleanup_task_session) - Add BaseCodecovTask import - Apply ruff fixes
- Update test_commit_measurement_update_component_parallel to use hook_session - Update test_delete_repository_data_measurements_only to use hook_session - Update test_compute_component_comparisons_parallel to use hook_session - Pass db_session parameter to save_commit_measurements calls
…components_measurements These functions need the db_session parameter to work with per-task sessions, matching the pattern used in PR #618.
Without these mocks, the task's run() method would detect the test transaction and call rollback(), destroying all test data. This caused e2e tests to fail because their created data was rolled back before the tasks could use it.
Contributor
Author
|
Closing as won't do - the scope of this change (per-task database sessions) is significant and the user impact from the "session in prepared state" errors doesn't justify the risk/effort at this time. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
Addresses "session in prepared state" errors by creating isolated database sessions for each task execution instead of sharing a global scoped session.
Problem
When tasks share a global scoped session (
get_db_session()), session state can leak between tasks:InvalidRequestError: session in 'prepared' stateSolution
Create isolated per-task sessions using a new
create_task_session()function:run()finallyblock (rollback + close)apply_async()androute_task()also use temporary sessionsChanges
database/engine.pyTaskSessionManager,create_task_session(),set_test_session_factory()tasks/base.pyrun()andapply_async()with proper cleanupcelery_task_router.pytasks/tests/utils.pyhook_session()to configure test session factorycreate_task_sessionMinimal Scope
This PR is intentionally minimal (6 files vs 22 in the original). Services that call
obj.get_db_session()will naturally get the correct task session because objects queried via the task session are bound to it.Explicit
db_session=db_sessionplumbing can be added in a follow-up PR if needed.Testing
create_task_sessioninstead ofget_db_sessionset_test_session_factory()for test session injectionhook_session()utility updated to work with new architectureNote
Introduces isolated SQLAlchemy sessions per worker task and uses temporary sessions for routing to prevent session state leakage.
TaskSessionManagerwithcreate_task_session()andset_test_session_factory()indatabase/engine.pyBaseCodecovTask: use per-task session inrun()(commit on success, robust rollback/close in_cleanup_task_session);apply_async()now does routing lookups with a temp session; preserve headers/metricscelery_task_router.route_taskto use a temporary session for plan/owner lookups with safe cleanupdb_sessionplumbing inservices.timeseries.upsert_components_measurementsandtasks.save_commit_measurementscreate_task_session; add test utilities to inject shared test session and prevent test-transaction cleanupWritten by Cursor Bugbot for commit 640146d. This will update automatically on new commits. Configure here.