Skip to content

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

Python

Status codes in error text match only as separate tokens

Murtaza Nasircd800830ab44
diff --git a/src/utils/error_formatting.py b/src/utils/error_formatting.py
index 836001ab..0cda7985 100644
--- a/src/utils/error_formatting.py
+++ b/src/utils/error_formatting.py
@@ -10,6 +10,13 @@ import json
from typing import Dict, Optional, Tuple
+def _code(status):
+ """A status code as a separate token ("status 401", "(429)"), never inside
+ an id or a longer number: "401" in a Ray actor id labelled a WhisperX
+ out-of-memory traceback as an authentication error."""
+ return rf'(?<![\w.-]){status}(?![\w-]|\.\w)'
+
+
# Known error patterns with user-friendly messages
ERROR_PATTERNS = [
# File size errors
@@ -17,7 +24,7 @@ ERROR_PATTERNS = [
'patterns': [
r'maximum content size limit.*exceeded',
r'file.*too large',
- r'413.*exceeded',
+ _code(413) + r'.*exceeded',
r'payload too large',
],
'title': 'File Too Large',
@@ -43,7 +50,7 @@ ERROR_PATTERNS = [
# Authentication errors
{
'patterns': [
- r'401.*unauthorized',
+ _code(401) + r'.*unauthorized',
r'invalid.*api.*key',
r'authentication.*failed',
r'api key.*invalid',
@@ -60,7 +67,7 @@ ERROR_PATTERNS = [
'patterns': [
r'rate.*limit',
r'too many requests',
- r'429',
+ _code(429),
r'quota.*exceeded',
],
'title': 'Rate Limit Exceeded',
@@ -88,9 +95,9 @@ ERROR_PATTERNS = [
# Service unavailable
{
'patterns': [
- r'503.*service unavailable',
- r'502.*bad gateway',
- r'500.*internal server error',
+ _code(503) + r'.*service unavailable',
+ _code(502) + r'.*bad gateway',
+ _code(500) + r'.*internal server error',
r'service.*unavailable',
r'server.*error',
],
diff --git a/static/js/app.modular.js b/static/js/app.modular.js
index 19e9eca1..7850893e 100644
--- a/static/js/app.modular.js
+++ b/static/js/app.modular.js
@@ -25,6 +25,7 @@ import { showToast } from './modules/utils/toast.js';
import { getContrastTextColor } from './modules/utils/colors.js';
import { labelPathForFilter, parseLabelPath } from './modules/utils/label-links.js';
import { buildVariableList } from './modules/utils/prompt-variables.js';
+import { errorTextMatches } from './modules/utils/error-patterns.js';
import {
detectPlatform,
getAudioCapabilities,
@@ -161,7 +162,7 @@ const parseUnformattedError = (text) => {
// Check patterns
for (const pattern of patterns) {
for (const p of pattern.patterns) {
- if (lowerText.includes(p)) {
+ if (errorTextMatches(lowerText, p)) {
return {
title: pattern.title,
message: pattern.message,
diff --git a/static/js/modules/composables/upload.js b/static/js/modules/composables/upload.js
index 224ff71e..7ff82f4c 100644
--- a/static/js/modules/composables/upload.js
+++ b/static/js/modules/composables/upload.js
@@ -10,6 +10,7 @@ import { getUploadCsrfToken, isCsrfRejection } from '../csrf.js';
import { shouldSliceUpload, uploadFileInSlices } from '../db/sliced-file-upload.js';
import { computeUploadTimeout } from '../utils/upload-timeout.js';
import { recorderInUse } from '../utils/recorder-state.js';
+import { errorTextMatches } from '../utils/error-patterns.js';
import {
sortQueuedForJoin, moveQueuedItem, placeQueuedItem, totalJoinDuration,
newJoinGroupId, isVideoFileName, MAX_JOIN_FILES,
@@ -37,7 +38,7 @@ function getFriendlyError(errorMessage, t) {
];
for (const pattern of patterns) {
for (const p of pattern.patterns) {
- if (lowerText.includes(p)) return { title: pattern.title, guidance: pattern.guidance };
+ if (errorTextMatches(lowerText, p)) return { title: pattern.title, guidance: pattern.guidance };
}
}
return { title: _t('errors.processingError'), guidance: _t('errors.processingErrorFallbackGuidance') };
diff --git a/static/js/modules/utils/error-patterns.js b/static/js/modules/utils/error-patterns.js
new file mode 100644
index 00000000..8c47458c
--- /dev/null
+++ b/static/js/modules/utils/error-patterns.js
@@ -0,0 +1,17 @@
+/**
+ * Pattern matching for the friendly-error tables (upload dialog, stored
+ * errors, unformatted errors).
+ *
+ * A three-digit status code matches only as a separate token, such as
+ * "status 401", "(429)" or "HTTP 503:", never inside an id or a longer number.
+ * A WhisperX out-of-memory traceback was shown as "Authentication Error"
+ * because "401" occurred in a Ray actor id, and "1500" counted as a 500.
+ */
+const STATUS_CODE = /^\d{3}$/;
+
+export function errorTextMatches(lowerText, pattern) {
+ if (STATUS_CODE.test(pattern)) {
+ return new RegExp(`(?<![\\w.-])${pattern}(?![\\w-]|\\.\\w)`).test(lowerText);
+ }
+ return lowerText.includes(pattern);
+}
diff --git a/static/js/modules/utils/error-patterns.test.js b/static/js/modules/utils/error-patterns.test.js
new file mode 100644
index 00000000..28c1eb27
--- /dev/null
+++ b/static/js/modules/utils/error-patterns.test.js
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest';
+
+import { errorTextMatches } from './error-patterns.js';
+
+describe('errorTextMatches', () => {
+ it('matches a status code written as a code', () => {
+ for (const text of ['asr request failed with status 401', 'http 401 unauthorized',
+ 'error code: 429 - too many', 'failed (503)', 'server returned 502.', 'status=500, retrying']) {
+ expect(errorTextMatches(text, text.match(/\d{3}/)[0]), text).toBe(true);
+ }
+ });
+
+ it('does not match a code inside an id or a longer number', () => {
+ // The WhisperX traceback that was labelled "Authentication Error".
+ expect(errorTextMatches('actor_id=8f2c401ab93e7d10 cuda failed with error out of memory', '401')).toBe(false);
+ expect(errorTextMatches('request 3a-401f failed', '401')).toBe(false);
+ expect(errorTextMatches('max_tokens=1500 exceeded', '500')).toBe(false);
+ expect(errorTextMatches('version 2.4.1.401', '401')).toBe(false);
+ });
+
+ it('matches words as substrings, as before', () => {
+ expect(errorTextMatches('the service is unauthorized here', 'unauthorized')).toBe(true);
+ expect(errorTextMatches('request timed out after 600s', 'timed out')).toBe(true);
+ });
+});
diff --git a/static/js/modules/utils/errorDisplay.js b/static/js/modules/utils/errorDisplay.js
index a5a9ae17..6c54a4fc 100644
--- a/static/js/modules/utils/errorDisplay.js
+++ b/static/js/modules/utils/errorDisplay.js
@@ -5,6 +5,8 @@
* Handles both JSON-formatted errors (ERROR_JSON:...) and plain text errors.
*/
+import { errorTextMatches } from './error-patterns.js';
+
/**
* Parse a stored error message from the backend.
* @param {string} text - The stored transcription/error text
@@ -148,7 +150,7 @@ function parseUnformattedError(text) {
// Check patterns
for (const pattern of patterns) {
for (const p of pattern.patterns) {
- if (lowerText.includes(p)) {
+ if (errorTextMatches(lowerText, p)) {
return {
title: pattern.title,
message: pattern.message,
diff --git a/tests/test_error_status_codes.py b/tests/test_error_status_codes.py
new file mode 100644
index 00000000..457d90b6
--- /dev/null
+++ b/tests/test_error_status_codes.py
@@ -0,0 +1,35 @@
+"""Status codes in error text are matched only as separate tokens.
+
+A WhisperX out-of-memory traceback was shown as "Authentication Error",
+because "401" occurred in a Ray actor id. The same applied to "429" inside
+any longer number.
+"""
+
+import os
+import sys
+
+import pytest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from src.utils.error_formatting import format_error_for_user
+
+OOM = ("ASR request failed with status 500: worker error: Traceback (most recent call last): "
+ "ray.exceptions.RayTaskError: ActorID 8f2c401ab93e7d10 ... RuntimeError: CUDA failed with error out of memory")
+
+
+def test_an_id_containing_401_is_not_an_authentication_error():
+ assert format_error_for_user(OOM)["type"] != "auth"
+
+
[email protected]("text,kind", [
+ ("Error code: 401 - {'error': {'message': 'Unauthorized'}}", "auth"),
+ ("HTTP 429 Too Many Requests", "rate_limit"),
+ ("Error code: 429 - please slow down", "rate_limit"),
+])
+def test_real_status_codes_are_still_recognised(text, kind):
+ assert format_error_for_user(text)["type"] == kind
+
+
+def test_a_longer_number_is_not_a_status_code():
+ assert format_error_for_user("used 1429 tokens, then the request failed")["type"] != "rate_limit"