Skip to content

Commit b8cd04e

Browse files
authored
fix: stop preloading entire preferences table into memory (#9747)
* fix: stop preloading entire preferences table into memory PR #9649 fixed an event-loop deadlock by preloading every row of the preferences table into an in-memory mirror at startup. The table can hold gigabytes of plugin KV data, so this can OOM the process. - initialize() no longer performs an unfiltered get_preferences(); the in-memory cache becomes a write overlay for read-after-write visibility only - get_async() falls back to an async point query on overlay miss and never backfills the overlay - deprecated sync get() falls back to a point query through a dedicated synchronous SQLite connection (the new SQLiteDatabase.get_preference_sync), so it never blocks on or deadlocks against the async pool; failures warn and return the default instead of raising - sync range_get() now only covers values written by this process (no internal callers remain); full scans stay available via range_get_async() - FIFO write queue semantics are unchanged * fix: preserve synchronous preference range reads
1 parent 9c89583 commit b8cd04e

3 files changed

Lines changed: 311 additions & 48 deletions

File tree

‎astrbot/core/db/sqlite.py‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import asyncio
22
import json
3+
import sqlite3
34
import threading
45
import typing as T
56
from collections.abc import Awaitable, Callable
67
from datetime import datetime, timedelta, timezone
8+
from pathlib import Path
79

810
from deprecated import deprecated
911
from sqlalchemy import CursorResult, Row, not_
@@ -1379,6 +1381,97 @@ async def get_preference(self, scope, scope_id, key):
13791381
result = await session.execute(query)
13801382
return result.scalar_one_or_none()
13811383

1384+
def get_preference_sync(
1385+
self,
1386+
scope: str,
1387+
scope_id: str,
1388+
key: str,
1389+
) -> dict | None:
1390+
"""Synchronous point query for a single preference value.
1391+
1392+
Uses a dedicated stdlib sqlite3 connection instead of the async
1393+
SQLAlchemy pool, so deprecated synchronous SharedPreferences APIs never
1394+
wait on (or deadlock against) the event-loop-owned pool. The database
1395+
runs in WAL mode, so this short index lookup can read concurrently with
1396+
the async writer.
1397+
1398+
Args:
1399+
scope: Preference scope.
1400+
scope_id: Identifier within the preference scope.
1401+
key: Preference key.
1402+
1403+
Returns:
1404+
The stored value dict (e.g. ``{"val": ...}``), or None if missing.
1405+
"""
1406+
conn = sqlite3.connect(Path(self.db_path), timeout=30)
1407+
try:
1408+
row = conn.execute(
1409+
"SELECT value FROM preferences "
1410+
"WHERE scope = ? AND scope_id = ? AND key = ?",
1411+
(scope, scope_id, key),
1412+
).fetchone()
1413+
if row is None:
1414+
return None
1415+
value = row[0]
1416+
return (
1417+
json.loads(value)
1418+
if isinstance(value, (str, bytes, bytearray))
1419+
else value
1420+
)
1421+
finally:
1422+
conn.close()
1423+
1424+
def get_preferences_sync(
1425+
self,
1426+
scope: str,
1427+
scope_id: str | None = None,
1428+
key: str | None = None,
1429+
) -> list[Preference]:
1430+
"""Synchronously query preferences within a scope.
1431+
1432+
This compatibility path uses a dedicated sqlite3 connection instead of
1433+
the async SQLAlchemy pool. It only loads the range explicitly requested
1434+
by the deprecated synchronous API and is never called during startup.
1435+
1436+
Args:
1437+
scope: Preference scope to query.
1438+
scope_id: Optional identifier within the scope.
1439+
key: Optional preference key.
1440+
1441+
Returns:
1442+
Preferences matching the supplied filters.
1443+
"""
1444+
query = "SELECT scope, scope_id, key, value FROM preferences WHERE scope = ?"
1445+
params: list[str] = [scope]
1446+
if scope_id is not None:
1447+
query += " AND scope_id = ?"
1448+
params.append(scope_id)
1449+
if key is not None:
1450+
query += " AND key = ?"
1451+
params.append(key)
1452+
1453+
conn = sqlite3.connect(Path(self.db_path), timeout=30)
1454+
try:
1455+
rows = conn.execute(query, params).fetchall()
1456+
preferences = []
1457+
for row_scope, row_scope_id, row_key, row_value in rows:
1458+
value = (
1459+
json.loads(row_value)
1460+
if isinstance(row_value, (str, bytes, bytearray))
1461+
else row_value
1462+
)
1463+
preferences.append(
1464+
Preference(
1465+
scope=row_scope,
1466+
scope_id=row_scope_id,
1467+
key=row_key,
1468+
value=value,
1469+
)
1470+
)
1471+
return preferences
1472+
finally:
1473+
conn.close()
1474+
13821475
async def get_preferences(self, scope=None, scope_id=None, key=None):
13831476
"""Get preferences, optionally filtered by scope, scope ID, or key."""
13841477
async with self.get_db() as session:

‎astrbot/core/utils/shared_preferences.py‎

Lines changed: 115 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,18 @@ def __init__(self, db_helper: BaseDatabase, json_storage_path=None) -> None:
3838
self.temporary_cache: dict[str, dict[str, Any]] = defaultdict(dict)
3939
"""automatically clear per 24 hours. Might be helpful in some cases XD"""
4040

41-
# In-memory mirror of persistent preferences. It lets synchronous APIs
42-
# read and update values without blocking on the async database, provides
43-
# immediate read-after-write visibility, and also serves async point reads.
44-
# Unlike temporary_cache, it is preloaded at startup, persisted to the
45-
# database, and never periodically cleared by the scheduler.
46-
# See https://github.com/AstrBotDevs/AstrBot/pull/9649 for the deadlock
47-
# scenario and design rationale.
41+
# In-memory overlay of preferences written through this process. It gives
42+
# read-after-write visibility for both sync and async APIs while writes
43+
# are asynchronously persisted through the FIFO write queue.
44+
#
45+
# This is intentionally NOT a full mirror of the preferences table: the
46+
# table can hold gigabytes of plugin KV data, so preloading it at startup
47+
# (as PR #9649 did) can OOM the process. Reads that miss the overlay fall
48+
# back to point queries against the database: async reads await the async
49+
# engine, while deprecated synchronous reads use a dedicated sync SQLite
50+
# connection so they never block on (or deadlock against) the async pool.
51+
# See https://github.com/AstrBotDevs/AstrBot/pull/9649 for the original
52+
# deadlock scenario and design rationale.
4853
self._cache: dict[tuple[str, str, str], Any] = {}
4954
self._cache_lock = threading.RLock()
5055
self._cache_initialized = False
@@ -54,6 +59,8 @@ def __init__(self, db_helper: BaseDatabase, json_storage_path=None) -> None:
5459
self._write_queue: asyncio.Queue[_WriteOperation] | None = None
5560
self._writer_task: asyncio.Task[None] | None = None
5661
self._pending_writes: list[_WriteOperation] = []
62+
self._warned_sync_read_unsupported = False
63+
self._warned_sync_range_read_unsupported = False
5764

5865
self._scheduler = BackgroundScheduler()
5966
self._scheduler.add_job(
@@ -173,7 +180,10 @@ async def _drain_write_queue(self) -> None:
173180
queue.task_done()
174181

175182
async def initialize(self) -> None:
176-
"""Load persisted preferences and bind writes to the current event loop.
183+
"""Bind writes to the current event loop and replay pending writes.
184+
185+
The preferences table is intentionally NOT preloaded here: it can be
186+
arbitrarily large, and reads fall back to point queries instead.
177187
178188
Raises:
179189
RuntimeError: If another running event loop already owns the store.
@@ -205,23 +215,13 @@ async def initialize(self) -> None:
205215
self._loop = loop
206216
self._write_queue = asyncio.Queue()
207217
self._writer_task = None
208-
if not self._cache_initialized:
209-
preferences = await self.db_helper.get_preferences()
210-
loaded_cache = {
211-
(item.scope, item.scope_id, item.key): deepcopy(
212-
item.value["val"]
213-
)
214-
for item in preferences
215-
}
216218

217219
with self._cache_lock:
218220
pending_writes = list(self._pending_writes)
219221
self._pending_writes.clear()
220-
if not self._cache_initialized:
221-
self._cache = loaded_cache
222-
for operation in pending_writes:
223-
self._apply_cache_operation(operation)
224-
self._cache_initialized = True
222+
for operation in pending_writes:
223+
self._apply_cache_operation(operation)
224+
self._cache_initialized = True
225225
self._initializing = False
226226
except BaseException:
227227
with self._cache_lock:
@@ -277,7 +277,12 @@ async def get_async(
277277
return default
278278
with self._cache_lock:
279279
value = self._cache.get((scope, scope_id, key), _MISSING)
280-
return default if value is _MISSING else deepcopy(value)
280+
if value is not _MISSING:
281+
return deepcopy(value)
282+
preference = await self.db_helper.get_preference(scope, scope_id, key)
283+
if preference is None:
284+
return default
285+
return deepcopy(preference.value["val"])
281286

282287
async def range_get_async(
283288
self,
@@ -439,12 +444,41 @@ def get(
439444
raise ValueError(
440445
"scope_id and key cannot be None when getting a specific preference.",
441446
)
447+
resolved_scope = scope or "unknown"
448+
resolved_scope_id = scope_id or "unknown"
442449
with self._cache_lock:
443-
value = self._cache.get(
444-
(scope or "unknown", scope_id or "unknown", key),
445-
_MISSING,
450+
value = self._cache.get((resolved_scope, resolved_scope_id, key), _MISSING)
451+
if value is not _MISSING:
452+
return default if value is None else deepcopy(value)
453+
# Overlay miss: fall back to a point query through a dedicated
454+
# synchronous database connection. This briefly blocks the calling
455+
# thread (unavoidable for a synchronous API), but never touches the
456+
# async connection pool, so it cannot deadlock the event loop.
457+
get_sync = getattr(self.db_helper, "get_preference_sync", None)
458+
if get_sync is None:
459+
if not self._warned_sync_read_unsupported:
460+
self._warned_sync_read_unsupported = True
461+
logger.warning(
462+
"SharedPreferences sync get() is not supported by database "
463+
"backend %s; returning the default. Use get_async() instead.",
464+
type(self.db_helper).__name__,
465+
)
466+
return default
467+
try:
468+
stored = get_sync(resolved_scope, resolved_scope_id, key)
469+
except Exception as exc:
470+
logger.warning(
471+
"SharedPreferences sync get() failed for %s/%s/%s: %s",
472+
resolved_scope,
473+
resolved_scope_id,
474+
key,
475+
exc,
446476
)
447-
return default if value is _MISSING or value is None else deepcopy(value)
477+
return default
478+
if stored is None:
479+
return default
480+
value = stored.get("val")
481+
return default if value is None else deepcopy(value)
448482

449483
@deprecated(version="4.0.0", reason="Use range_get_async() instead.")
450484
def range_get(
@@ -453,28 +487,62 @@ def range_get(
453487
scope_id: str | None = None,
454488
key: str | None = None,
455489
) -> list[Preference]:
456-
"""获取指定范围的偏好设置(已弃用)"""
490+
"""Synchronously get preferences matching the supplied range.
491+
492+
Historical values are loaded on demand through a dedicated synchronous
493+
database connection, then values written by this process are overlaid to
494+
preserve immediate read-after-write visibility without startup preload.
495+
496+
Args:
497+
scope: Preference scope to query.
498+
scope_id: Optional identifier within the scope.
499+
key: Optional preference key.
500+
501+
Returns:
502+
Preferences matching the supplied filters.
503+
"""
504+
get_sync = getattr(self.db_helper, "get_preferences_sync", None)
505+
if get_sync is None:
506+
if not self._warned_sync_range_read_unsupported:
507+
self._warned_sync_range_read_unsupported = True
508+
logger.warning(
509+
"SharedPreferences sync range_get() is not supported by "
510+
"database backend %s; returning process-local values only. "
511+
"Use range_get_async() instead.",
512+
type(self.db_helper).__name__,
513+
)
514+
persisted: list[Preference] = []
515+
else:
516+
try:
517+
persisted = get_sync(scope, scope_id, key)
518+
except Exception as exc:
519+
logger.warning(
520+
"SharedPreferences sync range_get() failed for %s/%s/%s: %s",
521+
scope,
522+
scope_id,
523+
key,
524+
exc,
525+
)
526+
persisted = []
527+
528+
values = {
529+
(preference.scope, preference.scope_id, preference.key): preference
530+
for preference in persisted
531+
}
457532
with self._cache_lock:
458-
values = [
459-
(cache_scope, cache_scope_id, cache_key, deepcopy(value))
460-
for (
461-
cache_scope,
462-
cache_scope_id,
463-
cache_key,
464-
), value in self._cache.items()
465-
if cache_scope == scope
466-
and (scope_id is None or cache_scope_id == scope_id)
467-
and (key is None or cache_key == key)
468-
]
469-
return [
470-
Preference(
471-
scope=cache_scope,
472-
scope_id=cache_scope_id,
473-
key=cache_key,
474-
value={"val": value},
475-
)
476-
for cache_scope, cache_scope_id, cache_key, value in values
477-
]
533+
for (cache_scope, cache_scope_id, cache_key), value in self._cache.items():
534+
if (
535+
cache_scope == scope
536+
and (scope_id is None or cache_scope_id == scope_id)
537+
and (key is None or cache_key == key)
538+
):
539+
values[(cache_scope, cache_scope_id, cache_key)] = Preference(
540+
scope=cache_scope,
541+
scope_id=cache_scope_id,
542+
key=cache_key,
543+
value={"val": deepcopy(value)},
544+
)
545+
return list(values.values())
478546

479547
@deprecated(
480548
version="4.0.0",

0 commit comments

Comments
 (0)