@@ -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