Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
One Markdown instance per thread (#442)
Murtaza Nasira46e550b25d2
diff --git a/src/app.py b/src/app.pyindex f0096f99..5162f4a6 100644--- a/src/app.py+++ b/src/app.py@@ -20,7 +20,6 @@ import httpximport reimport subprocessimport mimetypes-import markdownimport bleach# Add common audio MIME type mappings that might be missing@@ -160,19 +159,6 @@ root_logger.addHandler(handler)markdown_logger = logging.getLogger('MARKDOWN')markdown_logger.setLevel(logging.WARNING)-# --- Initialize Markdown Once (Performance Optimization) ----# Create a single reusable Markdown instance to avoid reinitializing extensions on every call-_markdown_instance = markdown.Markdown(extensions=[- 'fenced_code', # Fenced code blocks- 'tables', # Table support- 'attr_list', # Attribute lists- 'def_list', # Definition lists- 'footnotes', # Footnotes- 'abbr', # Abbreviations- 'codehilite', # Syntax highlighting for code blocks- 'smarty' # Smart quotes, dashes, etc.-])-# --- Rate Limiting Setup (will be configured after app creation) ---# RATELIMIT_ENABLED (default true) lets the test suite and any deployment that# fronts its own rate limiting turn Flask-Limiter off. The per-endpoint authdiff --git a/src/utils/markdown.py b/src/utils/markdown.pyindex f7a86495..b45d55e6 100644--- a/src/utils/markdown.py+++ b/src/utils/markdown.py@@ -6,12 +6,11 @@ sanitizing HTML to prevent XSS and other security issues."""import re+import threadingimport markdownimport bleach-# --- Initialize Markdown Once (Performance Optimization) ----# Create a single reusable Markdown instance to avoid reinitializing extensions on every call-_markdown_instance = markdown.Markdown(extensions=[+_EXTENSIONS = ['fenced_code', # Fenced code blocks'tables', # Table support'attr_list', # Attribute lists@@ -20,7 +19,19 @@ _markdown_instance = markdown.Markdown(extensions=['abbr', # Abbreviations'codehilite', # Syntax highlighting for code blocks'smarty' # Smart quotes, dashes, etc.-])+]++# A Markdown instance keeps state while it converts, so one instance shared by+# the request threads mixed the HTML of concurrent conversions (#442). Each+# thread builds its own instance once and reuses it.+_local = threading.local()+++def _markdown():+ md = getattr(_local, 'md', None)+ if md is None:+ md = _local.md = markdown.Markdown(extensions=_EXTENSIONS)+ return mddef sanitize_html(text):@@ -123,10 +134,10 @@ def md_to_html(text):# Fix list spacingprocessed_text = fix_list_spacing(text)- # Convert markdown to HTML using the pre-configured singleton instance- # Reset the instance to clear any state from previous conversions- _markdown_instance.reset()- html = _markdown_instance.convert(processed_text)+ # Reset the thread's instance to clear any state from its previous conversion+ md = _markdown()+ md.reset()+ html = md.convert(processed_text)# Apply sanitization to the generated HTMLreturn _with_auto_direction(sanitize_html(html))diff --git a/tests/test_markdown_threads.py b/tests/test_markdown_threads.pynew file mode 100644index 00000000..b6933dd7--- /dev/null+++ b/tests/test_markdown_threads.py@@ -0,0 +1,42 @@+"""Markdown conversion from several request threads at once (#442).++One Markdown instance was shared by all threads; its state (footnotes,+abbreviations, the output tree) is reset and filled during a conversion, so+concurrent conversions returned each other's HTML.+"""+import threading++from src.utils.markdown import md_to_html+++def _doc(n):+ return (f"# Summary {n}\n\nPoint {n} of the meeting.[^{n}]\n\n"+ f"*[ACME{n}]: Company {n}\n\nACME{n} agreed.\n\n[^{n}]: Footnote {n}.\n")+++def test_concurrent_conversions_match_single_thread():+ expected = {n: md_to_html(_doc(n)) for n in range(8)}+ mismatches, errors = [], []++ def work(n):+ for _ in range(60):+ try:+ if md_to_html(_doc(n)) != expected[n]:+ mismatches.append(n)+ except Exception as e: # noqa: BLE001 - any exception is a failure here+ errors.append(repr(e))++ threads = [threading.Thread(target=work, args=(n,)) for n in range(8)]+ for t in threads:+ t.start()+ for t in threads:+ t.join()+ assert not errors+ assert not mismatches+++def test_footnotes_do_not_carry_over():+ first = md_to_html("A[^1]\n\n[^1]: one")+ second = md_to_html("B without notes")+ assert "one" in first+ assert "footnote" not in second