Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Resume paid transcription tasks from the processing job (Tencent, AssemblyAI)
Murtaza Nasircab5c7dfdf88
diff --git a/config/env.transcription.example b/config/env.transcription.exampleindex 2045b05a..1c8e635b 100644--- a/config/env.transcription.example+++ b/config/env.transcription.example@@ -10,7 +10,6 @@# TENCENT_ASR_POLL_INTERVAL=5# TENCENT_ASR_HOTWORD_ID=your-hotword-table-id# TENCENT_ASR_STAGING_PREFIX=tencent-asr-# TENCENT_ASR_STATE_DIR=/data/instance/tencent-tasks# Files over 5 MiB require Speakr S3 storage; see docs/advanced/tencent-asr.md.## Speakr supports multiple transcription providers through a connector-baseddiff --git a/docs/advanced/tencent-asr.md b/docs/advanced/tencent-asr.mdindex 48f543a2..8c076cd2 100644--- a/docs/advanced/tencent-asr.md+++ b/docs/advanced/tencent-asr.md@@ -82,49 +82,25 @@ The API limits URL jobs to 1 GiB and five hours. The operator should configureexpiration and incomplete-multipart-upload cleanup on this prefix only;Speakr does not change bucket lifecycle policies automatically.-Live validation used an unchanged 9.64 MB WebM recording (598.74 seconds) in-a private COS object: downloaded bytes matched SHA-256, anonymous access was-denied, Tencent returned 176 timestamped segments, and deletion was verified.-This is a functional test, not an accuracy or performance benchmark.-## Failures and retries-Checkpoints are stored in `tencent-tasks/` next to the SQLite database-(`/data/instance/tencent-tasks` in Docker), or in `TENCENT_ASR_STATE_DIR` when-set. Keep that directory on persistent storage.-It contains task IDs, object locators and completed transcription results, but-not credentials or signed URLs. Treat it as private application data. Every-worker serving the same instance must share it; per-file OS locks prevent-concurrent submission. Distributed deployments need filesystem lock semantics-and are not validated by this connector.--An identical audio file, ASR account and recognition parameters reuse the saved-task. After a polling failure or worker restart, retrying the recording resumes-polling rather than submitting again. Completed results are reused; results are-saved before deleting staging audio. Failed cleanup retains its locator and is-retried when that recording is processed again, with bucket lifecycle cleanup-as a fallback. There is no new background polling thread: recovery occurs when-Speakr's job queue or the user invokes transcription again.--**Ambiguous submissions never retry automatically.** If the worker dies after-starting submission but before saving the returned task ID, the checkpoint-blocks further submission until an operator reconciles it with Tencent's-console. Tasks older than 23 hours also stop instead of querying a potentially-reused task ID (Tencent retains results for 24 hours). A known provider rejection-can be retried after fixing configuration or quota. Failed remote tasks require-operator review.--Checkpoints are removed two days after their last update, since Tencent keeps-task results for 24 hours. A checkpoint holds the transcription result, so-deleting a recording in Speakr leaves that copy for at most two days. After a-blocked checkpoint expires, processing the recording again submits a new-billable task. An expired checkpoint whose staging object was never deleted is-noted in the log; the bucket lifecycle rule removes the object.--To intentionally request fresh recognition with unchanged settings, stop work-on that recording, confirm the old remote task is finished and clean up any-staging locator, then back up/remove only its matching checkpoint JSON. This-explicit operation can create another billable task. A user-facing reset action-is not included yet.+When Tencent accepts a task, its task ID is saved with the processing job. If+polling times out, an error occurs or Speakr restarts while the task runs, the+job is retried automatically and the saved task is polled again; the audio is+not submitted a second time. Reprocessing a recording starts a new job, and the+audio is submitted again, which can create another billable task.++If no answer arrives while the audio is being submitted, Tencent may still have+accepted the task. That job is not retried automatically, and the recording+shows an error. Check the Tencent ASR console for the task before reprocessing+the recording.++A saved task older than 23 hours is not queried, since Tencent keeps results for+24 hours; the audio is submitted again on that retry. A task that failed on+Tencent's side is not submitted again automatically: check the console, then+reprocess the recording.++Staged audio is deleted when its task finishes. The bucket lifecycle rule+removes objects left after an uncertain submission or an interrupted worker.API reference: [CreateRecTask](https://cloud.tencent.com/document/api/1093/37823).diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.mdindex 3690efab..baea328c 100644--- a/docs/getting-started/installation.md+++ b/docs/getting-started/installation.md@@ -249,6 +249,8 @@ TRANSCRIPTION_API_KEY=your-assemblyai-api-keyThe AssemblyAI endpoint is fixed, so the shared `TRANSCRIPTION_BASE_URL` and `TRANSCRIPTION_MODEL` are intentionally ignored for this connector (a leftover value from another connector will not misroute requests). To pin a speech model, set `ASSEMBLYAI_SPEECH_MODEL` (for example `universal-3-pro`); omit it to use your account default. Speaker diarization and hotwords come from each user's settings (hotwords map to AssemblyAI's word boost). Configure the text generation model as described above for summaries and chat features.+If polling times out or Speakr restarts while AssemblyAI is working on a recording, the job is retried automatically and the same transcript is polled again; the audio is not uploaded and billed a second time. Reprocessing a recording submits it again.+### Step 4: Configure System SettingsOne of Speakr's conveniences is automatic admin account creation. Instead of going through a registration process, you define the admin credentials in your environment file, and Speakr creates the account automatically on first startup. This ensures you can log in immediately without any additional setup steps:diff --git a/src/init_db.py b/src/init_db.pyindex fd3a5f92..7e4b2767 100644--- a/src/init_db.py+++ b/src/init_db.py@@ -344,6 +344,8 @@ def _run_migrations(app, engine):# Add is_new_upload column to processing_job table for tracking upload vs reprocessing jobsif add_column_if_not_exists(engine, 'processing_job', 'is_new_upload', 'BOOLEAN DEFAULT 0'):app.logger.info("Added is_new_upload column to processing_job table")+ if add_column_if_not_exists(engine, 'processing_job', 'provider_task', 'TEXT'):+ app.logger.info("Added provider_task column to processing_job table")if add_column_if_not_exists(engine, 'tag', 'group_id', 'INTEGER'):app.logger.info("Added group_id column to tag table")diff --git a/src/models/processing_job.py b/src/models/processing_job.pyindex 313328c7..5ddc99ec 100644--- a/src/models/processing_job.py+++ b/src/models/processing_job.py@@ -34,6 +34,11 @@ class ProcessingJob(db.Model):# Track if this is a new upload (vs reprocessing) - for cleanup on failureis_new_upload = db.Column(db.Boolean, default=False, nullable=False)+ # JSON: the task a submit-and-poll transcription service accepted for this+ # job, so a retry polls it instead of submitting (and paying) again. See+ # src/services/transcription/provider_tasks.py.+ provider_task = db.Column(db.Text, nullable=True)+# Timestampscreated_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False, index=True)started_at = db.Column(db.DateTime, nullable=True)diff --git a/src/services/job_queue.py b/src/services/job_queue.pyindex c082fda9..13e3cd9b 100644--- a/src/services/job_queue.py+++ b/src/services/job_queue.py@@ -296,6 +296,9 @@ class FairJobQueue:'payment required','quota exceeded','insufficient funds',+ # A paid submission with no clear outcome (Tencent ASR); only a+ # reprocess, which starts a new job, submits it again.+ 'had no clear outcome','model not found','invalid model','unsupported format',diff --git a/src/services/transcription/base.py b/src/services/transcription/base.pyindex da06ddec..68470e8c 100644--- a/src/services/transcription/base.py+++ b/src/services/transcription/base.py@@ -6,7 +6,7 @@ import jsonfrom abc import ABC, abstractmethodfrom dataclasses import dataclass, fieldfrom enum import Enum, auto-from typing import Optional, List, Dict, Any, BinaryIO, Set, Type, FrozenSet+from typing import Optional, List, Dict, Any, BinaryIO, Callable, Set, Type, FrozenSetclass TranscriptionCapability(Enum):@@ -88,6 +88,14 @@ class TranscriptionRequest:# Provider-specific options (passthrough)extra_options: Dict[str, Any] = field(default_factory=dict)+ # Saved provider task, for connectors with SUPPORTS_TASK_RESUME. A+ # connector calls save_provider_task(task) as soon as the service accepts+ # a job (and with None to forget it); a retry of the same processing job+ # receives that task back in provider_task and polls it instead of+ # submitting the audio again. Both are None outside a processing job.+ provider_task: Optional[Dict[str, Any]] = None+ save_provider_task: Optional[Callable[[Optional[Dict[str, Any]]], None]] = None+@dataclassclass TranscriptionSegment:@@ -167,6 +175,10 @@ class BaseTranscriptionConnector(ABC):# Provider-specific constraints - subclasses should overrideSPECIFICATIONS: ConnectorSpecifications = DEFAULT_SPECIFICATIONS+ # Submit-and-poll services that charge per job set this and use+ # TranscriptionRequest.provider_task / save_provider_task.+ SUPPORTS_TASK_RESUME: bool = False+def __init__(self, config: Dict[str, Any]):"""Initialize connector with configuration.diff --git a/src/services/transcription/connectors/assemblyai.py b/src/services/transcription/connectors/assemblyai.pyindex a62bad2d..ae06b82b 100644--- a/src/services/transcription/connectors/assemblyai.py+++ b/src/services/transcription/connectors/assemblyai.py@@ -45,6 +45,7 @@ class AssemblyAITranscriptionConnector(BaseTranscriptionConnector):TranscriptionCapability.HOTWORDS, # word_boost}PROVIDER_NAME = "assemblyai"+ SUPPORTS_TASK_RESUME = True# AssemblyAI's own speech models. The transcription-model that reaches a# connector can be resolved from shared settings (env, admin default, tag /@@ -175,6 +176,13 @@ class AssemblyAITranscriptionConnector(BaseTranscriptionConnector):def transcribe(self, request: TranscriptionRequest) -> TranscriptionResponse:try:+ saved_id = (request.provider_task or {}).get('transcript_id')+ if saved_id:+ # A retry of the same job: poll the transcript AssemblyAI+ # already accepted instead of paying for another one.+ logger.info("AssemblyAI: resuming transcript %s", saved_id)+ with self._client() as client:+ return self._parse_result(self._poll(client, saved_id))audio_bytes = self._read_audio(request)with self._client() as client:audio_url = self._upload(client, audio_bytes)@@ -191,6 +199,8 @@ class AssemblyAITranscriptionConnector(BaseTranscriptionConnector):transcript_id = resp.json().get('id')if not transcript_id:raise ProviderError("AssemblyAI submit returned no transcript id", provider=self.PROVIDER_NAME)+ if request.save_provider_task:+ request.save_provider_task({'transcript_id': transcript_id})result = self._poll(client, transcript_id)return self._parse_result(result)except (TranscriptionError, ConfigurationError):diff --git a/src/services/transcription/connectors/tencent_asr.py b/src/services/transcription/connectors/tencent_asr.pyindex 18aaf97d..3609ce99 100644--- a/src/services/transcription/connectors/tencent_asr.py+++ b/src/services/transcription/connectors/tencent_asr.py@@ -6,7 +6,6 @@ import hmacimport ioimport jsonimport logging-import osimport tempfileimport timefrom datetime import datetime, timezone@@ -18,20 +17,20 @@ import httpxfrom ..base import (BaseTranscriptionConnector, ConnectorSpecifications,TranscriptionCapability, TranscriptionResponse, TranscriptionSegment)from ..exceptions import ConfigurationError, ProviderError, TranscriptionError-from ..tencent_state import locked_checkpoint, prune_checkpointslogger = logging.getLogger(__name__)HOST = 'asr.tencentcloudapi.com'INLINE_LIMIT = 5 * 1024 * 1024FILE_LIMIT = 1024 * 1024 * 1024MODELS = ('16k_zh_en_meeting', '16k_zh_en_2.0')-# Tencent keeps task results for 24 hours, so a checkpoint is no use for-# recovery after that; it is removed a day later.-CHECKPOINT_MAX_AGE = 2 * 24 * 3600+# Tencent keeps task results for 24 hours and may reuse task IDs after that,+# so an older saved task is not queried.+TASK_MAX_AGE = 23 * 3600class TencentASRConnector(BaseTranscriptionConnector):PROVIDER_NAME = 'tencent_asr'+ SUPPORTS_TASK_RESUME = TrueCAPABILITIES = {TranscriptionCapability.DIARIZATION,TranscriptionCapability.TIMESTAMPS, TranscriptionCapability.HOTWORDS}SPECIFICATIONS = ConnectorSpecifications(@@ -55,7 +54,6 @@ class TencentASRConnector(BaseTranscriptionConnector):raise ConfigurationError('Tencent requires 0 < poll_interval <= timeout <= 10800 seconds')self.hotword_id = self.config.get('hotword_id', '').strip()self.default_diarize = self.config.get('diarize', True)- self.state_dir = self.config.get('state_dir')self.staging_prefix = (self.config.get('staging_prefix') or 'tencent-asr').strip('/')if not self.staging_prefix or '..' in self.staging_prefix.split('/'):raise ConfigurationError('Tencent staging prefix must be a nonempty object prefix without ..')@@ -131,17 +129,13 @@ class TencentASRConnector(BaseTranscriptionConnector):params['HotwordId'] = self.hotword_idreturn params- def _stage(self, path, request, state=None, save=None):+ def _stage(self, path, request):from src.services.storage import get_storage_service, parse_locatorstorage = get_storage_service()if not storage.s3:raise ConfigurationError('Tencent audio over 5 MiB requires Speakr S3 storage with a publicly reachable endpoint')key = self.staging_prefix + '/' + uuid4().hex + Path(request.filename).suffixlocator = parse_locator(storage.s3.build_locator(key))- if state is not None:- state['staging_locator'] = storage.s3.build_locator(key)- state['staging_endpoint'] = storage.s3.endpoint_url- save() # Remember the key even if the worker dies during upload.try:storage.s3.upload_local_file(path, key, content_type=request.mime_type or 'application/octet-stream', acl='private')url = storage.s3.presign_get_url(locator, expires_seconds=86400)@@ -176,44 +170,59 @@ class TencentASRConnector(BaseTranscriptionConnector):raisetime.sleep(min(self.poll_interval, max(0, deadline - time.monotonic())))raise TranscriptionError(f'Tencent task {task_id}: polling timed out. The remote task may still be running; '- 'retry the same recording to resume polling the saved task.')+ 'a retry of this job resumes polling the same task.')- def _state_directory(self):- if self.state_dir:- return self.state_dir- # Next to the SQLite database on the instance volume, as for the- # generated secret key; Flask's instance_path (/app/instance) is not a- # volume and is lost when the container is recreated.- uri = os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite:////data/instance/transcriptions.db')- if uri.startswith('sqlite:///'):- base = os.path.dirname(uri.split('sqlite:///', 1)[1]) or '.'- else:- base = '/data/instance'- return os.path.join(base, 'tencent-tasks')-- def _cleanup_checkpoint(self, state, save):- if not state.get('staging_locator'):+ @staticmethod+ def _cleanup_saved(locator_value):+ """Delete a staged object known only from a saved task."""+ if not locator_value:returnfrom src.services.storage import get_storage_service, parse_locatorstorage = get_storage_service().s3- if not storage or storage.endpoint_url != state.get('staging_endpoint'):- logger.warning('Tencent staging cleanup deferred: original storage endpoint is unavailable')- return- if self._cleanup(storage, parse_locator(state['staging_locator'])):- state.pop('staging_locator', None)- state.pop('staging_endpoint', None)- save()+ if storage:+ TencentASRConnector._cleanup(storage, parse_locator(locator_value))def transcribe(self, request):params = self._parameters(request)+ saved = request.provider_task or {}+ with httpx.Client(timeout=httpx.Timeout(60, connect=15), follow_redirects=False) as client:+ task_id = saved.get('task_id')+ if saved.get('submitting') and not task_id:+ # A retry of a job whose submission had no clear outcome:+ # Tencent may have accepted it, and submitting again could+ # charge twice. A reprocess starts a new job and submits.+ raise TranscriptionError(+ 'Tencent ASR: an earlier submission of this recording had no clear outcome and may have been '+ 'accepted. Check the Tencent ASR console, then reprocess the recording to submit it again.')+ if task_id and time.time() - saved.get('submitted_at', 0) >= TASK_MAX_AGE:+ logger.warning('Tencent ASR: saved task %s is too old to query; submitting the audio again', task_id)+ self._cleanup_saved(saved.get('staging_locator'))+ task_id = None+ if task_id:+ logger.info('Tencent ASR: resuming task %s', task_id)+ result = self._poll(client, task_id)+ self._cleanup_saved(saved.get('staging_locator'))+ else:+ task_id, storage, locator = self._submit(client, request, params)+ result = self._poll(client, task_id)+ # The task has finished, so Tencent no longer needs the audio.+ if storage:+ self._cleanup(storage, locator)+ if result['Status'] == 3:+ raise TranscriptionError(f'Tencent task {task_id} failed; check the ASR console for details')+ return self._parse_result(result, params['EngineModelType'], request.diarize)++ def _submit(self, client, request, params):+ """Send the audio; return the task ID and the staged object, if any."""+ save_task = request.save_provider_task or (lambda task: None)try:request.audio_file.seek(0)except (AttributeError, OSError, io.UnsupportedOperation):pass- # Spool without transcoding; hash original bytes to identify safe retries.+ storage = locator = None+ # The original bytes are sent; nothing is transcoded.with tempfile.TemporaryDirectory(prefix='speakr_tencent_') as directory:path = Path(directory) / 'audio'- digest = hashlib.sha256()size = 0with path.open('wb') as output:while True:@@ -224,68 +233,36 @@ class TencentASRConnector(BaseTranscriptionConnector):if size > FILE_LIMIT:raise TranscriptionError('Tencent ASR: audio exceeds 1 GiB URL limit')output.write(chunk)- digest.update(chunk)if not size:raise TranscriptionError('Tencent ASR: empty audio file')- identity = json.dumps([self.secret_id, digest.hexdigest(), params], sort_keys=True)- fingerprint = hashlib.sha256(identity.encode()).hexdigest()- directory = self._state_directory()- for locator in prune_checkpoints(directory, CHECKPOINT_MAX_AGE):- logger.warning('Tencent ASR: expired checkpoint removed; its staging object %s was not '- 'deleted and is left to the bucket lifecycle rule', locator)- with locked_checkpoint(directory, fingerprint) as (state, save):- state.update(source_sha256=digest.hexdigest(), source_bytes=size)- save()- if state.get('status') in ('completed', 'failed'):- self._cleanup_checkpoint(state, save)- if state['status'] == 'failed':- raise TranscriptionError('Saved Tencent task failed; inspect the checkpoint before explicitly starting another billable task')- return self._parse_result(state['result'], params['EngineModelType'], request.diarize)- if state.get('status') == 'submitting':- raise TranscriptionError('Tencent submission outcome is uncertain. Check the ASR console and saved checkpoint; automatic resubmission is blocked to prevent duplicate charges')- with httpx.Client(timeout=httpx.Timeout(60, connect=15), follow_redirects=False) as client:- task_id = state.get('task_id')- if task_id:- if time.time() - state['submitted_at'] >= 23 * 3600:- raise TranscriptionError('Saved Tencent task is nearing its 24-hour expiry; automatic resubmission is blocked. Check the ASR console')- logger.info('Resuming Tencent ASR task: %s', task_id)- else:- # A previous interrupted upload has no ASR task yet.- self._cleanup_checkpoint(state, save)- if state.get('staging_locator'):- raise TranscriptionError('Previous Tencent staging cleanup is pending; check object storage before retrying')- state.update(status='preparing')- save()- if size <= INLINE_LIMIT:- params.update(SourceType=1, Data=base64.b64encode(path.read_bytes()).decode(), DataLen=size)- else:- _, _, url = self._stage(str(path), request, state, save)- params.update(SourceType=0, Url=url)- state.update(status='submitting', submitted_at=time.time())- save() # Crash after this point must not silently submit twice.- try:- result = self._call(client, 'CreateRecTask', params)- except ProviderError as exc:- if exc.status_code and 400 <= exc.status_code < 500:- state['status'] = 'rejected'- save()- self._cleanup_checkpoint(state, save)- raise- except httpx.HTTPError:- raise TranscriptionError('Tencent ASR network error. Submission was not retried; its outcome is uncertain. Check the ASR console') from None- task_id = result.get('TaskId')- if not isinstance(task_id, int) or isinstance(task_id, bool):- raise ProviderError('Tencent submit returned no task ID; automatic resubmission is blocked', provider=self.PROVIDER_NAME)- state.update(status='pending', task_id=task_id)- save()- logger.info('Tencent ASR task submitted: %s', task_id)- result = self._poll(client, task_id)- state.update(status='completed' if result['Status'] == 2 else 'failed', result=result)- save() # Keep result before deleting the only cloud audio copy.- self._cleanup_checkpoint(state, save)- if result['Status'] == 3:- raise TranscriptionError(f'Tencent task {task_id} failed; check the ASR console for details')- return self._parse_result(result, params['EngineModelType'], request.diarize)+ if size <= INLINE_LIMIT:+ params.update(SourceType=1, Data=base64.b64encode(path.read_bytes()).decode(), DataLen=size)+ else:+ storage, locator, url = self._stage(str(path), request)+ params.update(SourceType=0, Url=url)+ staging = getattr(locator, 'raw', None)+ # Saved before sending: when no answer arrives, Tencent may still have+ # accepted the task, and a retry of this job must not submit it again.+ save_task({'submitting': True, 'staging_locator': staging})+ try:+ result = self._call(client, 'CreateRecTask', params)+ except ProviderError as exc:+ if exc.status_code and 400 <= exc.status_code < 500:+ # A definite rejection: nothing was accepted.+ save_task(None)+ if storage:+ self._cleanup(storage, locator)+ raise+ except httpx.HTTPError:+ raise TranscriptionError('Tencent ASR network error during submission. The submission was not retried; '+ 'Tencent may have accepted it. Check the ASR console before reprocessing '+ 'the recording.') from None+ task_id = result.get('TaskId')+ if not isinstance(task_id, int) or isinstance(task_id, bool):+ raise ProviderError('Tencent submit returned no task ID', provider=self.PROVIDER_NAME)+ save_task({'task_id': task_id, 'submitted_at': time.time(), 'staging_locator': staging})+ logger.info('Tencent ASR task submitted: %s', task_id)+ return task_id, storage, locatordef _parse_result(self, result, model, diarize):segments = []diff --git a/src/services/transcription/provider_tasks.py b/src/services/transcription/provider_tasks.pynew file mode 100644index 00000000..f10d7297--- /dev/null+++ b/src/services/transcription/provider_tasks.py@@ -0,0 +1,63 @@+"""Saved provider tasks for submit-and-poll transcription services.++AssemblyAI and Tencent accept a job, return a task ID and are then polled, and+they charge for each job. The task is saved on the running ProcessingJob as+soon as the service accepts it, so a retry of that job (after a polling+timeout, an error or a restart) polls the same task instead of submitting and+paying again. A new job, such as a reprocess the user starts, has no saved task+and always submits. A saved task is used only for the same service and the+same audio bytes.+"""++import hashlib+import json++from src.database import db+from src.models import ProcessingJob++TRANSCRIPTION_JOB_TYPES = ('transcribe', 'reprocess_transcription')+++def _file_sha256(path):+ digest = hashlib.sha256()+ with open(path, 'rb') as audio:+ for block in iter(lambda: audio.read(1024 * 1024), b''):+ digest.update(block)+ return digest.hexdigest()+++def provider_task_for(recording_id, provider, audio_path):+ """Return (saved task, save function) for the recording's running job.++ Both are None when no transcription job is running for the recording, as+ in incognito mode.+ """+ job = (ProcessingJob.query+ .filter(ProcessingJob.recording_id == recording_id,+ ProcessingJob.status == 'processing',+ ProcessingJob.job_type.in_(TRANSCRIPTION_JOB_TYPES))+ .order_by(ProcessingJob.id.desc())+ .first())+ if job is None:+ return None, None+ audio_sha256 = _file_sha256(audio_path)+ try:+ stored = json.loads(job.provider_task) if job.provider_task else None+ except ValueError:+ stored = None+ saved = None+ if (isinstance(stored, dict) and stored.get('provider') == provider+ and stored.get('audio_sha256') == audio_sha256):+ saved = stored.get('task')+ job_id = job.id++ def save(task):+ value = None if task is None else json.dumps(+ {'provider': provider, 'audio_sha256': audio_sha256, 'task': task})+ # Written in its own transaction, at once: the worker may be stopped+ # while the service is still working on the task.+ table = ProcessingJob.__table__+ with db.engine.begin() as connection:+ connection.execute(table.update().where(table.c.id == job_id).values(provider_task=value))++ return saved, savediff --git a/src/services/transcription/registry.py b/src/services/transcription/registry.pyindex e0b01193..91527310 100644--- a/src/services/transcription/registry.py+++ b/src/services/transcription/registry.py@@ -362,7 +362,6 @@ class ConnectorRegistry:'timeout': os.environ.get('TENCENT_ASR_TIMEOUT', '1800'),'poll_interval': os.environ.get('TENCENT_ASR_POLL_INTERVAL', '5'),'hotword_id': os.environ.get('TENCENT_ASR_HOTWORD_ID', ''),- 'state_dir': os.environ.get('TENCENT_ASR_STATE_DIR') or None,'staging_prefix': os.environ.get('TENCENT_ASR_STAGING_PREFIX', 'tencent-asr'),'diarize': os.environ.get('ASR_DIARIZE', 'true').lower() == 'true',}diff --git a/src/services/transcription/tencent_state.py b/src/services/transcription/tencent_state.pydeleted file mode 100644index 30438fdf..00000000--- a/src/services/transcription/tencent_state.py+++ /dev/null@@ -1,89 +0,0 @@-"""Durable Tencent task checkpoints; one OS lock per audio/options fingerprint."""-import json-import os-import time-from contextlib import contextmanager-from pathlib import Path-from uuid import uuid4--from .exceptions import TranscriptionError---@contextmanager-def locked_checkpoint(directory, fingerprint):- root = Path(directory)- root.mkdir(parents=True, exist_ok=True, mode=0o700)- path = root / (fingerprint + '.json')- with (root / (fingerprint + '.lock')).open('a+b') as lock:- lock.seek(0)- if os.name == 'nt':- import msvcrt- if not lock.read(1):- lock.write(b'0')- lock.flush()- lock.seek(0)- try:- msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)- except OSError:- raise TranscriptionError('This Tencent recording is already being processed; wait before retrying') from None- else:- import fcntl- try:- fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)- except BlockingIOError:- raise TranscriptionError('This Tencent recording is already being processed; wait before retrying') from None- try:- try:- state = json.loads(path.read_text()) if path.exists() else {}- except (ValueError, OSError):- raise TranscriptionError('Tencent checkpoint cannot be read; refusing a potentially duplicate submission') from None-- def save():- temporary = root / (fingerprint + '.' + uuid4().hex + '.tmp')- try:- fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)- with os.fdopen(fd, 'w', encoding='utf-8') as output:- json.dump(state, output, ensure_ascii=False)- output.flush()- os.fsync(output.fileno())- os.replace(temporary, path)- finally:- temporary.unlink(missing_ok=True)- yield state, save- finally:- if os.name == 'nt':- lock.seek(0)- msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)- else:- fcntl.flock(lock, fcntl.LOCK_UN)---def prune_checkpoints(directory, max_age_seconds):- """Remove checkpoints that have not been written for max_age_seconds.-- A checkpoint holds the full transcription result, and it is kept only to- recover a task after a worker restart, so it must not outlive Tencent's- 24-hour task retention by much. Returns the staging locators that expired- checkpoints still held (their objects are left to the bucket lifecycle rule).- """- root = Path(directory)- if not root.is_dir():- return []- cutoff = time.time() - max_age_seconds- leftovers = []- for path in root.glob('*.json'):- try:- if path.stat().st_mtime >= cutoff:- continue- except OSError:- continue- try:- with locked_checkpoint(root, path.stem) as (state, _save):- if state.get('staging_locator'):- leftovers.append(state['staging_locator'])- path.unlink(missing_ok=True)- except TranscriptionError:- # In use by another worker, or unreadable (checkpoints are written- # atomically, so that needs outside interference); left alone.- continue- return leftoversdiff --git a/src/tasks/processing.py b/src/tasks/processing.pyindex 134f1c59..98db89cd 100644--- a/src/tasks/processing.py+++ b/src/tasks/processing.py@@ -2060,6 +2060,11 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_filecleanup_funasr_staging,prepare_funasr_file_url,)+ provider_task = save_provider_task = None+ if getattr(connector, 'SUPPORTS_TASK_RESUME', False) is True and recording:+ from src.services.transcription.provider_tasks import provider_task_for+ provider_task, save_provider_task = provider_task_for(+ recording.id, connector.PROVIDER_NAME, actual_filepath)with open(actual_filepath, 'rb') as audio_file:# FunASR requires an externally reachable object URL.extra_options = {}@@ -2080,6 +2085,8 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_filehotwords=hotwords,model=transcription_model,extra_options=extra_options,+ provider_task=provider_task,+ save_provider_task=save_provider_task,)current_app.logger.info(diff --git a/tests/test_provider_task_resume.py b/tests/test_provider_task_resume.pynew file mode 100644index 00000000..92fab226--- /dev/null+++ b/tests/test_provider_task_resume.py@@ -0,0 +1,238 @@+"""A paid submit-and-poll task is saved on its processing job and resumed on a retry.++AssemblyAI and Tencent charge for each job they accept. A retry of the same+job (after a polling timeout, an error or a restart) polls the saved task; a+new job, such as a reprocess, submits afresh.+"""+import io+import os+import sys+import time+import uuid+from types import SimpleNamespace+from unittest.mock import MagicMock, Mock, patch++import httpx+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 ProcessingJob, Recording, User+from src.services.job_queue import job_queue+from src.services.transcription.base import TranscriptionRequest+from src.services.transcription.connectors.assemblyai import AssemblyAITranscriptionConnector+from src.services.transcription.connectors.tencent_asr import TencentASRConnector+from src.services.transcription.exceptions import ProviderError, TranscriptionError+from src.services.transcription.provider_tasks import provider_task_for+import src.tasks.processing as proc+++def _recording():+ suffix = uuid.uuid4().hex[:8]+ user = User(username=f"ptask_{suffix}", email=f"ptask_{suffix}@local.test",+ password="placeholder-bcrypt-hash")+ db.session.add(user)+ db.session.commit()+ recording = Recording(user_id=user.id, original_filename="m.webm", audio_path="local://m.webm",+ status="PROCESSING", title="provider task")+ db.session.add(recording)+ db.session.commit()+ return recording+++def _job(recording, status="processing", job_type="transcribe"):+ job = ProcessingJob(user_id=recording.user_id, recording_id=recording.id,+ job_type=job_type, status=status)+ db.session.add(job)+ db.session.commit()+ return job+++def audio(tmp_path):+ path = tmp_path / "audio.webm"+ path.write_bytes(b"original bytes")+ return str(path)+++# --- saving on the job --------------------------------------------------------++def test_a_retry_of_the_same_job_gets_the_saved_task(audio, tmp_path):+ with app.app_context():+ recording = _recording()+ _job(recording)+ saved, save = provider_task_for(recording.id, "tencent_asr", audio)+ assert saved is None+ save({"task_id": 7})+ db.session.expire_all()+ assert provider_task_for(recording.id, "tencent_asr", audio)[0] == {"task_id": 7}+ # Another service, or other audio bytes, never get it.+ assert provider_task_for(recording.id, "assemblyai", audio)[0] is None+ other = tmp_path / "other.webm"+ other.write_bytes(b"other bytes")+ assert provider_task_for(recording.id, "tencent_asr", str(other))[0] is None+ save(None)+ db.session.expire_all()+ assert provider_task_for(recording.id, "tencent_asr", audio)[0] is None+++def test_a_new_job_submits_afresh(audio):+ with app.app_context():+ recording = _recording()+ first = _job(recording)+ provider_task_for(recording.id, "tencent_asr", audio)[1]({"task_id": 7})+ first.status = "completed"+ db.session.commit()+ _job(recording, job_type="reprocess_transcription")+ saved, save = provider_task_for(recording.id, "tencent_asr", audio)+ assert saved is None and save is not None+++def test_nothing_is_saved_without_a_running_job(audio):+ with app.app_context():+ recording = _recording()+ assert provider_task_for(recording.id, "tencent_asr", audio) == (None, None)+++def test_processing_hands_the_saved_task_to_the_connector(tmp_path):+ with app.app_context():+ recording = _recording()+ rid = recording.id+ _job(recording)+ path = os.path.join(app.config["UPLOAD_FOLDER"], f"ptask_{rid}.webm")+ with open(path, "wb") as f:+ f.write(b"original bytes")+ provider_task_for(rid, "tencent_asr", path)[1]({"task_id": 9, "submitted_at": time.time()})++ connector = MagicMock()+ connector.PROVIDER_NAME = "tencent_asr"+ connector.SUPPORTS_TASK_RESUME = True+ connector.supports_diarization = False+ connector.default_diarize = False+ connector.specifications = MagicMock(max_duration_seconds=None, handles_chunking_internally=True,+ unsupported_codecs=[])+ response = MagicMock(text="resumed text", segments=None, speakers=None, speaker_embeddings=None)+ response.has_diarization.return_value = False+ connector.transcribe.return_value = response+ conversion = MagicMock(was_converted=False)+ try:+ 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=conversion), \+ patch.object(proc, "client", MagicMock()), \+ patch.object(proc, "ENABLE_INQUIRE_MODE", False), \+ patch.object(proc, "generate_title_task"), \+ patch.object(proc, "generate_summary_only_task"), \+ 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, "m.webm", time.time(),+ mime_type="audio/webm")+ finally:+ os.remove(path)+ sent = connector.transcribe.call_args.args[0]+ assert sent.provider_task["task_id"] == 9+ assert callable(sent.save_provider_task)+++# --- Tencent ------------------------------------------------------------------++def _tencent():+ return TencentASRConnector({"secret_id": "id", "secret_key": "secret", "poll_interval": .001, "timeout": .5})+++def _request(saved=None, store=None):+ return TranscriptionRequest(audio_file=io.BytesIO(b"original bytes"), filename="m.webm", diarize=True,+ provider_task=saved,+ save_provider_task=store.append if store is not None else None)+++def test_tencent_saves_the_task_before_and_after_submission():+ connector, store = _tencent(), []+ connector._call = Mock(return_value={"TaskId": 123})+ connector._poll = Mock(return_value={"Status": 2, "Result": "ok"})+ assert connector.transcribe(_request(store=store)).text == "ok"+ assert store[0] == {"submitting": True, "staging_locator": None}+ assert store[1]["task_id"] == 123 and store[1]["submitted_at"] > 0+++def test_tencent_retry_polls_the_saved_task():+ connector = _tencent()+ connector._call = Mock(side_effect=AssertionError("must not submit"))+ connector._poll = Mock(return_value={"Status": 2, "Result": "recovered"})+ saved = {"task_id": 123, "submitted_at": time.time(), "staging_locator": None}+ assert connector.transcribe(_request(saved)).text == "recovered"+ assert connector._poll.call_args.args[1] == 123+++def test_tencent_resume_deletes_the_staged_audio(monkeypatch):+ import src.services.storage as storage_module+ storage = Mock()+ monkeypatch.setattr(storage_module, "get_storage_service", lambda: SimpleNamespace(s3=storage))+ connector = _tencent()+ connector._poll = Mock(return_value={"Status": 2, "Result": "ok"})+ saved = {"task_id": 5, "submitted_at": time.time(), "staging_locator": "s3://bucket/tencent-asr/a.webm"}+ connector.transcribe(_request(saved))+ assert storage.delete.call_args.args[0].key == "tencent-asr/a.webm"+++def test_tencent_uncertain_submission_stops_retries_until_reprocess():+ connector, store = _tencent(), []+ connector._call = Mock(side_effect=httpx.ReadTimeout("private"))+ with pytest.raises(TranscriptionError, match="not retried"):+ connector.transcribe(_request(store=store))+ assert store == [{"submitting": True, "staging_locator": None}]+ retry = _tencent()+ retry._call = Mock(side_effect=AssertionError("duplicate submission"))+ with pytest.raises(TranscriptionError, match="no clear outcome") as exc:+ retry.transcribe(_request(store[-1]))+ # The job queue does not retry it again; a reprocess (a new job) submits.+ assert job_queue._is_permanent_error(str(exc.value))+++def test_tencent_rejection_forgets_the_task():+ connector, store = _tencent(), []+ connector._call = Mock(side_effect=ProviderError("Tencent CreateRecTask: AuthFailure.",+ provider="tencent_asr", status_code=400))+ with pytest.raises(ProviderError):+ connector.transcribe(_request(store=store))+ assert store == [{"submitting": True, "staging_locator": None}, None]+++def test_tencent_task_older_than_a_day_is_submitted_again():+ connector = _tencent()+ connector._call = Mock(return_value={"TaskId": 124})+ connector._poll = Mock(return_value={"Status": 2, "Result": "fresh"})+ saved = {"task_id": 123, "submitted_at": 0, "staging_locator": None}+ assert connector.transcribe(_request(saved)).text == "fresh"+ assert connector._poll.call_args.args[1] == 124+++# --- AssemblyAI ---------------------------------------------------------------++class _AssemblyAIClient:+ def __init__(self):+ self.posted, self.polled = [], []+ def __enter__(self): return self+ def __exit__(self, *a): return False+ def post(self, path, content=None, json=None, headers=None):+ self.posted.append(path)+ if path == "/v2/upload":+ return SimpleNamespace(status_code=200, json=lambda: {"upload_url": "https://cdn/x"}, text="")+ return SimpleNamespace(status_code=200, json=lambda: {"id": "tid-1"}, text="")+ def get(self, path):+ self.polled.append(path)+ return SimpleNamespace(status_code=200, json=lambda: {"status": "completed", "text": "hello"}, text="")+++def test_assemblyai_saves_the_transcript_and_a_retry_polls_it():+ connector = AssemblyAITranscriptionConnector({"api_key": "k", "poll_interval": 0})+ store, client = [], _AssemblyAIClient()+ with patch.object(connector, "_client", return_value=client):+ assert connector.transcribe(_request(store=store)).text == "hello"+ assert store == [{"transcript_id": "tid-1"}]+ retry_client = _AssemblyAIClient()+ with patch.object(connector, "_client", return_value=retry_client):+ assert connector.transcribe(_request(store[0])).text == "hello"+ assert retry_client.posted == [] and retry_client.polled == ["/v2/transcript/tid-1"]diff --git a/tests/test_tencent_asr.py b/tests/test_tencent_asr.pyindex 438a6e77..55ec4350 100644--- a/tests/test_tencent_asr.py+++ b/tests/test_tencent_asr.py@@ -13,9 +13,9 @@ from src.services.transcription.exceptions import ConfigurationError, ProviderEr@pytest.fixture-def connector(tmp_path):+def connector():return mod.TencentASRConnector({'secret_id': 'test-id', 'secret_key': 'test-secret',- 'poll_interval': .001, 'timeout': .5, 'state_dir': str(tmp_path)})+ 'poll_interval': .001, 'timeout': .5})def request(data=b'audio', **kwargs):@@ -126,7 +126,6 @@ def test_large_file_uses_private_staging_and_cleans_terminal(connector, monkeypaassert mod.Path(path).read_bytes() == b'123456'return storage, locator, 'https://bucket/file?signed=PRIVATE'monkeypatch.setattr(connector, '_stage', stage)- monkeypatch.setattr(connector, '_cleanup_checkpoint', lambda state, save: storage.delete(locator, missing_ok=True) if state.get('status') in ('completed','failed') else None)calls = transport(monkeypatch, [{'Data': {'TaskId': 42}}, {'Data': {'Status': status, 'Result': 'text'}}])if status == 2:assert connector.transcribe(request(b'123456')).text == 'text'@@ -209,7 +208,6 @@ def test_submission_rejection_removes_staging(connector, monkeypatch):monkeypatch.setattr(mod, 'INLINE_LIMIT', 5)storage = Mock()monkeypatch.setattr(connector, '_stage', lambda *args: (storage, 'locator', 'https://bucket/file'))- monkeypatch.setattr(connector, '_cleanup_checkpoint', lambda state, save: storage.delete('locator', missing_ok=True) if state.get('status') == 'rejected' else None)transport(monkeypatch, [{'Error': {'Code': 'AuthFailure.SecretIdNotFound'}}])with pytest.raises(ProviderError):connector.transcribe(request(b'123456'))@@ -228,3 +226,35 @@ def test_unknown_speaker_not_fabricated(connector):{'FinalSentence': 'one', 'SpeakerId': -1}, {'FinalSentence': 'two'}]}, mod.MODELS[0], True)assert not result.has_diarization()assert result.segments[0].start_time is None+++def test_cos_client_configuration_and_private_upload(tmp_path):+ from unittest.mock import patch+ from src.services.storage.s3 import S3StorageBackend+ backend=S3StorageBackend(bucket='test-123',region='ap-hongkong',+ endpoint_url='https://cos.ap-hongkong.myqcloud.com')+ with patch('boto3.client') as factory:+ backend._create_client()+ config=factory.call_args.kwargs['config']+ assert config.s3['addressing_style']=='virtual'+ assert config.request_checksum_calculation=='when_required'+ assert config.response_checksum_validation=='when_required'+ path=tmp_path/'audio.webm'+ path.write_bytes(b'original audio unchanged')+ fake=Mock()+ with patch.object(backend,'_get_client',return_value=fake), patch.object(backend,'stat'):+ backend.upload_local_file(str(path),'recordings/audio.webm',acl='private')+ fake.upload_file.assert_called_once_with(str(path),'test-123','recordings/audio.webm',ExtraArgs={'ACL':'private'})+ assert path.read_bytes()==b'original audio unchanged'+++def test_webm_pipeline_preserves_original_even_when_compression_enabled(tmp_path,monkeypatch):+ import src.utils.audio_conversion as conversion+ p=tmp_path/'meeting.webm'+ p.write_bytes(b'original webm bytes')+ monkeypatch.setattr(conversion,'AUDIO_COMPRESS_UPLOADS',True)+ monkeypatch.setattr(conversion,'get_codec_info',Mock(side_effect=AssertionError('must not inspect or convert')))+ result=conversion.convert_if_needed(str(p),connector_specs=mod.TencentASRConnector.SPECIFICATIONS)+ assert result.output_path==str(p)+ assert not result.was_compressed and not result.was_converted+ assert p.read_bytes()==b'original webm bytes'diff --git a/tests/test_tencent_recovery.py b/tests/test_tencent_recovery.pydeleted file mode 100644index 2a637127..00000000--- a/tests/test_tencent_recovery.py+++ /dev/null@@ -1,163 +0,0 @@-"""Recovery and cross-process duplication tests for paid Tencent ASR tasks."""-import io-import json-import subprocess-import sys-from unittest.mock import Mock--import httpx-import pytest--from src.services.transcription.base import TranscriptionRequest-from src.services.transcription.connectors.tencent_asr import TencentASRConnector-from src.services.transcription.exceptions import TranscriptionError-from src.services.transcription.tencent_state import locked_checkpoint---def connector(tmp_path):- return TencentASRConnector({'secret_id':'id','secret_key':'secret','state_dir':str(tmp_path)})---def audio():- return TranscriptionRequest(audio_file=io.BytesIO(b'original bytes'),filename='meeting.webm',diarize=True)---def test_new_worker_resumes_saved_task(tmp_path):- first=connector(tmp_path)- first._call=Mock(return_value={'TaskId':123})- first._poll=Mock(side_effect=TranscriptionError('network interrupted'))- with pytest.raises(TranscriptionError):- first.transcribe(audio())- second=connector(tmp_path)- second._call=Mock(side_effect=AssertionError('must not resubmit'))- second._poll=Mock(return_value={'Status':2,'Result':'recovered'})- assert second.transcribe(audio()).text=='recovered'- assert second._poll.call_args.args[1]==123- third=connector(tmp_path)- third._call=Mock(side_effect=AssertionError('must use saved result'))- third._poll=Mock(side_effect=AssertionError('must use saved result'))- assert third.transcribe(audio()).text=='recovered'---def test_uncertain_post_blocks_new_worker(tmp_path):- first=connector(tmp_path)- first._call=Mock(side_effect=httpx.ReadTimeout('sensitive URL'))- with pytest.raises(TranscriptionError,match='uncertain'):- first.transcribe(audio())- second=connector(tmp_path)- second._call=Mock(side_effect=AssertionError('duplicate submission'))- with pytest.raises(TranscriptionError,match='automatic resubmission is blocked'):- second.transcribe(audio())---def test_expired_task_never_reused_or_resubmitted(tmp_path):- first=connector(tmp_path)- first._call=Mock(return_value={'TaskId':123})- first._poll=Mock(side_effect=TranscriptionError('interrupted'))- with pytest.raises(TranscriptionError): first.transcribe(audio())- path=next(tmp_path.glob('*.json'))- state=json.loads(path.read_text())- state['submitted_at']=0- path.write_text(json.dumps(state))- with pytest.raises(TranscriptionError,match='expiry'):- connector(tmp_path).transcribe(audio())---def test_corrupt_checkpoint_does_not_submit(tmp_path):- path=tmp_path/'fingerprint.json'- path.write_text('{')- with pytest.raises(TranscriptionError,match='cannot be read'):- with locked_checkpoint(tmp_path,'fingerprint'): pass---def test_real_process_lock_and_crash_release(tmp_path):- program='''import sys,time-from src.services.transcription.tencent_state import locked_checkpoint-with locked_checkpoint(sys.argv[1], 'same-audio') as (state, save):- state.update(status='submitting')- save()- print('LOCKED',flush=True)- time.sleep(120)-'''- child=subprocess.Popen([sys.executable,'-c',program,str(tmp_path)],stdout=subprocess.PIPE,text=True)- try:- assert child.stdout.readline().strip()=='LOCKED'- with pytest.raises(TranscriptionError,match='already being processed'):- with locked_checkpoint(tmp_path,'same-audio'): pass- finally:- child.kill()- child.wait(timeout=10)- with locked_checkpoint(tmp_path,'same-audio') as (state,save):- assert state['status']=='submitting'---def test_failed_cleanup_preserves_locator_for_retry(tmp_path,monkeypatch):- import src.services.storage as storage_module- from types import SimpleNamespace- storage=Mock(endpoint_url='https://cos.ap-hongkong.myqcloud.com')- monkeypatch.setattr(storage_module,'get_storage_service',lambda:SimpleNamespace(s3=storage))- c=connector(tmp_path)- state={'status':'completed','staging_locator':'s3://test/recordings/audio.webm',- 'staging_endpoint':storage.endpoint_url}- save=Mock()- storage.delete.side_effect=RuntimeError('network')- c._cleanup_checkpoint(state,save)- assert 'staging_locator' in state- storage.delete.side_effect=None- c._cleanup_checkpoint(state,save)- assert 'staging_locator' not in state- save.assert_called_once()---def test_cos_client_configuration_and_private_upload(tmp_path):- from unittest.mock import patch- from src.services.storage.s3 import S3StorageBackend- backend=S3StorageBackend(bucket='test-123',region='ap-hongkong',- endpoint_url='https://cos.ap-hongkong.myqcloud.com')- with patch('boto3.client') as factory:- backend._create_client()- config=factory.call_args.kwargs['config']- assert config.s3['addressing_style']=='virtual'- assert config.request_checksum_calculation=='when_required'- assert config.response_checksum_validation=='when_required'- path=tmp_path/'audio.webm'- path.write_bytes(b'original audio unchanged')- fake=Mock()- with patch.object(backend,'_get_client',return_value=fake), patch.object(backend,'stat'):- backend.upload_local_file(str(path),'recordings/audio.webm',acl='private')- fake.upload_file.assert_called_once_with(str(path),'test-123','recordings/audio.webm',ExtraArgs={'ACL':'private'})- assert path.read_bytes()==b'original audio unchanged'---def test_webm_pipeline_preserves_original_even_when_compression_enabled(tmp_path,monkeypatch):- import src.utils.audio_conversion as conversion- p=tmp_path/'meeting.webm'- p.write_bytes(b'original webm bytes')- monkeypatch.setattr(conversion,'AUDIO_COMPRESS_UPLOADS',True)- monkeypatch.setattr(conversion,'get_codec_info',Mock(side_effect=AssertionError('must not inspect or convert')))- result=conversion.convert_if_needed(str(p),connector_specs=TencentASRConnector.SPECIFICATIONS)- assert result.output_path==str(p)- assert not result.was_compressed and not result.was_converted- assert p.read_bytes()==b'original webm bytes'---def test_expired_checkpoints_are_removed_and_report_staging(tmp_path):- import os, time- from src.services.transcription.tencent_state import locked_checkpoint, prune_checkpoints- for name, state in (('old', {'result': {'Result': 'text'}, 'staging_locator': 's3://b/k'}),- ('new', {'result': {'Result': 'text'}})):- with locked_checkpoint(tmp_path, name) as (current, save):- current.update(state)- save()- stale = time.time() - 3 * 24 * 3600- os.utime(tmp_path / 'old.json', (stale, stale))- assert prune_checkpoints(tmp_path, 2 * 24 * 3600) == ['s3://b/k']- assert not (tmp_path / 'old.json').exists() and (tmp_path / 'new.json').exists()---def test_default_checkpoint_directory_is_next_to_the_database(monkeypatch):- monkeypatch.setenv('SQLALCHEMY_DATABASE_URI', 'sqlite:////data/instance/transcriptions.db')- connector = TencentASRConnector({'secret_id': 'id', 'secret_key': 'secret'})- assert connector._state_directory() == '/data/instance/tencent-tasks'- monkeypatch.setenv('SQLALCHEMY_DATABASE_URI', 'postgresql://u:p@db/speakr')- assert connector._state_directory() == '/data/instance/tencent-tasks'