Repository navigation
Conversation
|
Pre-existing failure evidence — referenced in the PR description as "the first comment". Evidence: the 41 full-suite failures are pre-existing on unmodified masterTwo full-suite runs were executed with the exact same command, on the same machine and environment:
The 41 failed test IDs are identical in both runs (diff of the two FAILED lists is empty); the only difference in passed count is +19, exactly the 19 tests added by this PR. All 26 collection errors are
Per-file failure counts (identical in both runs)
The 41 failing test IDs (same list in both runs)Collection errors (26, identical in both runs)All are
Full raw logs are retained locally ( Benchmark script — referenced in the Notes section of the PR description: """Benchmark: guarded cleanup DELETE with NOT EXISTS, conversations without a user_id index.
Reproduces the number quoted in the PR Notes:
- 100,000 conversation rows, no user_id index
- per-cleanup median / p95 over 200 runs (SQLite, WAL)
Run: python 基准_索引notexists_benchmark.py
"""
import os
import sqlite3
import statistics
import tempfile
import time
def main() -> None:
n_rows = 100_000
n_umos = 1000
runs = 200
db = os.path.join(tempfile.gettempdir(), "bench_cleanup.db")
for suffix in ("", "-wal", "-shm"):
try:
os.remove(db + suffix)
except FileNotFoundError:
pass
con = sqlite3.connect(db)
cur = con.cursor()
cur.execute("PRAGMA journal_mode=WAL")
cur.execute(
"CREATE TABLE conversations ("
"inner_conversation_id INTEGER PRIMARY KEY, user_id TEXT, "
"created_at DATETIME, updated_at DATETIME)"
)
cur.execute("CREATE TABLE umo_aliases (id INTEGER PRIMARY KEY, umo TEXT UNIQUE)")
cur.execute("CREATE TABLE umo_senders (id INTEGER PRIMARY KEY, umo TEXT)")
cur.executemany(
"INSERT INTO conversations (inner_conversation_id,user_id,created_at,updated_at) "
"VALUES (?,?,?,?)",
(
(i, f"qq:GroupMessage:{i % n_umos}", "2026-10-26", "2026-10-26")
for i in range(n_rows)
),
)
cur.executemany(
"INSERT INTO umo_aliases (umo) VALUES (?)",
((f"orphan:{i}",) for i in range(runs)),
)
con.commit()
plan = cur.execute(
"EXPLAIN QUERY PLAN DELETE FROM umo_aliases WHERE umo=? "
"AND NOT EXISTS (SELECT 1 FROM conversations WHERE user_id=?)",
("x", "x"),
).fetchall()
print("plan:", plan)
times = []
for i in range(runs):
umo = f"orphan:{i}"
t0 = time.perf_counter()
cur.execute(
"DELETE FROM umo_aliases WHERE umo=? "
"AND NOT EXISTS (SELECT 1 FROM conversations WHERE user_id=?)",
(umo, umo),
)
times.append((time.perf_counter() - t0) * 1000)
con.commit()
print(
f"rows={n_rows} runs={runs} "
f"median_ms={statistics.median(times):.3f} "
f"p95_ms={sorted(times)[int(runs * 0.95)]:.3f} "
f"min_ms={min(times):.3f} max_ms={max(times):.3f}"
)
con.close()
if __name__ == "__main__":
main() |
There was a problem hiding this comment.
Hey - I've found 1 issue
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="astrbot/dashboard/services/conversation_service.py" line_range="353-356" />
<code_context>
+ Conversations are already deleted when this runs, so a cleanup error
+ is reported as a structured field instead of a failed request.
+ """
+ try:
+ return await self._cleanup_orphaned_metadata(umos)
+ except Exception as exc:
+ logger.warning(f"清理会话元数据失败: {exc!s}")
+ return {
+ "deleted_aliases": 0,
</code_context>
<issue_to_address>
**Cleanup error handling is extracted**
When metadata cleanup raises an exception, `_safe_cleanup_metadata` handles the cleanup exception and logs it outside the single- and batch-delete main function blocks, contrary to the required placement of error handling and logging.
Handle the cleanup exception and logging directly in the single- and batch-delete main function blocks.
</issue_to_address>Sourcery assessment
Needs a human reviewer. With cleanup enabled, alias and sender metadata rows for sessions without remaining conversations are permanently deleted; reverting the code will not restore customized values. The deletion is opt-in and limited to those sessions, so the unrecoverable loss is bounded.
d51fa61 to
d83e557
Compare
There was a problem hiding this comment.
Linked issues
#10704 [Feature] 提供 delete_umo_alias 官方方法,避免会话删除后别名数据成为孤儿 · 1 of 2 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Expose an official per-UMO alias deletion method (delete_umo_alias(umo) -> bool), or the accepted conversation-delete cascade alternative. |
🟡 Partly met | The opt-in dashboard cleanup can remove orphan aliases, but there is no delete_umo_alias method or cascade option for external callers to use. |
| 2 | Keep the existing delete_conversations_by_user_id behavior unchanged. |
✅ Met |
| @abc.abstractmethod | ||
| async def delete_umo_metadata_if_unreferenced(self, umo: str) -> dict: | ||
| """Delete alias and sender metadata for a UMO without conversations. | ||
|
|
||
| The reference check and the deletions run as conditional statements in | ||
| a single transaction, so metadata is not deleted while a committed | ||
| conversation still references the UMO. | ||
|
|
||
| Args: | ||
| umo: Unified message origin whose orphaned metadata should be deleted. | ||
|
|
||
| Returns: | ||
| Mapping with ``alias_deleted`` (whether an alias row was removed), | ||
| ``senders_deleted`` (number of sender rows removed) and | ||
| ``retained`` (True when a conversation still references the UMO and | ||
| nothing was deleted). | ||
| """ | ||
| ... | ||
|
|
There was a problem hiding this comment.
🔴 Critical · Missing alias deletion API
The issue asks for an official delete_umo_alias(umo) -> bool method, or the stated cascade alternative. The change adds only delete_umo_metadata_if_unreferenced, which refuses to delete metadata while conversations exist and is only used by the dashboard cleanup flow, leaving the requested reusable API unavailable.
Prompt for AI agents
In `astrbot/core/db/__init__.py` at lines 897-915:
**Missing alias deletion API**
The issue asks for an official `delete_umo_alias(umo) -> bool` method, or the stated cascade alternative. The change adds only `delete_umo_metadata_if_unreferenced`, which refuses to delete metadata while conversations exist and is only used by the dashboard cleanup flow, leaving the requested reusable API unavailable.From #10704:
Expose an official per-UMO alias deletion method (`delete_umo_alias(umo) -> bool`), or the accepted conversation-delete cascade alternative.|
Rebased onto master ( This is a fork PR, so the workflows are stuck at |
d83e557 to
9dbc4af
Compare
Linked issuesChecked at commit e04b4b1 No linked issues found. |
| ... | ||
|
|
||
| @abc.abstractmethod | ||
| async def delete_umo_metadata_if_unreferenced(self, umo: str) -> dict: |
There was a problem hiding this comment.
🟡 Medium · Standalone alias deletion
The issue asks for an official per-UMO alias deletion method, or an equivalent cascade option. The new method only cleans metadata through conversation deletion and retains aliases while any conversation references the UMO, so callers cannot independently delete an alias.
Prompt for AI agents
In `astrbot/core/db/__init__.py` at line 914:
**Standalone alias deletion**
The issue asks for an official per-UMO alias deletion method, or an equivalent cascade option. The new method only cleans metadata through conversation deletion and retains aliases while any conversation references the UMO, so callers cannot independently delete an alias.From #10704:
Provide official per-UMO alias deletion or an equivalent cascade option.|
On Sourcery's "Missing alias deletion API" finding: this is intentional, per the two-layer split agreed in #10704.
Together, the two PRs fully cover #10704. |
…ency test - sync the delete_umo_metadata_if_unreferenced docstring with the PR wording - handle cleanup exceptions inside the single and batch delete blocks per AGENTS.md L73 and drop _safe_cleanup_metadata - assert the alias survives when a conversation remains after concurrent create/cleanup
… and reuse the shared confirm dialog - drop delete_umo_alias from the DB layer and its tests; the primitive stays with AstrBotDevs#10746, this PR only adds delete_umo_metadata_if_unreferenced, which does not depend on it - reuse ConfirmDialog with an optional checkbox on the workspace page instead of a bespoke dialog; askForConfirmationWithCheckbox keeps the existing askForConfirmation contract untouched - log cleanup failures with exc_info
9dbc4af to
e04b4b1
Compare
Motivation
Related to #10704. The DB primitive (
delete_umo_alias) is handled separately by #10746; this PR covers the conversation-delete cleanup layer.Deleting a conversation (single or batch) from Data & Logs → Conversations only removes the row from
conversations, leaving orphanedumo_aliases/umo_sendersrows that the UI offers no way to clean up. #10761 only covers deleting a whole bot, not an individual conversation.Following the two-layer plan in #10704 (comment), this PR adds an explicit, default-off cleanup option at the service layer on top of the precise primitive. Backward compatible:
cleanup_metadatadefaults tofalseon both single and batch delete paths.Relation to #10746
Per the agreed two-layer split, the
delete_umo_aliasprimitive belongs to #10746, and this PR no longer adds it (an earlier revision duplicated it — dropped in d83e557, rebased onto master 86c24e8). The only DB-layer addition here isdelete_umo_metadata_if_unreferenced, which is implemented independently and does not call the primitive, so this PR merges cleanly before or after #10746.Modifications
astrbot/core/db/__init__.py,sqlite.py)delete_umo_metadata_if_unreferenced(umo) -> dict: deletes the UMO's alias and sender metadata only when no conversation references it. Both DELETEs carry theNOT EXISTSguard in the statement itself, inside one transaction, so metadata is not deleted while a committed conversation still references the UMO. Returns{alias_deleted, senders_deleted, retained}.conversation_service.py)delete_conversationacceptscleanup_metadata(defaultFalse) for both single and batch paths.metadata_cleanup: {deleted_aliases, deleted_senders, retained_umos}; UMOs kept because other conversations still reference them are listed instead of reporting a plain success.errorfield and logged withexc_info.dashboard/api/conversations.py,schemas.py)cleanup_metadataquery parameter onDELETE /conversations/{id}and body field on batch delete; both default tofalse.openspec/openapi-v1.yaml,docs/public/openapi.jsonand the generated dashboard SDK are updated.ConfirmDialog(extended with an optional checkbox) instead of a bespoke dialog.askForConfirmationkeeps its existing contract; the newaskForConfirmationWithCheckboxonly returns{confirmed, checked}and falls back to a plain confirmation when a handler has no checkbox support.changelogs/unreleased.md).Screenshots or Test Results
Verification steps (local AstrBot 4.29.3):
umo_aliasesandumo_sendersare gone (row counts before/after).retained_umos.All four steps passed on local AstrBot 4.29.3 with sanitized test data. Screenshots are attached via GitHub's uploader (sanitized): the cleanup checkbox in the delete dialog, the list after cleanup, and same-UMO retention after deleting one of two conversations. Note: the workspace-page screenshot predates the switch to the shared
ConfirmDialog— the checkbox is now rendered inside that shared dialog; happy to re-shoot if needed.Tests:
tests/unit/test_conversation_metadata_cleanup.py: 17 tests (db / service / API); the twodelete_umo_aliasunit tests moved out with the primitive (covered by feat(db): add UMO alias deletion method #10746'stests/unit/test_umo_alias_deletion.py)86c24e8: targeted suite 17 passed;ruff check,ruff format --checkandvue-tsc --noEmitall pass on the rebased revisiondad255c: 4488 passed / 41 failed / 79 skipped / 26 collection errors vs 4469 passed / 41 failed / 79 skipped / 26 collection errors on unmodified master — the 41 failures and 26 collection errors are pre-existing environment issues (per-file counts and commands in the first comment);npm run buildand the i18n key check passed on that revisionChecklist
Notes
conversationshas no index onuser_id; theNOT EXISTSsubquery therefore scans the table. On a local SQLite database with 100,000 conversation rows, one guarded cleanup took ~4.8 ms median (p95 ~5.4 ms, 200 runs; measured with a local benchmark script included in the first comment). Conversation deletion is low-frequency; this PR does not change the schema.docs/zh/use/webui.mdanddocs/en/use/webui.md; neither mentions alias cleanup on conversation deletion. Changelog entry included inchangelogs/unreleased.md.Summary by Sourcery
Provide an opt-in, safely guarded cleanup path for UMO metadata when conversations are deleted.
New Features:
Bug Fixes:
Enhancements:
Documentation:
Tests: