Skip to content

fix: wrap sync task in Flask application context#615

Open
dahagag wants to merge 1 commit into
ascoderu:masterfrom
dahagag:fix/celery-app-context
Open

fix: wrap sync task in Flask application context#615
dahagag wants to merge 1 commit into
ascoderu:masterfrom
dahagag:fix/celery-app-context

Conversation

@dahagag
Copy link
Copy Markdown
Member

@dahagag dahagag commented May 29, 2026

Problem

The celery sync task was failing silently with a RuntimeError when trying to commit database changes:

RuntimeError: No application found. Either work inside a view function or push an application context.

This happens because the async task executes outside of Flask's application context. When _mark_as_synced() tries to commit via db.session.commit(), Flask-SQLAlchemy needs an active application context to function.

Root Cause

Celery worker processes run independently from the Flask application. Database operations that depend on Flask-SQLAlchemy's request/app context must be explicitly wrapped.

Solution

Wrap the sync task execution in a Flask application context using with webapp.app_context():. This ensures SQLAlchemy session handling works correctly during database operations.

Changes

  • Updated sync() task in tasks.py to wrap all operations in webapp.app_context()
  • Maintains all existing logic and error handling
  • No changes to dependencies or API

Testing

  • ✅ Upload completes successfully (HTTP 200 to server)
  • ✅ Database commit succeeds without RuntimeError
  • ✅ Emails marked as synced in local database

Related

Complements systemctl service restart fix in PR #614

The sync task was failing to commit database changes because it was
executing outside of the Flask application context. This caused
RuntimeError when trying to mark emails as synced after upload.

Added app_context() wrapper to ensure proper SQLAlchemy session
handling during database operations.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant