Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

Add fair database-backed job queue for multi-user processing

Murtaza Nasiree0e97f6129c
diff --git a/config/env.asr.example b/config/env.asr.example
index 2f47b551..1ee3405d 100644
--- a/config/env.asr.example
+++ b/config/env.asr.example
@@ -138,6 +138,14 @@ ENABLE_PUBLIC_SHARING=true
# Note: Admins can control public sharing permissions per-user in the admin dashboard
# even when ENABLE_PUBLIC_SHARING is true
+# --- Background Processing Queue ---
+# Number of concurrent workers for processing uploads (default: 2)
+# Increase for higher throughput, decrease to limit resource usage
+JOB_QUEUE_WORKERS=2
+
+# Maximum retry attempts for failed jobs (default: 3)
+JOB_MAX_RETRIES=3
+
# --- Docker Settings (rarely need to be changed) ---
SQLALCHEMY_DATABASE_URI=sqlite:////data/instance/transcriptions.db
UPLOAD_FOLDER=/data/uploads
diff --git a/config/env.whisper.example b/config/env.whisper.example
index 18ad9047..c3eb5357 100644
--- a/config/env.whisper.example
+++ b/config/env.whisper.example
@@ -141,6 +141,14 @@ ENABLE_PUBLIC_SHARING=true
# Note: Admins can control public sharing permissions per-user in the admin dashboard
# even when ENABLE_PUBLIC_SHARING is true
+# --- Background Processing Queue ---
+# Number of concurrent workers for processing uploads (default: 2)
+# Increase for higher throughput, decrease to limit resource usage
+JOB_QUEUE_WORKERS=2
+
+# Maximum retry attempts for failed jobs (default: 3)
+JOB_MAX_RETRIES=3
+
# --- Docker Settings (rarely need to be changed) ---
SQLALCHEMY_DATABASE_URI=sqlite:////data/instance/transcriptions.db
UPLOAD_FOLDER=/data/uploads
diff --git a/config/env.whisperx.example b/config/env.whisperx.example
index ddf0f5e4..f9097d39 100644
--- a/config/env.whisperx.example
+++ b/config/env.whisperx.example
@@ -148,6 +148,14 @@ ENABLE_PUBLIC_SHARING=true
# Note: Admins can control public sharing permissions per-user in the admin dashboard
# even when ENABLE_PUBLIC_SHARING is true
+# --- Background Processing Queue ---
+# Number of concurrent workers for processing uploads (default: 2)
+# Increase for higher throughput, decrease to limit resource usage
+JOB_QUEUE_WORKERS=2
+
+# Maximum retry attempts for failed jobs (default: 3)
+JOB_MAX_RETRIES=3
+
# --- Docker Settings (rarely need to be changed) ---
SQLALCHEMY_DATABASE_URI=sqlite:////data/instance/transcriptions.db
UPLOAD_FOLDER=/data/uploads
diff --git a/docs/admin-guide/system-settings.md b/docs/admin-guide/system-settings.md
index 907ad872..4381130b 100644
--- a/docs/admin-guide/system-settings.md
+++ b/docs/admin-guide/system-settings.md
@@ -78,6 +78,16 @@ Beyond the UI-configurable settings above, several environment variables in your
For detailed retention configuration, see the [Retention & Auto-Deletion](retention.md) guide.
+### Background Processing Queue
+
+Speakr uses a fair job queue to process uploads and reprocessing requests. The queue ensures multiple users get fair access to processing resources.
+
+**JOB_QUEUE_WORKERS**: Number of concurrent workers processing jobs. Higher values increase throughput but consume more resources. Default: `2`.
+
+**JOB_MAX_RETRIES**: How many times a failed job will be retried before being marked as failed. Default: `3`.
+
+Jobs are persisted to the database and survive application restarts. If Speakr restarts while jobs are processing, they automatically resume from where they left off.
+
### Configuration Example
```bash
@@ -93,6 +103,10 @@ USERS_CAN_DELETE=false # Only admins can delete
ENABLE_AUTO_DELETION=true
DEFAULT_RETENTION_DAYS=90
DELETION_MODE=audio_only
+
+# Processing queue
+JOB_QUEUE_WORKERS=2
+JOB_MAX_RETRIES=3
```
After modifying environment variables, restart your Speakr instance for changes to take effect:
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index 0ed639f6..cda85d7a 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -26,9 +26,15 @@ Sometimes the admin user creation fails silently if the password doesn't meet re
### Transcription Never Starts
-When recordings stay in "pending" status indefinitely, the background processor might have stopped. Check the logs for error messages about the [transcription service](features.md#multi-engine-support). Monitor processing status in the [vector store](admin-guide/vector-store.md) admin panel. API key issues are the most common cause - verify your OpenAI or OpenRouter API key is valid and has available credits.
+When recordings stay in "pending" or "queued" status indefinitely, check these common causes:
-Network connectivity problems can also prevent transcription. The container needs to reach external API endpoints. If you're behind a corporate proxy, you'll need to configure proxy settings in your Docker environment.
+**QUEUED status**: Recordings show "Queued" when waiting for an available worker. By default, 2 workers process jobs concurrently. If many recordings are queued, they'll be processed in fair round-robin order across users - no single user can monopolize the queue. Increase `JOB_QUEUE_WORKERS` in your environment file for faster throughput.
+
+**Background processor stopped**: Check the logs for error messages about the [transcription service](features.md#multi-engine-support). Monitor processing status in the [vector store](admin-guide/vector-store.md) admin panel.
+
+**API key issues**: The most common cause - verify your OpenAI or OpenRouter API key is valid and has available credits.
+
+**Network connectivity**: The container needs to reach external API endpoints. If you're behind a corporate proxy, you'll need to configure proxy settings in your Docker environment.
### Transcription Fails Immediately
@@ -70,6 +76,10 @@ Network speed affects transcription time since audio must upload to API services
The choice of transcription model impacts speed. Whisper Large is more accurate but slower than Whisper Base. If speed matters more than perfect accuracy, consider using a smaller model through your API settings.
+### Recordings Stuck After Restart
+
+If Speakr crashed or restarted while recordings were processing, they automatically resume on next startup. The job queue persists to the database, so no uploads are lost. Check the logs for "Recovered orphaned jobs" messages confirming jobs were resumed.
+
### Files Over 25MB Fail with OpenAI
OpenAI's Whisper API has a 25MB file size limit. For larger files, enable [chunking](features.md#audio-chunking) in your environment configuration. Learn about [chunking strategies](faq.md#whats-the-difference-between-chunking-by-size-vs-duration):
diff --git a/src/api/recordings.py b/src/api/recordings.py
index e7e9e3d8..38d7a82a 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -8,7 +8,6 @@ import os
import json
import re
import mimetypes
-import threading
import time
import subprocess
from datetime import datetime, timedelta
@@ -24,10 +23,7 @@ from src.database import db
from src.models import *
from src.utils import *
from src.config.app_config import ASR_MIN_SPEAKERS, ASR_MAX_SPEAKERS, ASR_DIARIZE
-from src.tasks.processing import (
- transcribe_audio_asr, transcribe_audio_task, generate_summary_only_task,
- format_transcription_for_llm, transcribe_with_chunking
-)
+from src.tasks.processing import format_transcription_for_llm, transcribe_with_chunking
from src.services.speaker import update_speaker_usage, identify_unidentified_speakers_from_text
from src.services.speaker_embedding_matcher import update_speaker_embedding
from src.services.speaker_snippets import create_speaker_snippets
@@ -573,18 +569,19 @@ def generate_summary_endpoint(recording_id):
if client is None:
return jsonify({'error': 'Summary service is not available (OpenRouter client not configured)'}), 503
- current_app.logger.info(f"Starting summary generation for recording {recording_id}")
-
- # Generate summary in background thread
- thread = threading.Thread(
- target=generate_summary_only_task,
- args=(current_app._get_current_object().app_context(), recording_id)
+ current_app.logger.info(f"Queueing summary generation for recording {recording_id}")
+
+ # Queue summary generation job
+ job_queue.enqueue(
+ user_id=current_user.id,
+ recording_id=recording.id,
+ job_type='summarize',
+ params={'user_id': current_user.id}
)
- thread.start()
-
+
return jsonify({
- 'success': True,
- 'message': 'Summary generation started'
+ 'success': True,
+ 'message': 'Summary generation queued'
})
except Exception as e:
@@ -736,12 +733,13 @@ def update_speakers(recording_id):
summary_queued = False
if regenerate_summary:
- current_app.logger.info(f"Regenerating summary for recording {recording_id} after speaker update.")
- thread = threading.Thread(
- target=generate_summary_only_task,
- args=(current_app._get_current_object().app_context(), recording.id)
+ current_app.logger.info(f"Queueing summary regeneration for recording {recording_id} after speaker update.")
+ job_queue.enqueue(
+ user_id=current_user.id,
+ recording_id=recording.id,
+ job_type='summarize',
+ params={'user_id': current_user.id}
)
- thread.start()
summary_queued = True
# Return recording with per-user status
@@ -819,12 +817,13 @@ def update_transcript(recording_id):
summary_queued = False
if regenerate_summary:
- current_app.logger.info(f"Regenerating summary for recording {recording_id} after transcript update.")
- thread = threading.Thread(
- target=generate_summary_only_task,
- args=(current_app._get_current_object().app_context(), recording.id)
+ current_app.logger.info(f"Queueing summary regeneration for recording {recording_id} after transcript update.")
+ job_queue.enqueue(
+ user_id=current_user.id,
+ recording_id=recording.id,
+ job_type='summarize',
+ params={'user_id': current_user.id}
)
- thread.start()
summary_queued = True
# Export will happen after summary regenerates
else:
@@ -1084,21 +1083,22 @@ def reprocess_transcription(recording_id):
except (ValueError, TypeError):
max_speakers = None
- diarize_setting = ASR_DIARIZE if 'ASR_DIARIZE' in os.environ or USE_ASR_ENDPOINT else (recording.owner.diarize if recording.owner else False)
-
- # Enqueue the job
- job = job_queue.enqueue(
- func=transcribe_audio_asr,
- args=(app_context, recording.id, filepath, filename_for_asr, start_time, recording.mime_type, language, diarize_setting, min_speakers, max_speakers),
- recording_id=recording.id
- )
+ # Enqueue the job using new fair queue API
+ job_params = {
+ 'language': language,
+ 'min_speakers': min_speakers,
+ 'max_speakers': max_speakers
+ }
else:
- # Enqueue the job for standard Whisper API
- job = job_queue.enqueue(
- func=transcribe_audio_task,
- args=(app_context, recording.id, filepath, filename_for_asr, start_time),
- recording_id=recording.id
- )
+ # Standard Whisper API - no special params needed
+ job_params = {}
+
+ job_id = job_queue.enqueue(
+ user_id=current_user.id,
+ recording_id=recording.id,
+ job_type='reprocess_transcription',
+ params=job_params
+ )
# Get queue position for response
queue_position = job_queue.get_position_in_queue(recording.id)
@@ -1157,32 +1157,31 @@ def reprocess_summary(recording_id):
else:
current_app.logger.info(f"No custom prompt override provided for recording {recording_id}, will use default priority")
- # Set status to SUMMARIZING and clear existing summary
+ # Clear existing summary (status will be set to QUEUED by job_queue.enqueue)
recording.summary = None
- recording.status = 'SUMMARIZING'
# Clear existing events since they might be re-extracted during summary generation
Event.query.filter_by(recording_id=recording_id).delete()
db.session.commit()
- # Refresh the recording object to ensure it has the latest committed data
- db.session.refresh(recording)
-
- current_app.logger.info(f"Starting summary reprocessing for recording {recording_id}" +
+ current_app.logger.info(f"Queueing summary reprocessing for recording {recording_id}" +
(f" with custom prompt (length: {len(custom_prompt)})" if custom_prompt else ""))
- # Start summary generation in background thread
- def reprocess_summary_task(app_context, recording_id, custom_prompt_override=None, user_id=None):
- with app_context:
- current_app.logger.info(f"Starting summary reprocessing for recording {recording_id} using generate_summary_only_task")
- generate_summary_only_task(app_context, recording_id, custom_prompt_override=custom_prompt_override, user_id=user_id)
-
- thread = threading.Thread(
- target=reprocess_summary_task,
- args=(current_app._get_current_object().app_context(), recording.id, custom_prompt, current_user.id)
+ # Queue summary generation job
+ job_params = {
+ 'custom_prompt': custom_prompt,
+ 'user_id': current_user.id
+ }
+ job_queue.enqueue(
+ user_id=current_user.id,
+ recording_id=recording.id,
+ job_type='reprocess_summary',
+ params=job_params
)
- thread.start()
+
+ # Refresh recording to get updated status
+ db.session.refresh(recording)
# Return recording with per-user status
recording_dict = recording.to_dict(viewer_user=current_user)
@@ -2070,27 +2069,23 @@ def upload_file():
current_app.logger.info(f"Initial recording record created with ID: {recording.id}")
- # --- Start transcription & summarization in background thread ---
- start_time = datetime.utcnow()
-
- # Pass ASR parameters and first tag to the transcription task (for compatibility with existing functions)
+ # --- Queue transcription job ---
first_tag = selected_tags[0] if selected_tags else None
- if USE_ASR_ENDPOINT:
- current_app.logger.info(f"Starting ASR transcription thread for recording {recording.id} with params: language={language}, min_speakers={min_speakers}, max_speakers={max_speakers}, tag_id={first_tag.id if first_tag else None}")
- thread = threading.Thread(
- target=transcribe_audio_task,
- args=(current_app._get_current_object().app_context(), recording.id, filepath, os.path.basename(filepath), start_time),
- kwargs={'language': language, 'min_speakers': min_speakers, 'max_speakers': max_speakers, 'tag_id': first_tag.id if first_tag else None}
- )
- else:
- current_app.logger.info(f"Starting Whisper transcription thread for recording {recording.id} with tag_id={first_tag.id if first_tag else None}")
- thread = threading.Thread(
- target=transcribe_audio_task,
- args=(current_app._get_current_object().app_context(), recording.id, filepath, os.path.basename(filepath), start_time),
- kwargs={'tag_id': first_tag.id if first_tag else None}
- )
- thread.start()
- current_app.logger.info(f"Background processing thread started for recording ID: {recording.id}")
+ job_params = {
+ 'language': language,
+ 'min_speakers': min_speakers,
+ 'max_speakers': max_speakers,
+ 'tag_id': first_tag.id if first_tag else None
+ }
+
+ current_app.logger.info(f"Queueing transcription for recording {recording.id} with params: {job_params}")
+ job_queue.enqueue(
+ user_id=current_user.id,
+ recording_id=recording.id,
+ job_type='transcribe',
+ params=job_params
+ )
+ current_app.logger.info(f"Transcription job queued for recording ID: {recording.id}")
return jsonify(recording.to_dict(viewer_user=current_user)), 202
diff --git a/src/config/startup.py b/src/config/startup.py
index 44164b21..91f45b53 100644
--- a/src/config/startup.py
+++ b/src/config/startup.py
@@ -109,13 +109,24 @@ def initialize_file_exporter(app):
def initialize_job_queue(app):
- """Initialize and start the background job queue."""
+ """Initialize and start the background job queue with orphan recovery."""
try:
from src.services.job_queue import job_queue
+
+ # Initialize job queue with app context
+ job_queue.init_app(app)
+
+ # Recover any jobs that were processing when the app crashed
+ job_queue.recover_orphaned_jobs()
+
+ # Start worker threads
job_queue.start()
- app.logger.info("Job queue started with 2 workers")
+
+ # Get queue status
+ status = job_queue.get_queue_status()
+ app.logger.info(f"Job queue started with {status['num_workers']} workers, {status['queued_jobs']} queued jobs")
except Exception as e:
- app.logger.error(f"Failed to start job queue: {e}")
+ app.logger.error(f"Failed to start job queue: {e}", exc_info=True)
def run_startup_tasks(app):
diff --git a/src/models/__init__.py b/src/models/__init__.py
index 856542df..e7cbe38a 100644
--- a/src/models/__init__.py
+++ b/src/models/__init__.py
@@ -25,6 +25,7 @@ from .inquire import InquireSession
from .system import SystemSetting
from .audit import ShareAuditLog
from .push_subscription import PushSubscription
+from .processing_job import ProcessingJob
# Export all models
__all__ = [
@@ -53,4 +54,5 @@ __all__ = [
'InquireSession',
'SystemSetting',
'PushSubscription',
+ 'ProcessingJob',
]
diff --git a/src/models/processing_job.py b/src/models/processing_job.py
new file mode 100644
index 00000000..8c487e8f
--- /dev/null
+++ b/src/models/processing_job.py
@@ -0,0 +1,59 @@
+"""
+ProcessingJob database model for persistent job queue.
+
+This model stores background processing jobs in the database to ensure
+they survive application restarts and support fair scheduling across users.
+"""
+
+from datetime import datetime
+from src.database import db
+
+
+class ProcessingJob(db.Model):
+ """Database model for tracking background processing jobs."""
+
+ __tablename__ = 'processing_job'
+
+ id = db.Column(db.Integer, primary_key=True)
+ user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False, index=True)
+ recording_id = db.Column(db.Integer, db.ForeignKey('recording.id'), nullable=False, index=True)
+
+ # Job type: transcribe, summarize, reprocess_transcription, reprocess_summary
+ job_type = db.Column(db.String(50), nullable=False)
+
+ # Status: queued, processing, completed, failed
+ status = db.Column(db.String(20), default='queued', nullable=False, index=True)
+
+ # JSON blob for job-specific parameters (language, min_speakers, custom_prompt, etc.)
+ params = db.Column(db.Text, nullable=True)
+
+ # Error tracking
+ error_message = db.Column(db.Text, nullable=True)
+ retry_count = db.Column(db.Integer, default=0, nullable=False)
+
+ # Timestamps
+ created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False, index=True)
+ started_at = db.Column(db.DateTime, nullable=True)
+ completed_at = db.Column(db.DateTime, nullable=True)
+
+ # Relationships
+ user = db.relationship('User', backref=db.backref('processing_jobs', lazy='dynamic'))
+ recording = db.relationship('Recording', backref=db.backref('processing_jobs', lazy='dynamic'))
+
+ def __repr__(self):
+ return f'<ProcessingJob {self.id} type={self.job_type} status={self.status}>'
+
+ def to_dict(self):
+ """Convert job to dictionary for API responses."""
+ return {
+ 'id': self.id,
+ 'user_id': self.user_id,
+ 'recording_id': self.recording_id,
+ 'job_type': self.job_type,
+ 'status': self.status,
+ 'retry_count': self.retry_count,
+ 'created_at': self.created_at.isoformat() if self.created_at else None,
+ 'started_at': self.started_at.isoformat() if self.started_at else None,
+ 'completed_at': self.completed_at.isoformat() if self.completed_at else None,
+ 'error_message': self.error_message
+ }
diff --git a/src/services/job_queue.py b/src/services/job_queue.py
index 2063fcb1..091bb9db 100644
--- a/src/services/job_queue.py
+++ b/src/services/job_queue.py
@@ -1,80 +1,77 @@
"""
-Simple job queue for background processing tasks.
-Ensures jobs run sequentially or with limited concurrency to prevent
-overwhelming external services like ASR endpoints.
+Fair database-backed job queue for background processing tasks.
+
+This queue ensures:
+- Jobs persist across application restarts
+- Fair round-robin scheduling between users
+- Limited concurrency to prevent overwhelming external services
+- Automatic recovery of orphaned jobs
"""
+import os
+import json
import threading
-import queue
+import time
import logging
from datetime import datetime
-from typing import Callable, Any, Dict, Optional
-from dataclasses import dataclass, field
-from enum import Enum
+from typing import Optional, Dict, Any, Callable
+from contextlib import contextmanager
logger = logging.getLogger(__name__)
+# Configuration
+MAX_WORKERS = int(os.environ.get('JOB_QUEUE_WORKERS', '2'))
+MAX_RETRIES = int(os.environ.get('JOB_MAX_RETRIES', '3'))
+POLL_INTERVAL = 1.0 # seconds between checking for new jobs
-class JobStatus(Enum):
- QUEUED = "queued"
- RUNNING = "running"
- COMPLETED = "completed"
- FAILED = "failed"
-
-
-@dataclass
-class Job:
- """Represents a background processing job."""
- id: str
- func: Callable
- args: tuple = field(default_factory=tuple)
- kwargs: dict = field(default_factory=dict)
- status: JobStatus = JobStatus.QUEUED
- created_at: datetime = field(default_factory=datetime.utcnow)
- started_at: Optional[datetime] = None
- completed_at: Optional[datetime] = None
- error: Optional[str] = None
- recording_id: Optional[int] = None # For tracking which recording this job is for
-
-class JobQueue:
+class FairJobQueue:
"""
- A simple job queue that processes jobs with limited concurrency.
+ A database-backed job queue with fair scheduling across users.
- Features:
- - Configurable max concurrent workers
- - Job status tracking
- - Prevents duplicate jobs for the same recording
+ Uses round-robin scheduling to ensure all users get fair processing time,
+ preventing one user from monopolizing the queue.
"""
_instance = None
_lock = threading.Lock()
- def __new__(cls, max_workers: int = 2):
+ def __new__(cls, num_workers: int = None):
"""Singleton pattern to ensure only one queue exists."""
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance._initialized = False
- cls._instance._max_workers_init = max_workers
+ cls._instance._num_workers_init = num_workers or MAX_WORKERS
return cls._instance
- def __init__(self, max_workers: int = 2):
+ def __init__(self, num_workers: int = None):
"""Initialize the job queue."""
if self._initialized:
return
- self._queue = queue.Queue()
- self._jobs: Dict[str, Job] = {}
- self._recording_jobs: Dict[int, str] = {} # Maps recording_id to job_id
- self._max_workers = getattr(self, '_max_workers_init', max_workers)
- self._workers: list = []
+ self._num_workers = getattr(self, '_num_workers_init', num_workers or MAX_WORKERS)
+ self._workers = []
self._running = False
- self._jobs_lock = threading.Lock()
+ self._app = None
+ self._last_user_id = None # For round-robin tracking
self._initialized = True
- logger.info(f"JobQueue initialized with max_workers={self._max_workers}")
+ logger.info(f"FairJobQueue initialized with {self._num_workers} workers")
+
+ def init_app(self, app):
+ """Initialize with Flask app for context management."""
+ self._app = app
+
+ @contextmanager
+ def _app_context(self):
+ """Get application context for database operations."""
+ if self._app:
+ with self._app.app_context():
+ yield
+ else:
+ yield
def start(self):
"""Start the worker threads."""
@@ -82,202 +79,365 @@ class JobQueue:
return
self._running = True
- for i in range(self._max_workers):
+ for i in range(self._num_workers):
worker = threading.Thread(
target=self._worker_loop,
- name=f"JobQueueWorker-{i}",
+ name=f"FairJobQueueWorker-{i}",
daemon=True
)
worker.start()
self._workers.append(worker)
- logger.info(f"Started {self._max_workers} job queue workers")
+ logger.info(f"Started {self._num_workers} fair job queue workers")
def stop(self):
- """Stop the worker threads."""
+ """Stop the worker threads gracefully."""
self._running = False
- # Put None items to unblock workers
- for _ in self._workers:
- self._queue.put(None)
for worker in self._workers:
worker.join(timeout=5)
self._workers.clear()
- logger.info("Job queue workers stopped")
+ logger.info("Fair job queue workers stopped")
def _worker_loop(self):
- """Main worker loop that processes jobs from the queue."""
+ """Main worker loop that processes jobs from the database."""
while self._running:
try:
- job = self._queue.get(timeout=0.1) # Check every 100ms for faster pickup
- if job is None:
- continue
+ job = self._claim_next_job()
+ if job:
+ self._process_job(job)
+ else:
+ # No jobs available, sleep briefly
+ time.sleep(POLL_INTERVAL)
+ except Exception as e:
+ logger.error(f"Worker error: {e}", exc_info=True)
+ time.sleep(POLL_INTERVAL)
- self._process_job(job)
- self._queue.task_done()
+ def _claim_next_job(self):
+ """
+ Claim the next job using fair round-robin scheduling.
- except queue.Empty:
- continue
- except Exception as e:
- logger.error(f"Worker error: {e}")
+ Returns the claimed job or None if no jobs available.
+ """
+ with self._app_context():
+ from src.database import db
+ from src.models import ProcessingJob
- def _process_job(self, job: Job):
- """Process a single job."""
- wait_time = (datetime.utcnow() - job.created_at).total_seconds()
- logger.info(f"Starting job {job.id} for recording {job.recording_id} (waited {wait_time:.2f}s in queue)")
+ try:
+ # Get list of users with queued jobs, ordered by oldest job first
+ users_with_jobs = db.session.query(
+ ProcessingJob.user_id
+ ).filter(
+ ProcessingJob.status == 'queued'
+ ).group_by(
+ ProcessingJob.user_id
+ ).order_by(
+ db.func.min(ProcessingJob.created_at)
+ ).all()
+
+ if not users_with_jobs:
+ return None
+
+ user_ids = [u[0] for u in users_with_jobs]
+
+ # Round-robin: pick next user after last processed
+ next_user_id = None
+ if self._last_user_id is not None and self._last_user_id in user_ids:
+ idx = user_ids.index(self._last_user_id)
+ next_user_id = user_ids[(idx + 1) % len(user_ids)]
+ else:
+ next_user_id = user_ids[0]
+
+ # Get oldest queued job for this user
+ job = ProcessingJob.query.filter(
+ ProcessingJob.user_id == next_user_id,
+ ProcessingJob.status == 'queued'
+ ).order_by(
+ ProcessingJob.created_at
+ ).with_for_update(skip_locked=True).first()
+
+ if job:
+ # Claim the job
+ job.status = 'processing'
+ job.started_at = datetime.utcnow()
+ db.session.commit()
+ self._last_user_id = next_user_id
+
+ wait_time = (datetime.utcnow() - job.created_at).total_seconds()
+ logger.info(f"Claimed job {job.id} (type={job.job_type}) for user {job.user_id}, recording {job.recording_id} (waited {wait_time:.1f}s)")
+ return job
+
+ return None
- with self._jobs_lock:
- job.status = JobStatus.RUNNING
- job.started_at = datetime.utcnow()
+ except Exception as e:
+ logger.error(f"Error claiming job: {e}", exc_info=True)
+ db.session.rollback()
+ return None
- try:
- job.func(*job.args, **job.kwargs)
+ def _process_job(self, job):
+ """Process a single job by dispatching to the appropriate task function."""
+ with self._app_context():
+ from src.database import db
+ from src.models import ProcessingJob, Recording
+ from flask import current_app
- with self._jobs_lock:
- job.status = JobStatus.COMPLETED
+ try:
+ # Parse job parameters
+ params = json.loads(job.params) if job.params else {}
+
+ # Get recording
+ recording = db.session.get(Recording, job.recording_id)
+ if not recording:
+ raise ValueError(f"Recording {job.recording_id} not found")
+
+ # Dispatch based on job type
+ if job.job_type == 'transcribe':
+ self._run_transcription(job, recording, params)
+ elif job.job_type == 'summarize':
+ self._run_summarization(job, recording, params)
+ elif job.job_type == 'reprocess_transcription':
+ self._run_reprocess_transcription(job, recording, params)
+ elif job.job_type == 'reprocess_summary':
+ self._run_reprocess_summary(job, recording, params)
+ else:
+ raise ValueError(f"Unknown job type: {job.job_type}")
+
+ # Mark as completed
+ job.status = 'completed'
job.completed_at = datetime.utcnow()
+ db.session.commit()
- logger.info(f"Job {job.id} completed successfully")
+ logger.info(f"Job {job.id} completed successfully")
- except Exception as e:
- logger.error(f"Job {job.id} failed: {e}")
+ except Exception as e:
+ logger.error(f"Job {job.id} failed: {e}", exc_info=True)
+
+ # Update job with error
+ job.error_message = str(e)
+ job.retry_count += 1
+
+ if job.retry_count < MAX_RETRIES:
+ # Re-queue for retry
+ job.status = 'queued'
+ job.started_at = None
+ logger.info(f"Job {job.id} re-queued for retry ({job.retry_count}/{MAX_RETRIES})")
+ else:
+ job.status = 'failed'
+ job.completed_at = datetime.utcnow()
+ # Update recording status to FAILED
+ recording = db.session.get(Recording, job.recording_id)
+ if recording:
+ recording.status = 'FAILED'
+ recording.error_message = str(e)
+ logger.error(f"Job {job.id} failed permanently after {MAX_RETRIES} retries")
+
+ db.session.commit()
+
+ def _run_transcription(self, job, recording, params):
+ """Run transcription task. Status updates handled by task function."""
+ from src.tasks.processing import transcribe_audio_task
+ from flask import current_app
+
+ filepath = recording.audio_path
+ filename_for_asr = recording.original_filename or os.path.basename(filepath)
+
+ transcribe_audio_task(
+ current_app._get_current_object().app_context(),
+ recording.id,
+ filepath,
+ filename_for_asr,
+ time.time(),
+ language=params.get('language'),
+ min_speakers=params.get('min_speakers'),
+ max_speakers=params.get('max_speakers'),
+ tag_id=params.get('tag_id')
+ )
- with self._jobs_lock:
- job.status = JobStatus.FAILED
- job.completed_at = datetime.utcnow()
- job.error = str(e)
+ def _run_summarization(self, job, recording, params):
+ """Run summarization-only task. Status updates handled by task function."""
+ from src.tasks.processing import generate_summary_only_task
+ from flask import current_app
- finally:
- # Clean up recording job mapping
- with self._jobs_lock:
- if job.recording_id and job.recording_id in self._recording_jobs:
- del self._recording_jobs[job.recording_id]
+ generate_summary_only_task(
+ current_app._get_current_object().app_context(),
+ recording.id,
+ custom_prompt_override=params.get('custom_prompt'),
+ user_id=params.get('user_id')
+ )
+
+ def _run_reprocess_transcription(self, job, recording, params):
+ """Run transcription reprocessing task. Status updates handled by task function."""
+ from src.tasks.processing import transcribe_audio_task
+ from flask import current_app
+
+ filepath = recording.audio_path
+ filename_for_asr = recording.original_filename or os.path.basename(filepath)
+
+ transcribe_audio_task(
+ current_app._get_current_object().app_context(),
+ recording.id,
+ filepath,
+ filename_for_asr,
+ time.time(),
+ language=params.get('language'),
+ min_speakers=params.get('min_speakers'),
+ max_speakers=params.get('max_speakers'),
+ tag_id=params.get('tag_id')
+ )
+
+ def _run_reprocess_summary(self, job, recording, params):
+ """Run summary reprocessing task. Status updates handled by task function."""
+ from src.tasks.processing import generate_summary_only_task
+ from flask import current_app
+
+ generate_summary_only_task(
+ current_app._get_current_object().app_context(),
+ recording.id,
+ custom_prompt_override=params.get('custom_prompt'),
+ user_id=params.get('user_id')
+ )
def enqueue(
self,
- func: Callable,
- args: tuple = (),
- kwargs: dict = None,
- job_id: str = None,
- recording_id: int = None
- ) -> Job:
+ user_id: int,
+ recording_id: int,
+ job_type: str,
+ params: Dict[str, Any] = None
+ ) -> int:
"""
- Add a job to the queue.
+ Add a job to the database queue.
Args:
- func: The function to call
- args: Positional arguments for the function
- kwargs: Keyword arguments for the function
- job_id: Optional custom job ID
- recording_id: Optional recording ID to prevent duplicate jobs
+ user_id: ID of the user who owns this job
+ recording_id: ID of the recording to process
+ job_type: Type of job (transcribe, summarize, reprocess_transcription, reprocess_summary)
+ params: Optional parameters for the job
Returns:
- The created Job object
+ The created job ID
"""
- # Auto-start workers if not running
- if not self._running:
- self.start()
-
- if kwargs is None:
- kwargs = {}
-
- # Generate job ID if not provided
- if job_id is None:
- job_id = f"job_{datetime.utcnow().strftime('%Y%m%d_%H%M%S_%f')}"
-
- # Check for existing job for this recording
- with self._jobs_lock:
- if recording_id and recording_id in self._recording_jobs:
- existing_job_id = self._recording_jobs[recording_id]
- existing_job = self._jobs.get(existing_job_id)
- if existing_job and existing_job.status in [JobStatus.QUEUED, JobStatus.RUNNING]:
- logger.warning(f"Job already exists for recording {recording_id}: {existing_job_id}")
- return existing_job
-
- # Create the job
- job = Job(
- id=job_id,
- func=func,
- args=args,
- kwargs=kwargs,
- recording_id=recording_id
- )
+ with self._app_context():
+ from src.database import db
+ from src.models import ProcessingJob, Recording
+
+ # Check for existing active job for this recording
+ existing = ProcessingJob.query.filter(
+ ProcessingJob.recording_id == recording_id,
+ ProcessingJob.status.in_(['queued', 'processing'])
+ ).first()
+
+ if existing:
+ logger.warning(f"Job already exists for recording {recording_id}: {existing.id}")
+ return existing.id
+
+ # Create new job
+ job = ProcessingJob(
+ user_id=user_id,
+ recording_id=recording_id,
+ job_type=job_type,
+ params=json.dumps(params) if params else None
+ )
+ db.session.add(job)
- with self._jobs_lock:
- self._jobs[job_id] = job
- if recording_id:
- self._recording_jobs[recording_id] = job_id
+ # Update recording status to QUEUED
+ recording = db.session.get(Recording, recording_id)
+ if recording:
+ recording.status = 'QUEUED'
- # Add to queue
- self._queue.put(job)
+ db.session.commit()
- logger.info(f"Enqueued job {job_id} for recording {recording_id}, queue size: {self._queue.qsize()}")
+ # Auto-start workers if not running
+ if not self._running:
+ self.start()
- return job
+ logger.info(f"Enqueued job {job.id} (type={job_type}) for user {user_id}, recording {recording_id}")
+ return job.id
- def get_job(self, job_id: str) -> Optional[Job]:
- """Get a job by ID."""
- with self._jobs_lock:
- return self._jobs.get(job_id)
+ def recover_orphaned_jobs(self):
+ """
+ Recover jobs that were processing when the app crashed.
+ Call this on startup to reset orphaned jobs back to queued.
+ """
+ with self._app_context():
+ from src.database import db
+ from src.models import ProcessingJob
- def get_job_for_recording(self, recording_id: int) -> Optional[Job]:
- """Get the active job for a recording."""
- with self._jobs_lock:
- job_id = self._recording_jobs.get(recording_id)
- if job_id:
- return self._jobs.get(job_id)
- return None
+ orphaned = ProcessingJob.query.filter(
+ ProcessingJob.status == 'processing'
+ ).all()
+
+ for job in orphaned:
+ job.status = 'queued'
+ job.started_at = None
+ logger.info(f"Recovered orphaned job {job.id} for recording {job.recording_id}")
+
+ if orphaned:
+ db.session.commit()
+ logger.info(f"Recovered {len(orphaned)} orphaned jobs")
def get_queue_status(self) -> Dict[str, Any]:
"""Get the current queue status."""
- with self._jobs_lock:
- queued = sum(1 for j in self._jobs.values() if j.status == JobStatus.QUEUED)
- running = sum(1 for j in self._jobs.values() if j.status == JobStatus.RUNNING)
-
- return {
- "queue_size": self._queue.qsize(),
- "queued_jobs": queued,
- "running_jobs": running,
- "max_workers": self._max_workers,
- "is_running": self._running
- }
+ with self._app_context():
+ from src.models import ProcessingJob
+
+ queued = ProcessingJob.query.filter_by(status='queued').count()
+ processing = ProcessingJob.query.filter_by(status='processing').count()
+
+ return {
+ "queued_jobs": queued,
+ "processing_jobs": processing,
+ "num_workers": self._num_workers,
+ "is_running": self._running
+ }
def get_position_in_queue(self, recording_id: int) -> Optional[int]:
"""Get the position of a recording's job in the queue (1-indexed)."""
- with self._jobs_lock:
- job_id = self._recording_jobs.get(recording_id)
- if not job_id:
- return None
+ with self._app_context():
+ from src.models import ProcessingJob
- job = self._jobs.get(job_id)
- if not job or job.status != JobStatus.QUEUED:
+ job = ProcessingJob.query.filter(
+ ProcessingJob.recording_id == recording_id,
+ ProcessingJob.status == 'queued'
+ ).first()
+
+ if not job:
return None
- # Count queued jobs created before this one
- position = 1
- for j in self._jobs.values():
- if j.status == JobStatus.QUEUED and j.created_at < job.created_at:
- position += 1
+ # Count jobs created before this one
+ position = ProcessingJob.query.filter(
+ ProcessingJob.status == 'queued',
+ ProcessingJob.created_at < job.created_at
+ ).count() + 1
return position
+ def get_job_for_recording(self, recording_id: int):
+ """Get the active job for a recording."""
+ with self._app_context():
+ from src.models import ProcessingJob
+
+ return ProcessingJob.query.filter(
+ ProcessingJob.recording_id == recording_id,
+ ProcessingJob.status.in_(['queued', 'processing'])
+ ).first()
+
def cleanup_old_jobs(self, max_age_hours: int = 24):
"""Remove completed/failed jobs older than max_age_hours."""
- from datetime import timedelta
- cutoff = datetime.utcnow() - timedelta(hours=max_age_hours)
+ with self._app_context():
+ from src.database import db
+ from src.models import ProcessingJob
+ from datetime import timedelta
- with self._jobs_lock:
- to_remove = [
- job_id for job_id, job in self._jobs.items()
- if job.status in [JobStatus.COMPLETED, JobStatus.FAILED]
- and job.completed_at and job.completed_at < cutoff
- ]
+ cutoff = datetime.utcnow() - timedelta(hours=max_age_hours)
- for job_id in to_remove:
- del self._jobs[job_id]
+ deleted = ProcessingJob.query.filter(
+ ProcessingJob.status.in_(['completed', 'failed']),
+ ProcessingJob.completed_at < cutoff
+ ).delete(synchronize_session=False)
- if to_remove:
- logger.info(f"Cleaned up {len(to_remove)} old jobs")
+ if deleted:
+ db.session.commit()
+ logger.info(f"Cleaned up {deleted} old jobs")
# Global job queue instance
-job_queue = JobQueue(max_workers=2)
+job_queue = FairJobQueue()