Repository navigation
fix: avoid redundant Lark private chat route writes - #11618
Open
Entropy-Enthalpy wants to merge 2 commits into
Open
Entropy-Enthalpy wants to merge 2 commits into
Entropy-Enthalpy wants to merge 2 commits into
Conversation
Contributor
There was a problem hiding this comment.
Hey - I've found 4 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="astrbot/core/utils/shared_preferences.py" line_range="455-461" />
<code_context>
+ with self._cache_lock:
+ cached = self._cache.get(address)
+ if (
+ isinstance(cached, _StringWrite)
+ and cached.value == value
+ and cached.completion.get_loop() is loop
+ and not cached.completion.cancelled()
+ and (
+ not cached.completion.done()
+ or cached.completion.exception() is None
+ )
+ ):
</code_context>
<issue_to_address>
**Route waiters hang after writer cancellation**
When the writer task is cancelled while a string write is being persisted and later messages ensure that same route, `_drain_write_queue` does not catch `asyncio.CancelledError`, so cancellation during persistence reaches `task_done()` without completing the cached future. Later calls with the same value reuse that still-pending future and wait indefinitely, leaving Lark messages unprocessed.
Resolve or invalidate the cached completion when the writer is cancelled so a later ensure call can retry instead of sharing a future that will never finish.
</issue_to_address>
### Comment 2
<location path="tests/unit/test_shared_preferences.py" line_range="99" />
<code_context>
+ await reopened.ensure_string(*key, "room-c")
+ await reopened.remove_async(*key)
+ await reopened.ensure_string(*key, "room-c")
+ assert writes[-2:] == ["room-c", "room-c"]
+ assert (await database.get_preference(*key)).value == {"val": "room-c"}
+ finally:
</code_context>
<issue_to_address>
**Deletion is not verified**
When `remove_async` fails to remove the reopened store's cached entry, `test_ensured_string_preserves_commit_order_and_retries_failures` still passes if `remove_async` is a no-op: the reopened store's earlier `ensure_string` already adds a `room-c` write, and `writes[-2:]` matches the prior batch's final `room-c` plus that write.
Record the write count before removal and assert that the ensure after removal adds a write, or assert the preference is absent immediately after removal.
</issue_to_address>
### Comment 3
<location path="astrbot/core/utils/shared_preferences.py" line_range="29-30" />
<code_context>
+ completion: asyncio.Future[None]
+
+
+def _copy_cached(value: Any) -> Any:
+ return value.value if isinstance(value, _StringWrite) else deepcopy(value)
+
+
</code_context>
<issue_to_address>
**Cached write handling lacks explanation**
When a cache read encounters an `_StringWrite` entry, `_copy_cached` unwraps `_StringWrite` entries to expose only their value while deep-copying other cache entries, but has no comment or docstring explaining this distinction. The special cache-read behavior is harder to maintain.
Document why `_StringWrite` cache entries are unwrapped and why other entries are deep-copied.
</issue_to_address>
### Comment 4
<location path="astrbot/core/utils/shared_preferences.py" line_range="115-129" />
<code_context>
for target_id, target_value in value.items():
self._cache[(scope, target_id, key)] = deepcopy(target_value)
+ def _enqueue_pending_writes(self) -> None:
+ """Move submitted writes onto the owning loop's FIFO in order."""
+ queue = self._write_queue
+ if queue is None or self._loop is not asyncio.get_running_loop():
+ return
+ with self._cache_lock:
+ if not self._pending_writes:
+ return
+ for pending in self._pending_writes:
+ queue.put_nowait(pending)
+ self._pending_writes.clear()
+ if self._writer_task is None or self._writer_task.done():
+ self._writer_task = self._loop.create_task(
+ self._drain_write_queue(), name="shared_preferences_writer"
+ )
+
def _schedule_write(self, operation: _WriteOperation) -> None:
</code_context>
<issue_to_address>
**Queue flow gains unnecessary indirection**
When the helper is used only by `_schedule_write` and `flush`, `_enqueue_pending_writes` adds a helper used at only two sites, while `_schedule_write` and `flush` remain under 50 lines and the queue handling does not severely derail either flow. This violates the repository’s helper-extraction guidance and makes the write path harder to follow.
Inline the queue-enqueue logic in the callers unless a third use or a materially longer caller justifies the helper.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 2 findings to address first, and if the new write coalescing or ordering leaves a sender mapped to the wrong Lark chat, replies can be sent to an unintended recipient; reverting would not recall messages already sent. The stored route can be corrected afterward, but that does not undo the exposure.
Blocking findings: astrbot/core/utils/shared_preferences.py:461, tests/unit/test_shared_preferences.py:99
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Every incoming Lark direct message waits for the shared-preference writer to save the sender's private chat ID before it reaches the message queue. Even when the ID is unchanged, SQLite still looks up the row. Repeated messages can therefore wait behind unrelated preference writes.
Changes
Verification
All 70 tests passed. The new cases cover concurrent waiters on a failed write, retry, address changes, deletion, reopening the store, and a synchronous caller on another thread. Ruff reported 606 files formatted and no lint errors.
A local component check passed synthetic messages through the native Lark private-message conversion with file-backed SQLite. For 16 first-seen addresses, both versions issued 16 lookups and 16 writes. All four address changes were persisted. For 64 subsequent messages with unchanged addresses, database lookups fell from 64 to zero and all 64 messages reached the queue.
Checklist
Summary by Sourcery
Skip redundant persistence work for unchanged Lark private-chat routes while retaining reliable write ordering and retry behavior.
Bug Fixes:
Enhancements:
Tests: