Skip to content

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

Python

Tests: finish last 2 false guards via behaviour-preserving helper extractions

Murtaza Nasir0dc4ae79f1b2
diff --git a/src/init_db.py b/src/init_db.py
index 9a461dde..41093b0b 100644
--- a/src/init_db.py
+++ b/src/init_db.py
@@ -22,6 +22,37 @@ from src.utils import add_column_if_not_exists, migrate_column_type, create_inde
ENABLE_INQUIRE_MODE = os.environ.get('ENABLE_INQUIRE_MODE', 'false').lower() == 'true'
+def classify_embedding_identifier_state(current_identifier, stored_identifier, legacy_identifier):
+ """Decide the embedding-identifier compatibility outcome at startup.
+
+ Pure, side-effect-free decision logic extracted from initialize_database.
+ Pre-v0.8.16-alpha instances stored only the bare model name under the
+ legacy 'embedding_model_name' key; such a value is by definition a local
+ sentence-transformers model, so it is wrapped as 'local::<name>' before
+ comparison to avoid a false-positive mismatch warning on first upgrade.
+
+ Returns a 3-tuple (effective_stored, migrated_from_legacy, outcome) where
+ outcome is one of:
+ 'first-run' - nothing stored yet; record the current identifier.
+ 'silent-migration' - legacy value matches current; promote to new key.
+ 'no-change' - stored identifier already matches current.
+ 'warn-mismatch' - stored identifier differs from current.
+ """
+ migrated_from_legacy = False
+ if stored_identifier is None and legacy_identifier:
+ stored_identifier = f"local::{legacy_identifier}"
+ migrated_from_legacy = True
+
+ if stored_identifier is None:
+ outcome = 'first-run'
+ elif stored_identifier == current_identifier:
+ outcome = 'silent-migration' if migrated_from_legacy else 'no-change'
+ else:
+ outcome = 'warn-mismatch'
+
+ return stored_identifier, migrated_from_legacy, outcome
+
+
def initialize_database(app):
"""
Initialize database schema and run migrations.
@@ -709,21 +740,21 @@ def initialize_database(app):
from src.services.embeddings import EMBEDDING_IDENTIFIER
current_identifier = EMBEDDING_IDENTIFIER
- stored_identifier = SystemSetting.get_setting('embedding_identifier', None)
+ raw_stored_identifier = SystemSetting.get_setting('embedding_identifier', None)
# Backwards-compat path: pre-v0.8.16-alpha instances stored only the
# bare model name under the legacy 'embedding_model_name' key. Any
# such value is by definition a local sentence-transformers model,
# so wrap it in the new 'local::<name>' format before comparing.
# This prevents a false-positive warning on first upgrade.
legacy_model_name = SystemSetting.get_setting('embedding_model_name', None)
- migrated_from_legacy = False
- if stored_identifier is None and legacy_model_name:
- stored_identifier = f"local::{legacy_model_name}"
- migrated_from_legacy = True
+
+ stored_identifier, migrated_from_legacy, outcome = classify_embedding_identifier_state(
+ current_identifier, raw_stored_identifier, legacy_model_name
+ )
chunk_count = TranscriptChunk.query.filter(TranscriptChunk.embedding.isnot(None)).count()
- if stored_identifier is None:
+ if outcome == 'first-run':
SystemSetting.set_setting(
key='embedding_identifier',
value=current_identifier,
@@ -732,20 +763,19 @@ def initialize_database(app):
)
if chunk_count:
app.logger.info(f"Recorded embedding_identifier={current_identifier} (existing {chunk_count} chunks assumed to match)")
- elif stored_identifier == current_identifier:
- if migrated_from_legacy:
- # Same configuration, just promote the value into the new key
- # so subsequent restarts skip the legacy lookup.
- SystemSetting.set_setting(
- key='embedding_identifier',
- value=current_identifier,
- description='Identifier of the embedding provider and model that produced the stored chunk vectors. Used to detect dimensionality and semantic-space mismatches at startup.',
- setting_type='string',
- )
- app.logger.info(
- f"Migrated legacy embedding_model_name={legacy_model_name!r} to embedding_identifier={current_identifier!r}"
- )
- else:
+ elif outcome == 'silent-migration':
+ # Same configuration, just promote the value into the new key
+ # so subsequent restarts skip the legacy lookup.
+ SystemSetting.set_setting(
+ key='embedding_identifier',
+ value=current_identifier,
+ description='Identifier of the embedding provider and model that produced the stored chunk vectors. Used to detect dimensionality and semantic-space mismatches at startup.',
+ setting_type='string',
+ )
+ app.logger.info(
+ f"Migrated legacy embedding_model_name={legacy_model_name!r} to embedding_identifier={current_identifier!r}"
+ )
+ elif outcome == 'warn-mismatch':
if chunk_count:
app.logger.warning(
f"Embedding identifier changed from {stored_identifier!r} to {current_identifier!r} "
@@ -759,6 +789,7 @@ def initialize_database(app):
setting_type='string',
)
app.logger.info(f"Updated embedding_identifier in system_setting: {stored_identifier!r} -> {current_identifier!r}")
+ # outcome == 'no-change': stored value already matches current; nothing to do.
except Exception as e:
db.session.rollback()
app.logger.warning(f"embedding_identifier compatibility check skipped: {e}")
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index f4bbb5ae..a40d98d5 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -52,6 +52,14 @@ VIDEO_RETENTION = os.environ.get('VIDEO_RETENTION', 'false').lower() == 'true'
_ERROR_MESSAGE_MAX_CHARS = 500
+def resolve_hotwords(hotwords, admin_default):
+ """Hotwords to use: an explicit value wins; otherwise the admin default
+ (or the original falsy value when there is no default)."""
+ if hotwords:
+ return hotwords
+ return admin_default or hotwords
+
+
def _sanitize_error_message(text):
"""Trim and redact a raw exception string before persisting on a
Recording so it stays useful but doesn't leak deployment paths or
@@ -1607,11 +1615,12 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file
current_app.logger.info(f"Using transcription connector: {connector_name}")
# Fall back to admin default hotwords if none provided
- if not hotwords:
- admin_hotwords = SystemSetting.get_setting('admin_default_hotwords', '')
- if admin_hotwords:
- hotwords = admin_hotwords
- current_app.logger.debug(f"Using admin default hotwords: {hotwords}")
+ resolved_hotwords = resolve_hotwords(
+ hotwords, SystemSetting.get_setting('admin_default_hotwords', '')
+ )
+ if resolved_hotwords != hotwords:
+ hotwords = resolved_hotwords
+ current_app.logger.debug(f"Using admin default hotwords: {hotwords}")
# Check transcription budget before processing
can_proceed, usage_pct, budget_msg = transcription_tracker.check_budget(recording.user_id)
diff --git a/tests/test_admin_hotwords_and_bugfixes.py b/tests/test_admin_hotwords_and_bugfixes.py
index 7f739247..05a47c93 100644
--- a/tests/test_admin_hotwords_and_bugfixes.py
+++ b/tests/test_admin_hotwords_and_bugfixes.py
@@ -75,42 +75,39 @@ def test_admin_default_hotwords():
def t3():
"""Admin hotwords only apply when user hotwords are empty (priority chain)."""
- # This tests the logic: if not hotwords -> use admin default
- # Simulate the processing.py logic
- with app.app_context():
- SystemSetting.set_setting('admin_default_hotwords', 'AdminWord1, AdminWord2')
+ # Assert the REAL pure helper extracted from src/tasks/processing.py
+ # rather than an inline copy of its logic.
+ from src.tasks.processing import resolve_hotwords
- # Case 1: User has hotwords - admin should NOT be used
- user_hotwords = 'UserWord1, UserWord2'
- hotwords = user_hotwords
- if not hotwords:
- admin_hotwords = SystemSetting.get_setting('admin_default_hotwords', '')
- if admin_hotwords:
- hotwords = admin_hotwords
- assert hotwords == 'UserWord1, UserWord2', "User hotwords should take priority"
-
- # Case 2: User has no hotwords - admin SHOULD be used
- user_hotwords = ''
- hotwords = user_hotwords
- if not hotwords:
- admin_hotwords = SystemSetting.get_setting('admin_default_hotwords', '')
- if admin_hotwords:
- hotwords = admin_hotwords
- assert hotwords == 'AdminWord1, AdminWord2', "Admin hotwords should be used as fallback"
-
- # Case 3: No user hotwords AND no admin hotwords
- SystemSetting.set_setting('admin_default_hotwords', '')
- user_hotwords = ''
- hotwords = user_hotwords
- if not hotwords:
- admin_hotwords = SystemSetting.get_setting('admin_default_hotwords', '')
- if admin_hotwords:
- hotwords = admin_hotwords
- assert hotwords == '', "Should remain empty when no hotwords at any level"
+ # Case 1: explicit user hotwords win, admin default ignored.
+ assert resolve_hotwords('UserWord1, UserWord2', 'AdminWord1, AdminWord2') == 'UserWord1, UserWord2', \
+ "User hotwords should take priority"
+
+ # Case 2: no user hotwords -> admin default used as fallback.
+ assert resolve_hotwords('', 'AdminWord1, AdminWord2') == 'AdminWord1, AdminWord2', \
+ "Admin hotwords should be used as fallback"
+
+ # Case 3: no user hotwords AND no admin default -> stays falsy.
+ assert resolve_hotwords('', '') == '', "Should remain empty when no hotwords at any level"
+ # Edge: None inputs preserve the original falsy value (no crash).
+ assert resolve_hotwords(None, '') is None
+ assert resolve_hotwords(None, 'AdminWord') == 'AdminWord'
+ run_test("Hotword priority chain: user > admin > none", t3)
+
+ def t4():
+ """End-to-end SystemSetting round-trip feeding the real helper."""
+ from src.tasks.processing import resolve_hotwords
+ with app.app_context():
+ SystemSetting.set_setting('admin_default_hotwords', 'AdminWord1, AdminWord2')
+ admin_default = SystemSetting.get_setting('admin_default_hotwords', '')
+ assert resolve_hotwords('', admin_default) == 'AdminWord1, AdminWord2'
+ assert resolve_hotwords('UserWord', admin_default) == 'UserWord'
# Clean up
SystemSetting.set_setting('admin_default_hotwords', '')
- run_test("Hotword priority chain: user > admin > none", t3)
+ empty_default = SystemSetting.get_setting('admin_default_hotwords', '')
+ assert resolve_hotwords('', empty_default) == ''
+ run_test("Hotword resolution via SystemSetting round-trip", t4)
# =============================================================================
diff --git a/tests/test_embedding_identifier_compat.py b/tests/test_embedding_identifier_compat.py
index b3acb126..df92e6b1 100644
--- a/tests/test_embedding_identifier_compat.py
+++ b/tests/test_embedding_identifier_compat.py
@@ -81,26 +81,22 @@ def restore_env(saved):
def run_compat_check():
- """Replays the inline migration block from src/init_db.py."""
+ """Drives the REAL pure decision function extracted from src/init_db.py
+ using live SystemSetting values, so this is a true integration check of the
+ function the startup path calls (not an inline copy of its logic)."""
from src.app import app
- from src.models import SystemSetting, TranscriptChunk
+ from src.models import SystemSetting
from src.services.embeddings import EMBEDDING_IDENTIFIER
+ from src.init_db import classify_embedding_identifier_state
with app.app_context():
current = EMBEDDING_IDENTIFIER
- stored = SystemSetting.get_setting('embedding_identifier', None)
+ raw_stored = SystemSetting.get_setting('embedding_identifier', None)
legacy = SystemSetting.get_setting('embedding_model_name', None)
- migrated_from_legacy = False
- if stored is None and legacy:
- stored = f"local::{legacy}"
- migrated_from_legacy = True
-
- if stored is None:
- outcome = 'first-run'
- elif stored == current:
- outcome = 'silent-migration' if migrated_from_legacy else 'no-change'
- else:
- outcome = 'warn-mismatch'
+
+ stored, migrated_from_legacy, outcome = classify_embedding_identifier_state(
+ current, raw_stored, legacy
+ )
return {
'stored': stored,