Skip to content

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

Python

Worker ends its DB transaction before long ASR and LLM calls (#405); an empty transcript fails the recording instead of completing it, and Mossland no longer reports an empty finished task as success (#406)

Murtaza Nasir77b135c10356
diff --git a/src/services/transcription/connectors/mossland.py b/src/services/transcription/connectors/mossland.py
index d0659262..e6558fc3 100644
--- a/src/services/transcription/connectors/mossland.py
+++ b/src/services/transcription/connectors/mossland.py
@@ -266,10 +266,12 @@ class MosslandTranscriptionConnector(BaseTranscriptionConnector):
payload = response.json()
status = (payload.get("status") or "").upper()
if status in ("SUCCESS", "COMPLETED"):
- return self._result(
- payload.get("text") or "", self._segments(payload.get("segments") or []),
- model, payload,
- )
+ segments = self._segments(payload.get("segments") or [])
+ text = (payload.get("text") or "").strip()
+ if not text and not segments:
+ # A finished task with nothing in it is not a transcript (#406).
+ raise TranscriptionError(f"Mossland task {task_id} finished without any transcript text")
+ return self._result(text, segments, model, payload)
if status in ("FAILED", "ERROR"):
detail = payload.get("error") or payload.get("message") or status
if isinstance(detail, dict):
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index 4e6803bd..05ca4b8e 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -299,6 +299,61 @@ ENABLE_INQUIRE_MODE = os.environ.get('ENABLE_INQUIRE_MODE', 'false').lower() ==
# not at module level (matching original pre-refactor behavior)
+EMPTY_TRANSCRIPT_MESSAGE = (
+ "The transcription service returned no text. The recording may contain no "
+ "speech, or the service failed without reporting an error."
+)
+
+
+def _has_transcript_content(transcription):
+ """True when a stored transcript holds at least some text (#406).
+
+ Accepts the plain-text form and the JSON segment list the diarized form
+ is stored as.
+ """
+ if not transcription:
+ return False
+ if not isinstance(transcription, str):
+ return True
+ text = transcription.strip()
+ if not text:
+ return False
+ if text.startswith('['):
+ try:
+ segments = json.loads(text)
+ except ValueError:
+ return True
+ if isinstance(segments, list):
+ return any(
+ isinstance(seg, dict) and str(seg.get('sentence') or seg.get('text') or '').strip()
+ for seg in segments
+ )
+ return True
+
+
+def _end_transaction_before_external_call(*instances):
+ """End the open database transaction before a long outside call (#405).
+
+ Commits pending work, reloads the given instances, then ends that short
+ read transaction as well, so no connection sits idle in a transaction
+ while a transcription or LLM call runs. PostgreSQL's
+ idle_in_transaction_session_timeout would otherwise drop the worker's
+ connection during a long job. The instances keep their loaded values, and
+ anything changed on them afterwards is written by the next commit.
+ """
+ session = db.session()
+ session.commit()
+ for instance in instances:
+ if instance is not None:
+ session.refresh(instance)
+ previous = session.expire_on_commit
+ session.expire_on_commit = False
+ try:
+ session.commit()
+ finally:
+ session.expire_on_commit = previous
+
+
def generate_title_task(app_context, recording_id, will_auto_summarize=False):
"""Generates only a title for a recording based on transcription.
@@ -529,6 +584,7 @@ Title:"""
system_message_content += f" Ensure your response is in {user_output_language}."
try:
+ _end_transaction_before_external_call(recording)
completion = call_llm_completion(
messages=[
{"role": "system", "content": system_message_content},
@@ -856,6 +912,7 @@ Summarization Instructions:
current_app.logger.debug(f"=== END SUMMARIZATION DEBUG for recording {recording_id} ===")
try:
+ _end_transaction_before_external_call(recording)
completion = call_llm_completion(
messages=[
{"role": "system", "content": system_message_content},
@@ -1125,6 +1182,7 @@ You must respond with valid JSON format only."""
if user_output_language:
system_message_content += f"\n\nLanguage Requirement: You MUST generate ALL event titles, descriptions, and locations in {user_output_language}. This is mandatory."
+ _end_transaction_before_external_call(recording)
completion = call_llm_completion(
messages=[
{"role": "system", "content": system_message_content},
@@ -2059,6 +2117,7 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file
# Use chunking for large files
file_size_mb = os.path.getsize(actual_filepath) / (1024 * 1024)
current_app.logger.info(f"File {actual_filepath} is large ({file_size_mb:.1f}MB), using chunking for transcription")
+ _end_transaction_before_external_call(recording)
chunk_result = transcribe_chunks_with_connector(
connector, actual_filepath, actual_filename, actual_content_type, language,
diarize=should_diarize, # Pass diarization setting for speaker reference tracking
@@ -2118,6 +2177,7 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file
should_diarize,
language,
)
+ _end_transaction_before_external_call(recording)
try:
response = connector.transcribe(request)
finally:
@@ -2241,6 +2301,18 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file
except OSError:
pass # Best effort cleanup
+ # A transcription that came back empty is a failure, not a finished
+ # recording (#406): marked COMPLETED it would pass unnoticed in a
+ # batch. Not retried, since silence would come back empty again.
+ if not _has_transcript_content(recording.transcription):
+ current_app.logger.warning(
+ f"Transcription for recording {recording_id} returned no text; marking it failed")
+ recording.transcription = None
+ recording.status = 'FAILED'
+ recording.error_message = EMPTY_TRANSCRIPT_MESSAGE
+ db.session.commit()
+ return
+
# Calculate and save transcription duration
transcription_end_time = time.time()
recording.transcription_duration_seconds = int(transcription_end_time - transcription_start_time)
@@ -2677,6 +2749,10 @@ def transcribe_incognito(filepath, original_filename, language=None, min_speaker
result['transcription'] = response.text
result['processing_time_seconds'] = int(time.time() - start_time)
+ if not _has_transcript_content(result['transcription']):
+ result['transcription'] = None
+ result['error'] = EMPTY_TRANSCRIPT_MESSAGE
+ return result
current_app.logger.info(f"[Incognito] Transcription completed in {result['processing_time_seconds']}s")
# Generate a title if we have transcription
diff --git a/tests/test_worker_transactions.py b/tests/test_worker_transactions.py
new file mode 100644
index 00000000..6269f870
--- /dev/null
+++ b/tests/test_worker_transactions.py
@@ -0,0 +1,203 @@
+"""Worker transactions and empty transcripts (#405, #406).
+
+#405: the transcription worker must not hold a database transaction open
+while it waits on the ASR service or the LLM; PostgreSQL's
+idle_in_transaction_session_timeout would drop the connection on long jobs.
+
+#406: a transcription that comes back empty is a failure, never COMPLETED.
+
+SHARED-DB: every test uses its own user and removes its recordings.
+"""
+import json
+import os
+import sys
+import time
+import uuid
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from src.app import app, db
+from src.models import Recording, User
+import src.tasks.processing as proc
+from src.services.transcription.connectors.mossland import MosslandTranscriptionConnector as MosslandConnector
+from src.services.transcription.exceptions import TranscriptionError
+
+_created = []
+
+
+def ctx():
+ with app.app_context():
+ yield
+ db.session.rollback()
+ for rid in _created:
+ Recording.query.filter_by(id=rid).delete()
+ db.session.commit()
+ _created.clear()
+
+
+def _recording():
+ s = uuid.uuid4().hex[:8]
+ user = User(username=f"wt_{s}", email=f"wt_{s}@local.test", password="x")
+ db.session.add(user)
+ db.session.commit()
+ rec = Recording(user_id=user.id, original_filename="w.mp3", audio_path="local://w.mp3",
+ status="PENDING", title="wt")
+ db.session.add(rec)
+ db.session.commit()
+ _created.append(rec.id)
+ return rec
+
+
+def _connector(transcribe):
+ connector = MagicMock()
+ connector.PROVIDER_NAME = "test-connector"
+ connector.supports_diarization = False
+ connector.default_diarize = False
+ specs = MagicMock()
+ specs.max_duration_seconds = 1800
+ specs.handles_chunking_internally = False
+ specs.recommended_chunk_seconds = 600
+ specs.unsupported_codecs = []
+ connector.specifications = specs
+ connector.transcribe.side_effect = transcribe
+ return connector
+
+
+def _response(text, segments=None):
+ response = MagicMock()
+ response.text = text
+ response.segments = segments
+ response.speakers = None
+ response.speaker_embeddings = None
+ response.language = "en"
+ response.has_diarization.return_value = bool(segments)
+ return response
+
+
+def _run(rid, connector):
+ path = os.path.join(app.config["UPLOAD_FOLDER"], f"wt_{rid}.mp3")
+ with open(path, "wb") as f:
+ f.write(b"\x00" * 1024)
+ conv = MagicMock()
+ conv.was_converted = False
+ with patch("src.services.transcription.get_connector", return_value=connector), \
+ patch.object(proc, "is_video_file", return_value=False), \
+ patch.object(proc, "convert_if_needed", return_value=conv), \
+ patch.object(proc, "client", MagicMock()), \
+ patch.object(proc, "ENABLE_INQUIRE_MODE", False), \
+ patch.object(proc, "generate_title_task") as title, \
+ patch.object(proc, "generate_summary_only_task") as summary, \
+ patch.object(proc, "chunking_service") as chunking:
+ chunking.needs_chunking.return_value = False
+ chunking.get_audio_duration.return_value = 60.0
+ proc.transcribe_with_connector(app.app_context(), rid, path, "w.mp3", time.time(),
+ mime_type="audio/mpeg")
+ return title, summary
+
+
+# ------------------------------------------------------------ #405
+
+def test_no_transaction_is_open_during_the_asr_call(ctx):
+ rec = _recording()
+ seen = {}
+
+ def transcribe(request):
+ seen["in_transaction"] = db.session().in_transaction()
+ return _response("Some words were said.")
+
+ _run(rec.id, _connector(transcribe))
+ assert seen == {"in_transaction": False}
+ db.session.expire_all()
+ out = db.session.get(Recording, rec.id)
+ assert out.transcription == "Some words were said."
+ assert out.transcription_duration_seconds is not None
+
+
+def test_no_transaction_is_open_during_the_summary_llm_call(ctx):
+ rec = _recording()
+ rec.transcription = "word " * 60
+ db.session.commit()
+ seen = {}
+
+ def fake_llm(*args, **kwargs):
+ seen["in_transaction"] = db.session().in_transaction()
+ completion = MagicMock()
+ completion.choices = [MagicMock()]
+ completion.choices[0].message.content = "A summary."
+ completion.choices[0].message.reasoning = None
+ return completion
+
+ with patch.object(proc, "client", MagicMock()), \
+ patch.object(proc, "call_llm_completion", side_effect=fake_llm), \
+ patch.object(proc, "ENABLE_INQUIRE_MODE", False):
+ proc.generate_summary_only_task(app.app_context(), rec.id)
+ assert seen.get("in_transaction") is False
+ db.session.expire_all()
+ assert db.session.get(Recording, rec.id).summary
+
+
+def test_ending_the_transaction_keeps_loaded_values_and_later_writes(ctx):
+ rec = _recording()
+ rec.title = "before"
+ proc._end_transaction_before_external_call(rec)
+ assert not db.session().in_transaction()
+ assert rec.title == "before"
+ rec.title = "after"
+ db.session.commit()
+ db.session.expire_all()
+ assert db.session.get(Recording, rec.id).title == "after"
+
+
+# ------------------------------------------------------------ #406
+
[email protected]("text,segments", [("", None), (" ", None), (None, None)])
+def test_an_empty_transcript_fails_the_recording(ctx, text, segments):
+ rec = _recording()
+ title, summary = _run(rec.id, _connector(lambda request: _response(text, segments)))
+ db.session.expire_all()
+ out = db.session.get(Recording, rec.id)
+ assert out.status == "FAILED"
+ assert out.error_message == proc.EMPTY_TRANSCRIPT_MESSAGE
+ assert not out.transcription
+ title.assert_not_called()
+ summary.assert_not_called()
+
+
+def test_a_real_transcript_still_completes_the_pipeline(ctx):
+ rec = _recording()
+ title, summary = _run(rec.id, _connector(lambda request: _response("Hello there.")))
+ db.session.expire_all()
+ assert db.session.get(Recording, rec.id).status != "FAILED"
+ title.assert_called_once()
+
+
[email protected]("value,expected", [
+ (None, False), ("", False), (" \n", False), ("hello", True),
+ (json.dumps([{"speaker": "A", "sentence": ""}]), False),
+ (json.dumps([{"speaker": "A", "sentence": " hi "}]), True),
+ ("[not json", True),
+])
+def test_has_transcript_content(value, expected):
+ assert proc._has_transcript_content(value) is expected
+
+
+def test_mossland_task_that_finishes_empty_is_an_error():
+ connector = MosslandConnector.__new__(MosslandConnector)
+ connector.poll_timeout = 5
+ connector.poll_interval = 0
+ client = MagicMock()
+ response = MagicMock()
+ response.status_code = 200
+ response.json.return_value = {"status": "SUCCESS", "text": "", "segments": []}
+ client.get.return_value = response
+ with pytest.raises(TranscriptionError, match="without any transcript"):
+ connector._poll_task(client, "task-1", "model")
+
+ response.json.return_value = {"status": "COMPLETED", "text": "",
+ "segments": [{"text": "Hello", "start": 0, "end": 1}]}
+ result = connector._poll_task(client, "task-2", "model")
+ assert result.text == "Hello"