Fix SQLite lock errors on /api/stats under concurrent writes.

Retry stats cache commits, serialize refresh, and fall back to read-only compute so the stats API does not return 500 when the database is briefly locked.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
dekun
2026-06-26 12:23:33 +08:00
parent d3955309d9
commit 508d85a282
3 changed files with 50 additions and 12 deletions
+15 -7
View File
@@ -45,7 +45,7 @@ from fee_specs import (
purge_non_ctp_fee_rates,
)
from nav_settings import NAV_TOGGLES, get_nav_items, nav_enabled, save_nav_items
from stats_engine import STATS_VIEWS, load_stats_cache, refresh_stats_cache
from stats_engine import STATS_VIEWS, build_all_stats, load_stats_cache, refresh_stats_cache
from kline_store import ensure_kline_tables
from kline_stream import kline_hub, sse_format
from kline_chart import generate_review_kline_chart, fetch_market_klines, MARKET_PERIODS
@@ -230,12 +230,20 @@ def touch_stats_cache():
def get_stats_data() -> dict:
conn = get_db()
capital = float(get_setting("live_capital", "0") or 0)
data = load_stats_cache(conn)
if not data:
data = refresh_stats_cache(conn, capital)
conn.close()
return data
try:
capital = float(get_setting("live_capital", "0") or 0)
data = load_stats_cache(conn)
if data:
return data
try:
return refresh_stats_cache(conn, capital)
except sqlite3.OperationalError as exc:
if "locked" not in str(exc).lower():
raise
app.logger.warning("stats cache refresh locked, compute without save: %s", exc)
return build_all_stats(conn, capital)
finally:
conn.close()
def init_db():