Author SHA1 Message Date
ahp 53becfa1de fix(api): answer 503 when an upload cannot be stored
An unwritable DATA_DIR (a root-owned volume, a full disk, a read-only
mount) made POST /jobs and POST /v1/audio/transcriptions fail with a
bare 500 and a PermissionError traceback, with nothing in the response
telling the client it was a server-side storage problem.

- save_upload raises StorageUnavailableError on any OSError while
  creating DATA_DIR/audio or writing the file, and removes a partially
  written file first
- one app-level handler turns it into 503 with a short detail; the real
  error, including the path, goes only to the server log
- the API logs an error at startup when DATA_DIR is not writable, so a
  bad volume shows up before the first upload
2026-11-26 18:02:05 +03:30
6 changed files with 100 additions and 77 deletions

No files matched your search

+6 -6
View File
@@ -76,12 +76,12 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
### Fixed
- The punctuation post-pass no longer splits numbers written with a
thousands separator: `1,000` stayed `1، 000` (Persian comma plus a
space). A comma between digits followed by exactly three digits is now
kept as is; a comma in a list of numbers (`4090,4080`) still becomes `،`.
The edge cases from #30 (slash dates, Latin digits in Persian sentences,
abbreviations, ellipses, repeated marks) are pinned by tests.
- An upload the API cannot store (unwritable `DATA_DIR`, full disk,
read-only volume) now answers **503** with a short message on `POST /jobs`
and `POST /v1/audio/transcriptions`, instead of a 500 with a traceback in
the log. The real `OSError` is logged server-side, a partially written
file is removed, and the API logs an error at startup when `DATA_DIR`
is not writable.
## [1.4.1] - 2026-11-26
+22 -3
View File
@@ -25,6 +25,14 @@ ALLOWED_EXTENSIONS = {".mp3", ".m4a", ".mp4", ".wav", ".ogg", ".opus", ".webm",
_SAFE_SUFFIX = re.compile(r"^[a-z0-9]{1,8}$")
class StorageUnavailableError(Exception):
"""DATA_DIR cannot be written, e.g. a root-owned volume or a full disk.
It is a server fault, not a bad upload, so the API answers 503 and the
real OSError stays in the server log instead of reaching the client.
"""
def decode_to_mono_16k(path: str | Path) -> np.ndarray:
"""Decode any media file to mono float32 PCM at 16 kHz."""
return decode_audio(str(path), sampling_rate=SAMPLE_RATE)
@@ -102,12 +110,23 @@ def audio_dir() -> Path:
def save_upload(data: bytes, job_id: str, original_filename: str) -> Path:
"""Persist an upload under DATA_DIR/audio with a safe extension."""
"""Persist an upload under DATA_DIR/audio with a safe extension.
Raises StorageUnavailableError when the directory or file cannot be
written; a partially written file is removed first.
"""
suffix = Path(original_filename).suffix.lower()
if suffix not in ALLOWED_EXTENSIONS or not _SAFE_SUFFIX.match(suffix[1:]):
suffix = ".bin"
path = audio_dir() / f"{job_id}{suffix}"
path.write_bytes(data)
try:
path = audio_dir() / f"{job_id}{suffix}"
except OSError as exc:
raise StorageUnavailableError(str(exc)) from exc
try:
path.write_bytes(data)
except OSError as exc:
delete_audio(path)
raise StorageUnavailableError(str(exc)) from exc
return path
+2 -10
View File
@@ -5,8 +5,7 @@ puts the transcript back into publishable shape with three conservative,
deterministic rule families — no model call, no LLM dependency:
1. Script fix: the Latin comma, question mark and semicolon become their
Persian counterparts (، ؟ ؛). A comma that groups digits ("1,000",
"12,500,000") is a thousands separator, not punctuation, and is kept.
Persian counterparts (، ؟ ؛).
2. Spacing: no space *before* punctuation, exactly one space *after* clause
and sentence punctuation. `.` and `:` are deliberately left alone so
decimals ("3.5") and clock times ("12:30") survive.
@@ -27,12 +26,6 @@ import re
# Latin forms that should not survive in a Persian transcript.
_LATIN_TO_PERSIAN = str.maketrans({",": "،", "?": "؟", ";": "؛"})
# A comma between a digit and exactly three more digits groups a number.
# \d matches Persian digits too, so "۱,۲۰۰" is covered.
_THOUSANDS_COMMA = re.compile(r"(?<=\d),(?=\d{3}(?!\d))")
# Stands in for a thousands comma while the Latin marks are translated.
_KEPT_COMMA = "\x00"
_CLAUSE = "،؛"
_SENTENCE_END = "؟!…."
_PUNCT_CHARS = _CLAUSE + _SENTENCE_END + ":."
@@ -80,8 +73,7 @@ def _has_terminal(text: str) -> bool:
def restore_punctuation(text: str) -> str:
"""Return `text` with Persian punctuation restored; safe to re-apply."""
cleaned = _THOUSANDS_COMMA.sub(_KEPT_COMMA, text)
cleaned = cleaned.translate(_LATIN_TO_PERSIAN).replace(_KEPT_COMMA, ",").strip()
cleaned = text.translate(_LATIN_TO_PERSIAN).strip()
cleaned = _SPACE_BEFORE.sub(r"\1", cleaned)
cleaned = _SPACE_AFTER.sub(r"\1 ", cleaned)
cleaned = _WS_RUNS.sub(" ", cleaned).strip()
+19 -1
View File
@@ -10,11 +10,13 @@ import os
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi import FastAPI, Request, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from sokhan import __version__
from sokhan.config import get_settings
from sokhan.core.audio import StorageUnavailableError, audio_dir
from sokhan.db import configure, create_all
logger = logging.getLogger("sokhan")
@@ -27,6 +29,14 @@ def create_app() -> FastAPI:
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
configure()
create_all()
try:
audio_dir()
except OSError as exc:
logger.error(
"DATA_DIR is not writable (%s) - uploads will fail with 503 until "
"it is; in Docker check the volume is owned by the app user",
exc,
)
if not settings.celery_enabled:
logger.warning(
"CELERY_ENABLED=false - jobs run inline in the API process; "
@@ -68,6 +78,14 @@ def create_app() -> FastAPI:
app.include_router(routes_openai.router)
app.include_router(routes_admin.router)
@app.exception_handler(StorageUnavailableError)
async def storage_unavailable(request: Request, exc: StorageUnavailableError) -> JSONResponse:
logger.error("upload storage failed for %s %s: %s", request.method, request.url.path, exc)
return JSONResponse(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
content={"detail": "upload storage is unavailable, try again later"},
)
@app.get("/")
def root() -> dict:
return {"name": "Sokhan API", "version": __version__, "docs": "/docs"}
+51
View File
@@ -1,5 +1,8 @@
import io
import shutil
from pathlib import Path
import pytest
from docx import Document
@@ -188,3 +191,51 @@ def test_other_users_cannot_read_a_job(client, auth, wav_bytes, fake_engine):
assert client.get(f"/jobs/{job_id}", headers=headers).status_code == 404
assert client.get("/jobs", headers=headers).json()["total"] == 0
def _make_data_dir_unwritable(tmp_path):
"""Replace DATA_DIR with a plain file, so creating DATA_DIR/audio fails."""
shutil.rmtree(tmp_path / "data")
(tmp_path / "data").write_text("not a directory")
def test_upload_answers_503_when_storage_is_unwritable(
client, auth, wav_bytes, fake_engine, tmp_path
):
_make_data_dir_unwritable(tmp_path)
response = _upload(client, auth, wav_bytes)
assert response.status_code == 503
assert response.json() == {"detail": "upload storage is unavailable, try again later"}
# No job row is left behind for an upload that was never stored.
assert client.get("/jobs", headers=auth).json()["total"] == 0
def test_openai_endpoint_answers_503_when_storage_is_unwritable(
client, auth, wav_bytes, fake_engine, tmp_path
):
_make_data_dir_unwritable(tmp_path)
response = client.post(
"/v1/audio/transcriptions",
files={"file": ("test.wav", wav_bytes, "audio/wav")},
data={"language": "fa", "response_format": "json"},
headers=auth,
)
assert response.status_code == 503
def test_failed_write_removes_the_partial_file(app, tmp_path, monkeypatch):
from sokhan.core.audio import StorageUnavailableError, audio_dir, save_upload
def write_fails_midway(self, data):
self.open("wb").write(data[:1])
raise OSError(28, "No space left on device")
monkeypatch.setattr(Path, "write_bytes", write_fails_midway)
with pytest.raises(StorageUnavailableError):
save_upload(b"RIFF....", "job-1", "clip.wav")
assert list(audio_dir().iterdir()) == []
-57
View File
@@ -51,60 +51,3 @@ def test_empty_and_whitespace_input_stay_empty():
def test_statement_with_colon_gets_no_double_mark():
assert restore_punctuation("این است") == "این است."
assert restore_punctuation("این است:") == "این است:"
# Edge cases from #30. Each test pins the behavior on real-world input; the
# comments say why that behavior is the right one for a transcript.
def test_slash_dates_are_left_intact():
# `/` is not punctuation to this pass, so date groups never get spaced
# or split, in Persian and in Latin digits alike.
assert restore_punctuation("تاریخ ۱۴۰۴/۰۹/۰۲ است") == "تاریخ ۱۴۰۴/۰۹/۰۲ است."
assert restore_punctuation("جلسه 2026/11/23 برگزار شد") == "جلسه 2026/11/23 برگزار شد."
assert restore_punctuation("نسبت ۱/۲ است") == "نسبت ۱/۲ است."
def test_latin_digits_and_words_inside_persian_sentences():
assert restore_punctuation("۳ دستگاه RTX 4090 خریدیم") == "۳ دستگاه RTX 4090 خریدیم."
assert restore_punctuation("قیمت ۳.۵ میلیون شد") == "قیمت ۳.۵ میلیون شد."
assert restore_punctuation("نسخه 1.4.1 منتشر شد") == "نسخه 1.4.1 منتشر شد."
assert restore_punctuation("ساعت ۱۲:۳۰ بیا") == "ساعت ۱۲:۳۰ بیا."
def test_thousands_separators_are_not_turned_into_persian_commas():
# A Latin comma followed by exactly three digits groups a number; turning
# it into ، and spacing it ("1، 000") would split one number into two.
assert restore_punctuation("قیمت 1,000 دلار شد") == "قیمت 1,000 دلار شد."
assert restore_punctuation("جمعیت 12,500,000 نفر") == "جمعیت 12,500,000 نفر."
assert restore_punctuation("مبلغ ۱,۲۰۰ تومان") == "مبلغ ۱,۲۰۰ تومان."
def test_comma_between_numbers_that_is_not_grouping_stays_a_list_separator():
assert restore_punctuation("RTX 4090,4080 و 3090") == "RTX 4090، 4080 و 3090."
assert restore_punctuation("اعداد 1,2 و 3") == "اعداد 1، 2 و 3."
def test_abbreviation_dots_are_kept_and_end_the_segment():
# A trailing dot already counts as terminal punctuation, so nothing is
# appended; a dot in the middle is left alone like a decimal point.
assert restore_punctuation("Dr.") == "Dr."
assert restore_punctuation("با Dr. Smith صحبت کردم") == "با Dr. Smith صحبت کردم."
assert restore_punctuation("با دکتر. احمدی") == "با دکتر. احمدی."
def test_ellipsis_forms_are_terminal_and_tightened():
assert restore_punctuation("صبر کن…") == "صبر کن…"
assert restore_punctuation("نمیدونم...") == "نمیدونم..."
assert restore_punctuation("صبر کن ... بعد") == "صبر کن... بعد."
# A trailing-off question keeps its ellipsis instead of gaining a ؟.
assert restore_punctuation("کی میای...") == "کی میای..."
def test_repeated_and_mixed_marks_are_preserved():
# Repetition carries the speaker's emphasis; the pass only converts the
# script of Latin marks and never collapses them.
assert restore_punctuation("وای!!!") == "وای!!!"
assert restore_punctuation("چرا!!!") == "چرا!!!"
assert restore_punctuation("چی؟؟") == "چی؟؟"
assert restore_punctuation("واقعا?!") == "واقعا؟!"