Skip to content

fix: avoid redundant Lark private chat route writes - #11618

Open
Entropy-Enthalpy wants to merge 2 commits into
AstrBotDevs:masterfrom
Entropy-Enthalpy:fix/lark-private-chat-preference-writes
Open

Entropy-Enthalpy wants to merge 2 commits into
AstrBotDevs:masterfrom
Entropy-Enthalpy:fix/lark-private-chat-preference-writes

Conversation

@Entropy-Enthalpy

@Entropy-Enthalpy Entropy-Enthalpy commented Dec 2, 2026 •

Copy link
Copy Markdown

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

python -m pytest -q tests/unit/test_shared_preferences.py tests/test_lark_private_chat_fallback.py tests/test_lark_sender_name.py tests/unit/test_astrbot_config_manager.py tests/unit/test_session_overrides.py
ruff format --check .
ruff check .

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

  • Existing callers retain their public interfaces.
  • Verification steps and results are included.
  • The change is internal to the Lark receiver and preference writer. Existing WebUI instructions and screenshots still apply.
  • No new dependencies.

Summary by Sourcery

Skip redundant persistence work for unchanged Lark private-chat routes while retaining reliable write ordering and retry behavior.

Bug Fixes:

  • Avoid repeated preference writes and database lookups for unchanged Lark private-chat routes while ensuring messages wait for the route write to persist.

Enhancements:

  • Preserve FIFO ordering for preference writes submitted from both synchronous callers and the event loop.

Tests:

  • Add coverage for concurrent waiters, failed-write retries, changed and deleted routes, store reopening, and cross-thread write ordering.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread tests/unit/test_shared_preferences.py Resolved

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant