Skip to content

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

Python

fix: let an ingest report itself alive instead of inferring it from a clock

François Catuhebc65ecdc11b7
diff --git a/docs/admin-guide/recording-sessions.md b/docs/admin-guide/recording-sessions.md
index 2fe3dcf9..61f4ee9f 100644
--- a/docs/admin-guide/recording-sessions.md
+++ b/docs/admin-guide/recording-sessions.md
@@ -132,7 +132,7 @@ Environment variables, all optional:
| `RECORDING_SESSION_MAX_CHUNK_BYTES` | `16777216` (16 MB) | Per-chunk upload cap. Generous; MediaRecorder chunks are typically <1 MB. |
| `RECORDING_SESSION_ALLOWED_MIME_TYPES` | `audio/webm,audio/ogg,audio/mp4,audio/mpeg,audio/wav,audio/x-m4a,video/webm,video/mp4` | Comma-separated whitelist. The video types carry the optional tab/window/screen video capture. |
| `RECORDING_SESSION_CLEANUP_INTERVAL_SECONDS` | `3600` | How often the background thread sweeps expired sessions. Set to `0` to disable. |
-| `RECORDING_SESSION_INGEST_CEILING_SECONDS` | `900` | How long a sliced upload's in-request ingest can possibly still be running. Past this, a session left `finalizing` is taken over by the next finalize. Keep it above the WSGI request timeout (gunicorn ships with `--timeout 600`), never below, or a live ingest could be claimed twice. |
+| `RECORDING_SESSION_INGEST_HEARTBEAT_SECONDS` | `30` | How often a sliced upload's in-request ingest stamps its session to say it is alive. Three missed stamps mark the session abandoned, and the next finalize takes it over. Nothing else can tell: under gunicorn's `gthread` worker, which is what Speakr ships, `--timeout` bounds the accept loop's silence rather than a request's duration, so a long ingest is never aborted and its session's age says nothing about whether anyone is still working on it. |
| `RECORDING_MAX_HOURS` | `8` | Absolute ceiling on a single recording. Stops the recorder automatically at this duration regardless of size; a toast warns the user at 80% of the ceiling. |
| `RECORDING_VIDEO_KBPS` | `2500` | Video bitrate cap (kbps) for the opt-in tab/window/screen video capture. At the default, an hour of capture is roughly 1 GB. |
@@ -250,14 +250,19 @@ on the server, or discard them.
- **Deploys interrupt sliced uploads that are ingesting.** A sliced
upload ingests inside the finalize request, so recreating the
container mid-ingest loses that work and leaves the session
- `finalizing` with nobody running it. Nothing is lost and nothing
- leaks: the slices stay on disk and the user's retry takes the session
- over once its claim is older than
- `RECORDING_SESSION_INGEST_CEILING_SECONDS`, re-ingesting from the
- slices already delivered. But a retry *before* that point waits ten
- minutes and then fails, so a deploy is best timed when nothing is
- uploading. Slice POSTs and recorder sessions are unaffected: those
- requests are short, and their retries resume.
+ `finalizing` with nobody running it. The slices stay on disk, the
+ stamping stops with the container, and about a minute and a half
+ later the user's retry takes the session over and re-ingests from the
+ slices already delivered. A retry inside that window is told the
+ session is being finalized and waits. Slice POSTs and recorder
+ sessions are unaffected: those requests are short, and their retries
+ resume. Still worth timing a deploy for when nothing is uploading,
+ since the interrupted ingest's work is thrown away either way.
+- **The upload staging directory has no sweeper.** An ingest killed
+ mid-flight leaves its staged copy of the file behind, and nothing
+ removes it: the session sweep only owns `_sessions/`. This is not
+ specific to sliced uploads, `POST /upload` behaves the same way, but
+ it is worth a glance at `UPLOAD_FOLDER/_staging` after an incident.
## API
diff --git a/src/api/recording_sessions.py b/src/api/recording_sessions.py
index bcd94315..11718228 100644
--- a/src/api/recording_sessions.py
+++ b/src/api/recording_sessions.py
@@ -50,9 +50,11 @@ what was uploaded into the user's library) and only deletes sessions that
have nothing to recover. See that function for the full policy.
"""
+import contextlib
import json
import os
import shutil
+import threading
from datetime import datetime, timedelta
from flask import Blueprint, request, jsonify, current_app
@@ -107,20 +109,26 @@ def _max_chunk_bytes():
return int(os.environ.get('RECORDING_SESSION_MAX_CHUNK_BYTES', str(16 * 1024 * 1024)))
-def _ingest_ceiling_seconds():
- """How long a finalize's ingest can possibly still be running.
+def _ingest_heartbeat_seconds():
+ """How often an in-progress ingest stamps the session it is working on.
- A sliced upload's ingest happens inside the request, so no ingest
- outlives the WSGI server's own request timeout (gunicorn runs with
- ``--timeout 600``). Past this, a session still marked ``finalizing``
- belongs to a worker that no longer exists, typically because the
- container was recreated mid-ingest, and the next finalize may take it
- over. Set it above the deployment's request timeout, never below.
+ A sliced upload's ingest runs inside the request, and its liveness
+ cannot be inferred from any timeout: under gunicorn's ``gthread``
+ worker, which is what Speakr ships, ``--timeout`` bounds the accept
+ loop's silence, not a request's duration (``notify()`` fires every
+ iteration regardless of what the thread pool is doing), so a request
+ in a pool thread is never aborted. An ingest therefore says so
+ itself, every interval, and a session whose stamp has gone quiet for
+ three intervals is one whose worker is gone.
"""
try:
- return max(60, int(os.environ.get('RECORDING_SESSION_INGEST_CEILING_SECONDS', '900')))
+ return max(5, int(os.environ.get('RECORDING_SESSION_INGEST_HEARTBEAT_SECONDS', '30')))
except (TypeError, ValueError):
- return 900
+ return 30
+
+
+def _ingest_abandoned_after_seconds():
+ return _ingest_heartbeat_seconds() * 3
def _commit_batch_size():
@@ -173,6 +181,56 @@ def _write_session_manifest(session):
current_app.logger.warning(f"Could not write session manifest for {session.id}: {e}")
+def _touch_session(app, session_id):
+ """Stamp a session as still being worked on. Best-effort by design:
+ a missed stamp costs a takeover, a raised exception would cost the
+ ingest it is reporting on."""
+ try:
+ with app.app_context():
+ db.session.query(RecordingSession).filter(
+ RecordingSession.id == session_id,
+ RecordingSession.status == 'finalizing',
+ ).update({'last_seen_at': datetime.utcnow()}, synchronize_session=False)
+ db.session.commit()
+ except Exception as e:
+ app.logger.warning(f"Could not stamp session {session_id} during ingest: {e}")
+
+
+def _beat_until_stopped(app, session_id, stop, interval):
+ while True:
+ _touch_session(app, session_id)
+ if stop.wait(interval):
+ return
+
+
+def _ingest_heartbeat(session_id):
+ """Report an ingest alive until the returned callable is invoked.
+
+ Used as a context manager so the stamping stops whichever way the
+ ingest ends, including an exception on the way out.
+ """
+ app = current_app._get_current_object()
+ stop = threading.Event()
+ beater = threading.Thread(
+ target=_beat_until_stopped,
+ args=(app, session_id, stop, _ingest_heartbeat_seconds()),
+ name=f'ingest-heartbeat-{session_id[:8]}',
+ daemon=True,
+ )
+ beater.start()
+ return contextlib.closing(_Heartbeat(stop, beater))
+
+
+class _Heartbeat:
+ def __init__(self, stop, beater):
+ self._stop = stop
+ self._beater = beater
+
+ def close(self):
+ self._stop.set()
+ self._beater.join(timeout=5)
+
+
def _remove_session_dir(session_id, app=None):
"""Best-effort removal of a session's on-disk chunk directory."""
logger = (app.logger if app is not None else current_app.logger)
@@ -628,11 +686,12 @@ def finalize_sliced_upload(session_id):
declared at create, so a short or missing slice fails loudly instead
of ingesting as a truncated recording.
- A session already ``finalizing`` is claimable again once its claim is
- older than :func:`_ingest_ceiling_seconds`, which no live ingest can
- be: that state otherwise outlives the worker that owned it whenever a
- container is recreated mid-ingest, and the user's retry would wait
- for an ingest nobody is running until the TTL sweep, a day later.
+ A session already ``finalizing`` is claimable again once its ingest
+ has stopped saying it is alive (see
+ :func:`_ingest_heartbeat_seconds`). That state otherwise outlives the
+ worker that owned it whenever a container is recreated mid-ingest,
+ and the user's retry would wait for an ingest nobody is running until
+ the TTL sweep, a day later.
"""
session = db.session.get(RecordingSession, session_id)
err = _ensure_owned(session)
@@ -653,7 +712,7 @@ def finalize_sliced_upload(session_id):
}), 409
now = datetime.utcnow()
- abandoned_before = now - timedelta(seconds=_ingest_ceiling_seconds())
+ abandoned_before = now - timedelta(seconds=_ingest_abandoned_after_seconds())
claimed = db.session.query(RecordingSession).filter(
RecordingSession.id == session.id,
db.or_(
@@ -684,20 +743,21 @@ def finalize_sliced_upload(session_id):
}), 409
joined_path = os.path.join(dir_path, 'joined.bin')
- try:
- byte_join(slice_paths, joined_path)
- except OSError as e:
- current_app.logger.error(f"Could not join slices for session {session_id}: {e}")
- _fail_sliced_upload(session, f'Could not reassemble slices: {e}')
- return jsonify({'error': 'Server could not reassemble the uploaded slices'}), 500
-
- from src.api.recordings import ingest_uploaded_recording
- result = ingest_uploaded_recording(
- owner=current_user,
- uploaded_file=ReassembledUpload(joined_path, session.upload_filename),
- form=request.form,
- original_filename=session.upload_filename,
- )
+ with _ingest_heartbeat(session.id):
+ try:
+ byte_join(slice_paths, joined_path)
+ except OSError as e:
+ current_app.logger.error(f"Could not join slices for session {session_id}: {e}")
+ _fail_sliced_upload(session, f'Could not reassemble slices: {e}')
+ return jsonify({'error': 'Server could not reassemble the uploaded slices'}), 500
+
+ from src.api.recordings import ingest_uploaded_recording
+ result = ingest_uploaded_recording(
+ owner=current_user,
+ uploaded_file=ReassembledUpload(joined_path, session.upload_filename),
+ form=request.form,
+ original_filename=session.upload_filename,
+ )
response, status = result if isinstance(result, tuple) else (result, 200)
if 200 <= status < 300:
diff --git a/tests/test_sliced_file_upload.py b/tests/test_sliced_file_upload.py
index bb1fc664..0170dcc0 100644
--- a/tests/test_sliced_file_upload.py
+++ b/tests/test_sliced_file_upload.py
@@ -20,6 +20,7 @@ import os
import shutil
import sys
import tempfile
+import threading
import uuid
from datetime import datetime, timedelta
from unittest.mock import patch
@@ -28,7 +29,11 @@ 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, RecordingSession
-from src.api.recording_sessions import cleanup_expired_sessions
+from src.api.recording_sessions import (
+ _beat_until_stopped,
+ _ingest_heartbeat_seconds,
+ cleanup_expired_sessions,
+)
from tests.test_cov_recordings_write import _cleanup, _mk_user, _upload_mocks
from tests.test_recording_sessions import _login
@@ -402,6 +407,37 @@ def test_an_interrupted_sliced_upload_resumes_from_the_slices_already_sent():
shutil.rmtree(upload_folder, ignore_errors=True)
+def test_an_ingest_stamps_the_session_it_is_working_on():
+ """The stamp is the only liveness signal there is: under gunicorn's
+ gthread worker no timeout aborts a request, so a session in
+ 'finalizing' says nothing about whether anyone is still ingesting
+ it."""
+ upload_folder = _tmp_upload_folder()
+ with app.app_context():
+ app.config["UPLOAD_FOLDER"] = upload_folder
+ user = _mk_user("slice_beat")
+ client = app.test_client()
+ _login(client, user)
+ session_id = _open_session(client, filename="sample.mp3", mime_type="audio/mpeg")["session_id"]
+
+ session = db.session.get(RecordingSession, session_id)
+ session.status = "finalizing"
+ went_quiet_at = datetime.utcnow() - timedelta(minutes=5)
+ session.last_seen_at = went_quiet_at
+ db.session.commit()
+
+ stop = threading.Event()
+ stop.set()
+ _beat_until_stopped(app, session_id, stop, interval=999)
+
+ db.session.expire_all()
+ assert db.session.get(RecordingSession, session_id).last_seen_at > went_quiet_at
+
+ client.delete(f"/upload/session/{session_id}")
+ _cleanup(user)
+ shutil.rmtree(upload_folder, ignore_errors=True)
+
+
def test_a_finalize_abandoned_by_a_dead_worker_can_be_taken_over():
"""Recreating the container mid-ingest leaves the session finalizing
with nobody ingesting. Without a takeover the user's retry waits for
@@ -418,9 +454,10 @@ def test_a_finalize_abandoned_by_a_dead_worker_can_be_taken_over():
total_bytes=len(payload))["session_id"]
_send_slices(client, session_id, payload)
+ heartbeat = _ingest_heartbeat_seconds()
session = db.session.get(RecordingSession, session_id)
session.status = "finalizing"
- session.last_seen_at = datetime.utcnow()
+ session.last_seen_at = datetime.utcnow() - timedelta(seconds=heartbeat * 2)
db.session.commit()
fresh_claim = client.post(f"/upload/session/{session_id}/finalize-upload",
@@ -428,7 +465,7 @@ def test_a_finalize_abandoned_by_a_dead_worker_can_be_taken_over():
assert fresh_claim.status_code == 409
assert "already being finalized" in fresh_claim.get_json()["error"]
- session.last_seen_at = datetime.utcnow() - timedelta(hours=1)
+ session.last_seen_at = datetime.utcnow() - timedelta(seconds=heartbeat * 4)
db.session.commit()
staging = os.path.join(upload_folder, f"stg_{uuid.uuid4().hex[:6]}")