From c2b01943da30aa211a32f680a2c78a6cc9764aaf Mon Sep 17 00:00:00 2001 From: Vito Sansevero Date: Sun, 22 Nov 2026 04:44:11 -0800 Subject: [PATCH] feat(maintenance): tag cleanup rules, find job and plan (#618) database/tag_cleanup.py holds a registry of tag rules; two ship: tags containing a comma (never a lora: tag; removed from every owner and deleted) and tags with no links (deleted). A tag belongs to the first rule that finds it. POST /prompt_manager/jobs/tag_cleanup runs the find as a read job that holds its findings; GET /prompt_manager/maintenance/tag_cleanup/{job_id} answers every rule with them; the tag_cleanup preview plans only the ticked findings, protecting any changed since the search. The apply is the maintenance job Tag cleanup: always after a safety backup, it rechecks each tag in one transaction and keeps, with its reason, each one that changed while the rest still apply. delete_vocabulary_tag and the rules share the new connection-level _delete_tag. --- database/maintenance.py | 17 + database/operations.py | 26 +- database/tag_cleanup.py | 440 +++++++++++++++++++ database/vocabulary.py | 35 +- py/api/__init__.py | 7 + py/api/jobs.py | 4 + py/api/maintenance.py | 73 ++- py/api/tag_cleanup.py | 245 +++++++++++ tests/fixtures/legacy_contract_snapshot.json | 2 + tests/test_api_tag_cleanup.py | 369 ++++++++++++++++ tests/test_maintenance_plans.py | 28 ++ tests/test_tag_cleanup.py | 432 ++++++++++++++++++ tests/test_vocabulary.py | 12 + tests/trash_route_audit.py | 3 + 14 files changed, 1659 insertions(+), 34 deletions(-) create mode 100644 database/tag_cleanup.py create mode 100644 py/api/tag_cleanup.py create mode 100644 tests/test_api_tag_cleanup.py create mode 100644 tests/test_tag_cleanup.py diff --git a/database/maintenance.py b/database/maintenance.py index d33abec4..d1c0da0c 100644 --- a/database/maintenance.py +++ b/database/maintenance.py @@ -19,6 +19,10 @@ Pair prompts' empty category and tags, live in their own modules): It also forgets the removal marks (#480) that hide nothing any more: the file is gone or changed, under a readable source (#501, ``_stale_marks``). +#618's ``tag_cleanup`` (``database/tag_cleanup.py``) is planned from a tag +search's findings, never previewed here; its apply rechecks each target and +keeps the ones that changed instead of refusing the whole plan. + ``preview_maintenance`` reads one snapshot on its own ``mode=ro`` connection (``health.readonly_uri``) and closes it in ``finally``; files are looked at after the snapshot ended. It returns a ``MaintenanceDraft``: the public plan @@ -64,6 +68,9 @@ MAINTENANCE_OPERATIONS = ( # #550: fill old Pair prompts' empty category and tags # (database/pair_metadata_repair.py). "pair_metadata", + # #618: tags to clean up, found by a job and planned from its findings + # (database/tag_cleanup.py); never previewed without them. + "tag_cleanup", ) MAX_DETAILS = 50 # detail rows a plan lists MAX_RESULT_ROWS = 200 # changed records an apply describes (the job lists 200) @@ -574,6 +581,9 @@ class MaintenanceOperations: """ if operation not in MAINTENANCE_OPERATIONS: raise ValueError(f"Unknown maintenance operation {operation!r}") + if operation == "tag_cleanup": + # Planned from a find's findings (tag_cleanup.plan_tag_cleanup). + raise ValueError("tag_cleanup is planned from a tag search") roots = [str(root) for root in roots] if operation == "optimize": return self._plan_optimize() @@ -867,6 +877,8 @@ class MaintenanceOperations: prompt operations also return ``kept``: every prompt the plan keeps, ``{prompt_id, reasons}`` in the review's wording (#550, #586); the links a missing-links plan keeps are read by ``kept_links``. + ``tag_cleanup`` (#618) does not compare the fingerprint: it rechecks + each target and returns every deleted and kept tag, uncapped. """ if operation not in MAINTENANCE_OPERATIONS or operation == "workflow_storage": raise ValueError(f"Unknown maintenance operation {operation!r}") @@ -885,6 +897,11 @@ class MaintenanceOperations: from .pair_metadata_repair import apply_pair_metadata return apply_pair_metadata(conn, fingerprint, targets) + if operation == "tag_cleanup": + # #618: each target is rechecked; a changed one is kept. + from .tag_cleanup import apply_tag_cleanup + + return apply_tag_cleanup(conn, targets) if operation == "missing_links": return self._apply_missing_links( conn, fingerprint, targets, roots, list(marks) diff --git a/database/operations.py b/database/operations.py index 678079c8..df980dbe 100644 --- a/database/operations.py +++ b/database/operations.py @@ -26,7 +26,7 @@ from .review_decisions import ReviewDecisionOperations from .saved_views import SavedViewOperations from .library_commands import LibraryCommandOperations from .library_archive import LibraryArchiveOperations, delete_prompt_rows -from .vocabulary import VocabularyOperations +from .vocabulary import VocabularyOperations, bump_image_tag_bytes from .execution_history import ExecutionHistoryOperations from .execution_contexts import ExecutionContextOperations from .execution_outputs import ExecutionOutputOperations @@ -1262,26 +1262,10 @@ class PromptDatabase( "has_more": (offset + limit) < total, } - @staticmethod - def _bump_image_tag_bytes(conn: sqlite3.Connection, tag_id: int) -> int: - """Move the tag revision of every image set that carries *tag_id*. - - Vocabulary rename, merge and delete change what an image's set reads - as, so a Tag dialog opened before the change must see ``tag-conflict`` - on Save instead of recreating the old name. Bumps the image index - revision once when any set was affected; returns that count. - """ - cursor = conn.execute( - "UPDATE media_annotation_bytes SET tag_revision = tag_revision + 1 " - "WHERE id IN (SELECT byte_id FROM media_image_tags WHERE tag_id = ?)", - (tag_id,), - ) - if cursor.rowcount > 0: - conn.execute( - "UPDATE media_annotation_metadata SET " - "image_index_revision = image_index_revision + 1 WHERE singleton_id = 1" - ) - return cursor.rowcount + # Vocabulary rename, merge and delete bump image tag revisions through + # the connection-level helper (database/vocabulary.py, shared with #618's + # tag cleanup). + _bump_image_tag_bytes = staticmethod(bump_image_tag_bytes) @classmethod def _move_tag_links( diff --git a/database/tag_cleanup.py b/database/tag_cleanup.py new file mode 100644 index 00000000..db922225 --- /dev/null +++ b/database/tag_cleanup.py @@ -0,0 +1,440 @@ +"""Tag cleanup: a registry of rules over the tag registry (#618). + +Each ``TagRule`` finds tag ids on a read-only connection, rechecks one +reviewed target on the write connection and applies it there. ``RULES`` is +the registry; its order is the review's order and decides ownership: a tag +belongs to the first rule that finds it and is listed only there. Two rules +ship: + +- ``comma``: tags whose name holds an ASCII or a fullwidth comma (a whole + list saved as one tag, usually from a LoRA's trained words). A tag whose + name starts with ``lora:`` is never one: it is the LoRA import's identity + tag, which the next import makes again (maintainer ruling, 2026-11-22). + Applying removes the tag from its prompts, pairs and images and deletes it. +- ``unused``: tags no prompt, saved pair or image carries. Deleted. + +``find_tag_cleanup`` reads one ``mode=ro`` snapshot and returns every rule's +findings (at most ``MAX_FINDINGS`` held per rule, totals exact). +``plan_tag_cleanup`` re-reads the selected findings on another snapshot; one +whose fingerprint ``(tag_id, name, links)`` changed since the find is +protected, not planned. ``links`` hashes the sorted prompt ids, pair ids and +``(byte_id, position)`` rows carrying the tag, so a tag moved from one prompt +to another is seen. ``apply_tag_cleanup`` runs inside the caller's ``BEGIN +IMMEDIATE`` and rechecks each target: one that changed is kept with its +reason and the rest still apply (one edited tag must not block hundreds). + +Saved views are never rewritten; a finding says how many name it. The +auto-tag marks (``media_image_autotags``) are never read or written. +""" + +import hashlib +import json +import sqlite3 +from dataclasses import dataclass +from typing import Callable, Optional + +from .maintenance import ( + MAX_DETAILS, + MaintenanceDraft, + _Fingerprint, + _plural, + _read_snapshot, +) +from .vocabulary import VocabularyOperations, _delete_tag + +OPERATION = "tag_cleanup" +MAX_FINDINGS = 2000 # findings a find holds and lists per rule +COMMAS = (",", ",") +LORA_PREFIX = "lora:" +CHANGED_SINCE_SEARCH = "changed since the search" +NO_FILES = "No files are removed" + +# Findings are listed by name (case-insensitive), then id. +_COMMA_SQL = ( + "SELECT id FROM tags WHERE (instr(name, ?) > 0 OR instr(name, ?) > 0) " + "AND substr(name, 1, ?) != ? ORDER BY name COLLATE NOCASE, id" +) +_UNUSED_SQL = ( + "SELECT id FROM tags t WHERE " + "NOT EXISTS (SELECT 1 FROM prompt_tags x WHERE x.tag_id = t.id) AND " + "NOT EXISTS (SELECT 1 FROM prompt_pair_tags x WHERE x.tag_id = t.id) " + "ORDER BY name COLLATE NOCASE, id" +) +_UNUSED_WITH_IMAGES_SQL = ( + "SELECT id FROM tags t WHERE " + "NOT EXISTS (SELECT 1 FROM prompt_tags x WHERE x.tag_id = t.id) AND " + "NOT EXISTS (SELECT 1 FROM prompt_pair_tags x WHERE x.tag_id = t.id) AND " + "NOT EXISTS (SELECT 1 FROM media_image_tags x WHERE x.tag_id = t.id) " + "ORDER BY name COLLATE NOCASE, id" +) +_ANNOTATION_TABLES = ("media_image_tags", "media_annotation_bytes") + + +@dataclass(frozen=True) +class TagRule: + """One cleanup rule: its copy and its three functions.""" + + id: str + title: str + explanation: str + action_label: str + find: Callable[[sqlite3.Connection], list] + recheck: Callable[[sqlite3.Connection, dict], Optional[str]] + apply: Callable[[sqlite3.Connection, dict], None] + + +def _has_image_links(conn): + """Whether the image annotation tables exist (else images link nothing).""" + found = conn.execute( + "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name IN (?, ?)", + _ANNOTATION_TABLES, + ).fetchone()[0] + return found == len(_ANNOTATION_TABLES) + + +def _links(conn, tag_id): + """sha256 of the link rows carrying ``tag_id``: prompts, pairs, images.""" + prompts = [ + r[0] + for r in conn.execute( + "SELECT prompt_id FROM prompt_tags WHERE tag_id=? ORDER BY 1", (tag_id,) + ) + ] + pairs = [ + r[0] + for r in conn.execute( + "SELECT pair_id FROM prompt_pair_tags WHERE tag_id=? ORDER BY 1", + (tag_id,), + ) + ] + images = [] + if _has_image_links(conn): + images = [ + [r[0], r[1]] + for r in conn.execute( + "SELECT byte_id, position FROM media_image_tags WHERE tag_id=? " + "ORDER BY 1, 2", + (tag_id,), + ) + ] + return _hash_links(prompts, pairs, images) + + +def _hash_links(prompts, pairs, images): + encoded = json.dumps([prompts, pairs, images], separators=(",", ":")) + return hashlib.sha256(encoded.encode("utf-8")).hexdigest() + + +NO_LINKS = _hash_links([], [], []) + + +def _find_comma(conn): + params = (*COMMAS, len(LORA_PREFIX), LORA_PREFIX) + return [row[0] for row in conn.execute(_COMMA_SQL, params)] + + +def _find_unused(conn): + sql = _UNUSED_WITH_IMAGES_SQL if _has_image_links(conn) else _UNUSED_SQL + return [row[0] for row in conn.execute(sql)] + + +def _identity_reason(conn, target): + """``already deleted`` or ``renamed since the review``, else None.""" + row = conn.execute("SELECT name FROM tags WHERE id=?", (target["tag_id"],)) + row = row.fetchone() + if row is None: + return "already deleted" + if row[0] != target["name"]: + return "renamed since the review" + return None + + +def _recheck_comma(conn, target): + reason = _identity_reason(conn, target) + if reason is None and _links(conn, target["tag_id"]) != target["links"]: + reason = "its links changed since the review" + return reason + + +def _recheck_unused(conn, target): + reason = _identity_reason(conn, target) + if reason is None and _links(conn, target["tag_id"]) != target["links"]: + reason = "it is used now" + return reason + + +def _delete_target(conn, target): + """Both shipped rules' apply: delete the tag; its links cascade.""" + _delete_tag(conn, target["tag_id"]) + + +def _apply_target(conn, target): + # Looked up at call time, so a test can stand in for the delete. + _delete_target(conn, target) + + +RULES = ( + TagRule( + id="comma", + title="Tags containing a comma", + explanation=( + "A whole list saved as one tag, usually from a LoRA's trained words." + ), + action_label=( + "Removes the tag from its prompts, pairs and images and deletes it." + ), + find=_find_comma, + recheck=_recheck_comma, + apply=_apply_target, + ), + TagRule( + id="unused", + title="Tags with no links", + explanation="No prompt, saved pair or image carries the tag.", + action_label="Deletes the tag.", + find=_find_unused, + recheck=_recheck_unused, + apply=_apply_target, + ), +) +RULE_IDS = tuple(rule.id for rule in RULES) +_BY_ID = {rule.id: rule for rule in RULES} + + +def rule(rule_id): + """The registered rule ``rule_id`` (KeyError when there is none).""" + return _BY_ID[rule_id] + + +def _saved_view_names(conn): + """``{tag name: views naming it}`` from every saved view's state.""" + exists = conn.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='saved_views'" + ).fetchone() + if not exists: + return {} + counts = {} + for (state,) in conn.execute("SELECT state FROM saved_views"): + try: + tags = json.loads(state).get("tags") or [] + except (TypeError, ValueError, AttributeError): + continue + for name in {tag for tag in tags if isinstance(tag, str)}: + counts[name] = counts.get(name, 0) + 1 + return counts + + +def _finding(conn, rule_id, tag_id, views): + row = conn.execute("SELECT name FROM tags WHERE id=?", (tag_id,)).fetchone() + if row is None: + return None + counts = ( + VocabularyOperations._tag_owner_counts(conn, tag_id) + if _has_image_links(conn) + else _counts_without_images(conn, tag_id) + ) + return { + "rule": rule_id, + "tag_id": tag_id, + "name": row[0], + "prompts": counts["components_changed"], + "pairs": counts["pairs_changed"], + "images": counts["images_changed"], + "saved_views": views.get(row[0], 0), + "links": _links(conn, tag_id), + } + + +def _counts_without_images(conn, tag_id): + prompts = conn.execute( + "SELECT COUNT(DISTINCT prompt_id) FROM prompt_tags WHERE tag_id=?", (tag_id,) + ).fetchone()[0] + pairs = conn.execute( + "SELECT COUNT(DISTINCT pair_id) FROM prompt_pair_tags WHERE tag_id=?", + (tag_id,), + ).fetchone()[0] + return {"components_changed": prompts, "pairs_changed": pairs, "images_changed": 0} + + +def _owners_text(finding): + parts = [ + _plural(finding[key], noun) + for key, noun in (("prompts", "prompt"), ("pairs", "pair"), ("images", "image")) + if finding[key] + ] + return " · ".join(parts) + + +def finding_detail(finding): + """The server's line for a finding: ``3 prompts · 1 pair``, ``no links``, + with `` · in 1 saved view`` when a saved view names it.""" + detail = _owners_text(finding) or "no links" + views = finding.get("saved_views", 0) + if views: + detail += f" · in {_plural(views, 'saved view')}" + return detail + + +def find_tag_cleanup(db_path): + """Every rule's findings on one ``mode=ro`` snapshot (blocking, read-only). + + ``{"rules": {rule_id: [finding, ...]}, "totals": {rule_id: int}}``: + findings by name (case-insensitive), then id; at most ``MAX_FINDINGS`` + held per rule, totals exact. A tag is listed under the first rule that + finds it only. + """ + + def read(conn): + owned = set() + views = _saved_view_names(conn) + rules, totals = {}, {} + for item in RULES: + ids = [tag_id for tag_id in item.find(conn) if tag_id not in owned] + owned.update(ids) + totals[item.id] = len(ids) + findings = [] + for tag_id in ids[:MAX_FINDINGS]: + finding = _finding(conn, item.id, tag_id, views) + if finding is not None: + findings.append(finding) + rules[item.id] = findings + return {"rules": rules, "totals": totals} + + return _read_snapshot(db_path, read) + + +def _target(finding): + return { + key: finding[key] + for key in ( + "rule", + "tag_id", + "name", + "prompts", + "pairs", + "images", + "saved_views", + "links", + ) + } + + +def _scope_label(targets): + if not targets: + return "No tags to delete" + prompts = sum(t["prompts"] for t in targets) + pairs = sum(t["pairs"] for t in targets) + images = sum(t["images"] for t in targets) + return ( + f"Delete {_plural(len(targets), 'tag')} (removed from " + f"{_plural(prompts, 'prompt')}, {_plural(pairs, 'pair')} and " + f"{_plural(images, 'image')})" + ) + + +def plan_tag_cleanup(db_path, held, tag_ids_by_rule): + """The reviewed plan for the selected findings (blocking, read-only). + + ``held`` is a ``find_tag_cleanup`` result and ``tag_ids_by_rule`` + ``{rule_id: [tag_id, ...]}`` of its findings (the caller validated + both). Each selected finding is read again on one snapshot; one whose + ``(tag_id, name, links)`` changed since the find is protected + (``changed since the search``), not planned. Targets follow the + registry's order, then the find's. + """ + reviewed = { + (finding["rule"], finding["tag_id"]): finding + for findings in held["rules"].values() + for finding in findings + } + + def read(conn): + views = _saved_view_names(conn) + targets, protected = [], [] + for item in RULES: + for tag_id in tag_ids_by_rule.get(item.id, ()): + before = reviewed[(item.id, tag_id)] + now = _finding(conn, item.id, tag_id, views) + same = now is not None and (now["name"], now["links"]) == ( + before["name"], + before["links"], + ) + if same: + targets.append(_target(now)) + else: + protected.append( + {**_target(before), "reason": CHANGED_SINCE_SEARCH} + ) + return targets, protected + + targets, protected = _read_snapshot(db_path, read) + fingerprint = _Fingerprint(OPERATION) + for target in targets: + fingerprint.add([target["rule"], target["tag_id"], target["name"]]) + fingerprint.add(target["links"]) + reasons = ( + [f"{_plural(len(protected), 'tag')} {CHANGED_SINCE_SEARCH}"] + if protected + else [] + ) + draft = MaintenanceDraft( + operation=OPERATION, + fingerprint=fingerprint.hexdigest(), + targets=targets, + scope={"count": len(targets), "label": _scope_label(targets)}, + protected={"count": len(protected), "reasons": reasons}, + media={"deletes_files": False, "label": NO_FILES}, + details=[ + { + "label": target["name"], + "detail": f"{rule(target['rule']).title} · {finding_detail(target)}", + } + for target in targets[:MAX_DETAILS] + ], + ) + draft.held = protected + return draft + + +def held_rows(draft): + """The findings a plan protected, each with its reason.""" + return list(getattr(draft, "held", ())) + + +def _empties_legacy_tags(conn): + """Whether deleting one more tag would empty ``tags`` while a prompt still + holds legacy JSON tags: the start-up migration would then bring every + legacy tag and link back (``models._migrate_json_tags_to_junction``).""" + if conn.execute("SELECT COUNT(*) FROM tags").fetchone()[0] > 1: + return False + legacy = conn.execute( + "SELECT 1 FROM prompts WHERE tags IS NOT NULL AND tags != '' " + "AND tags != '[]' LIMIT 1" + ).fetchone() + return legacy is not None + + +LAST_TAG = "kept so the old tag migration does not run again" + + +def apply_tag_cleanup(conn, targets): + """Apply the reviewed targets in the caller's transaction (blocking). + + Each target's rule rechecks it on ``conn``; one that changed is kept with + its reason and the rest still apply. ``{"changed": n, "rows": [every + deleted target], "kept": [{...target, "reason"}]}``. Any exception + propagates, so the caller's transaction rolls back as a whole. + """ + changed, rows, kept = 0, [], [] + for target in targets: + item = rule(target["rule"]) + reason = item.recheck(conn, target) + if reason is None and _empties_legacy_tags(conn): + reason = LAST_TAG + if reason is not None: + kept.append({**target, "reason": reason}) + continue + item.apply(conn, target) + changed += 1 + rows.append(dict(target)) + return {"changed": changed, "rows": rows, "kept": kept} diff --git a/database/vocabulary.py b/database/vocabulary.py index 206d13f6..8dee04b1 100644 --- a/database/vocabulary.py +++ b/database/vocabulary.py @@ -295,6 +295,38 @@ def _category_after(after: object) -> tuple[int, str] | None: return after[0], after[1] +def bump_image_tag_bytes(conn: sqlite3.Connection, tag_id: int) -> int: + """Move the tag revision of every image set that carries *tag_id*. + + Vocabulary rename, merge and delete change what an image's set reads as, + so a Tag dialog opened before the change must see ``tag-conflict`` on Save + instead of recreating the old name. Bumps the image index revision once + when any set was affected; returns that count. + """ + cursor = conn.execute( + "UPDATE media_annotation_bytes SET tag_revision = tag_revision + 1 " + "WHERE id IN (SELECT byte_id FROM media_image_tags WHERE tag_id = ?)", + (tag_id,), + ) + if cursor.rowcount > 0: + conn.execute( + "UPDATE media_annotation_metadata SET " + "image_index_revision = image_index_revision + 1 WHERE singleton_id = 1" + ) + return cursor.rowcount + + +def _delete_tag(conn: sqlite3.Connection, tag_id: int) -> None: + """Delete the registry row *tag_id* in the caller's transaction. + + Image sets carrying it get a new tag revision first; its component, pair + and image links cascade. Shared by ``delete_vocabulary_tag`` and the tag + cleanup rules (#618, ``database/tag_cleanup.py``). + """ + bump_image_tag_bytes(conn, tag_id) + conn.execute("DELETE FROM tags WHERE id=?", (tag_id,)) + + class VocabularyOperations: """Vocabulary reads and tag commands. @@ -405,8 +437,7 @@ class VocabularyOperations: epoch = self._library_epoch(conn, expected_epoch) self._vocabulary_identity(conn, epoch, tag_id, name) counts = self._tag_owner_counts(conn, tag_id) - self._bump_image_tag_bytes(conn, tag_id) - conn.execute("DELETE FROM tags WHERE id=?", (tag_id,)) + _delete_tag(conn, tag_id) return {"library_epoch": epoch, "deleted": True, **counts} def vocabulary_tag_impact(self, tag_id: int) -> dict | None: diff --git a/py/api/__init__.py b/py/api/__init__.py index 41da17f1..17dbe5f6 100644 --- a/py/api/__init__.py +++ b/py/api/__init__.py @@ -23,6 +23,7 @@ Split into domain-specific mixins for maintainability: - LibraryDeleteRoutesMixin: the Library's Delete… (archive paired) and Restore - WorkflowStorageRoutesMixin: store each workflow once, then Reclaim space - DuplicateFilesMixin: duplicate image files as find and removal jobs +- TagCleanupMixin: tag cleanup (#618) as a find job, its findings and a plan - LoraImportRoutesMixin: the reviewed, staged LoRA reference import job """ @@ -74,6 +75,7 @@ from .maintenance import MaintenanceRoutesMixin from .backup_restore import BackupRestoreRoutesMixin from .workflow_storage import WorkflowStorageRoutesMixin from .duplicate_files import DuplicateFilesMixin +from .tag_cleanup import TagCleanupMixin from .maintenance_plans import PlanStore from .jobs import JobRegistry from .logging_routes import LoggingRoutesMixin @@ -317,6 +319,7 @@ class PromptManagerAPI( BackupRestoreRoutesMixin, WorkflowStorageRoutesMixin, DuplicateFilesMixin, + TagCleanupMixin, LoggingRoutesMixin, LogCleanupMixin, DiagnosticsReportMixin, @@ -394,6 +397,9 @@ class PromptManagerAPI( # Duplicate-file finds by job id, with the groups each one holds for # review (py/api/duplicate_files.py); the last few only. self._duplicate_finds = {} + # Tag cleanup finds by job id with the findings each holds (#618, + # py/api/tag_cleanup.py); None while a find runs or after it failed. + self._tag_cleanup_finds = {} # The last System health report this session and the database # generation it describes, bumped when a restore replaces self.db # (py/api/system.py). @@ -691,6 +697,7 @@ class PromptManagerAPI( self._register_maintenance_routes(routes) self._register_backup_restore_routes(routes) self._register_duplicate_routes(routes) + self._register_tag_cleanup_routes(routes) self._register_logging_routes(routes) self._register_autotag_routes(routes) self._register_lora_routes(routes) diff --git a/py/api/jobs.py b/py/api/jobs.py index d20eab21..45925a07 100644 --- a/py/api/jobs.py +++ b/py/api/jobs.py @@ -124,6 +124,10 @@ MODEL_DOWNLOAD_JOB_KIND = "model_download" DUPLICATES_JOB_KIND = "duplicates" DUPLICATE_GROUP_NAMES = ("groups_found",) DUPLICATE_CLEANUP_GROUP_NAMES = ("removed", "kept", "errors") +# Tag cleanup (#618, py/api/tag_cleanup.py): the find is a ``read`` job that +# holds its findings; the reviewed apply is a ``maintenance`` job. +TAG_CLEANUP_JOB_KIND = "tag_cleanup" +TAG_CLEANUP_GROUP_NAMES = ("found",) # The workspace Library's Delete… (#443, py/api/library_delete.py): a # ``records`` hold around its safety backup and write. PROMPT_DELETE_JOB_KIND = "prompt_delete" diff --git a/py/api/maintenance.py b/py/api/maintenance.py index ab3f4744..9582ae6a 100644 --- a/py/api/maintenance.py +++ b/py/api/maintenance.py @@ -5,7 +5,9 @@ one operation (``duplicate_prompts``, ``optimize``, ``unused_components``, ``missing_links`` or ``pair_metadata``, #550; ``database/maintenance.py``; ``duplicate_files``, ``py/api/duplicate_files.py``; ``rotated_logs``, the rotated log copies, -``py/api/log_cleanup.py``, which has its own apply job) off the event loop and +``py/api/log_cleanup.py``, which has its own apply job; ``tag_cleanup``, +#618, the ticked findings of a tag search, ``py/api/tag_cleanup.py``) off the +event loop and answers a ``Plan``: ``{success, token, operation, expires_at, scope:{count, label}, protected:{count, reasons}, backup:{policy, destination_label}, media:{deletes_files, label}, details:[≤50 {label, detail}]}``. The preview @@ -29,13 +31,17 @@ The token is consumed when the job starts (on the same loop turn, before its runner runs); a refused start keeps it. The runner: 1. takes a safety backup when the plan was reviewed with the policy on or the - policy (``maintenance.safety_backup``, default on) is on now: SQLite's + policy (``maintenance.safety_backup``, default on) is on now, and always + for ``workflow_storage`` and ``tag_cleanup`` (``ALWAYS_BACKED_UP``, policy + ``required``): SQLite's backup API into a temp file beside the database, ``verify_database_file``, fsync, ``0o600`` on POSIX, then ``os.replace`` onto a unique ``.backup_[_n]`` name. Any failure removes what it wrote and ends the job ``backup-failed`` with nothing changed; 2. applies the plan, which first rechecks the reviewed fingerprint inside - ``BEGIN IMMEDIATE`` (``plan-changed`` writes nothing); + ``BEGIN IMMEDIATE`` (``plan-changed`` writes nothing); ``tag_cleanup`` + rechecks each tag instead and keeps, with its reason, each one that + changed, while the rest still apply; 3. counts the changed and protected records, and prunes old safety backups. The job log names the backup by its file name only, and the job says "No @@ -87,6 +93,13 @@ MAINTENANCE_PREVIEW_LEASE = "Maintenance preview" DUPLICATE_PREVIEW_BODY_MAX = 1024 * 1024 DUPLICATE_FILES = "duplicate_files" WORKFLOW_STORAGE = "workflow_storage" # applied by py/api/workflow_storage.py +# #618: planned from a tag search's findings (py/api/tag_cleanup.py). +TAG_CLEANUP = "tag_cleanup" +# Previews whose options list many ids, read up to the large body cap. +LARGE_PREVIEWS = frozenset({DUPLICATE_FILES, TAG_CLEANUP}) +# Always backed up first, whatever the safety-backup setting: Store each +# workflow once (the way back) and Tag cleanup (maintainer ruling, #618). +ALWAYS_BACKED_UP = frozenset({WORKFLOW_STORAGE, TAG_CLEANUP}) # rotated_logs (#329, py/api/log_cleanup.py) reviews log files, not records. PREVIEW_OPERATIONS = MAINTENANCE_OPERATIONS + (DUPLICATE_FILES, ROTATED_LOGS) # Room left over beyond what a step writes, so a disk is never filled to 0. @@ -100,9 +113,12 @@ MAINTENANCE_TITLES = { "workflow_storage": "Store each workflow once", # #550, beyond the concept: fills old Pair prompts' empty category and tags. "pair_metadata": "Pair category and tags", + # #618 (D210), beyond the concept: deletes comma-list and unused tags. + TAG_CLEANUP: "Tag cleanup", } -# Operations whose job keeps every changed row for its report (#550). -COMPLETE_RECORD = frozenset({"pair_metadata"}) +# Operations whose job keeps every changed row for its report (#550; #618: +# the report and the backup are the only record of the deleted tag names). +COMPLETE_RECORD = frozenset({"pair_metadata", TAG_CLEANUP}) _OPERATION_ERROR = "operation must be one of: " + ", ".join(PREVIEW_OPERATIONS) MAINTENANCE_GROUPS = ("changed", "protected", "errors") MAX_TOKEN_LENGTH = 128 @@ -307,6 +323,8 @@ def _changed_line(operation, count, marks=0, result=None): return "Optimized the database" if operation == "pair_metadata": return _pair_metadata_line(result or {"changed": count}) + if operation == TAG_CLEANUP: + return f"Deleted {count:,} {'tag' if count == 1 else 'tags'}" if operation == "duplicate_prompts": noun = "duplicate prompt" if count == 1 else "duplicate prompts" return f"Merged {count:,} {noun}" @@ -408,7 +426,7 @@ class MaintenanceRoutesMixin: ("operation", "options"), cap=lambda body: ( DUPLICATE_PREVIEW_BODY_MAX - if body.get("operation") == DUPLICATE_FILES + if body.get("operation") in LARGE_PREVIEWS else PREVIEW_BODY_MAX ), ) @@ -420,6 +438,8 @@ class MaintenanceRoutesMixin: return _invalid(_OPERATION_ERROR) if operation == DUPLICATE_FILES: return await self.preview_duplicate_files(options) + if operation == TAG_CLEANUP: + return await self.preview_tag_cleanup(options) if not isinstance(options, dict) or options: return _invalid(f"{operation} takes no options") if operation == ROTATED_LOGS: @@ -470,10 +490,12 @@ class MaintenanceRoutesMixin: ) policy = self._safety_backup_policy() destination = "backup" - if operation == WORKFLOW_STORAGE: - # Always backed up first, whatever the policy (the way back); - # one kept pre-migration backup ever, pooled ones after it. + if operation in ALWAYS_BACKED_UP: + # Always backed up first, whatever the policy. policy = "required" + if operation == WORKFLOW_STORAGE: + # The way back: one kept pre-migration backup ever, pooled ones + # after it. kept = await self._run_in_executor(pre_migration_backups, db.model.db_path) destination = "backup" if kept else PRE_MIGRATION_LABEL try: @@ -635,8 +657,8 @@ class MaintenanceRoutesMixin: Decided once, when the apply starts (the disk check measured it), and handed to the job. """ - if plan.operation == WORKFLOW_STORAGE: - return True # never without its pre-migration backup + if plan.operation in ALWAYS_BACKED_UP: + return True # never without its backup (pre-migration, or #618's) return plan.payload["backup"] == "on" or self._safety_backup_policy() == "on" async def _safety_backup_step(self, job, db, backup_on): @@ -746,6 +768,13 @@ class MaintenanceRoutesMixin: } ) return rows + if plan.operation == TAG_CLEANUP: + # The findings the review protected, then each target the apply + # kept, every one with its reason (#618). + return [ + {"path": "", "detail": f"Kept tag “{item['name']}”: {item['reason']}"} + for item in [*plan.payload.get("held", ()), *result["kept"]] + ] if "kept" not in result: return None return [ @@ -775,6 +804,8 @@ class MaintenanceRoutesMixin: return rows if operation == "pair_metadata": return [{"path": "", "detail": _filled_detail(item)} for item in described] + if operation == TAG_CLEANUP: + return [{"path": "", "detail": _deleted_tag_detail(i)} for i in described] if operation == "duplicate_prompts": return [ { @@ -792,6 +823,26 @@ class MaintenanceRoutesMixin: ] +def _deleted_tag_detail(item): + """``Deleted tag “a, b” (Tags containing a comma) · removed from 3 prompts``.""" + from .tag_cleanup import rules + + line = f"Deleted tag “{item['name']}” ({rules.rule(item['rule']).title})" + owners = [ + f"{item[key]:,} {noun if item[key] == 1 else noun + 's'}" + for key, noun in (("prompts", "prompt"), ("pairs", "pair"), ("images", "image")) + if item.get(key) + ] + if not owners: + return line + joined = ( + owners[0] + if len(owners) == 1 + else (", ".join(owners[:-1]) + " and " + owners[-1]) + ) + return f"{line} · removed from {joined}" + + def _filled_detail(item): """``Prompt 12: category “portrait”; tags a, b``: one filled prompt (#550).""" parts = [] diff --git a/py/api/tag_cleanup.py b/py/api/tag_cleanup.py new file mode 100644 index 00000000..aeab717d --- /dev/null +++ b/py/api/tag_cleanup.py @@ -0,0 +1,245 @@ +"""Tag cleanup as a find job, its findings and a reviewed plan (#618). + +- ``POST /prompt_manager/jobs/tag_cleanup`` (body ignored) starts the find + (202 ``{job}``): kind ``tag_cleanup``, "Find tags to clean up", admission + ``read``, not cancellable (one snapshot read), outcome group ``found``. It + runs every rule of ``database/tag_cleanup.py`` on one read-only snapshot, + holds the result under the job id (the last ``MAX_HELD_FINDS``), records one + ``found`` row per tag and writes nothing. 409 ``busy`` while a find or an + exclusive job runs. +- ``GET /prompt_manager/maintenance/tag_cleanup/{job_id}`` answers every held + finding at once: ``{success, job:{id, state}, rules:[{id, title, + explanation, action_label, total, findings:[{tag_id, name, detail}]}]}``, + at most ``MAX_FINDINGS`` per rule (``total`` is exact). 404 ``not-found``, + 409 ``job-running``, 409 ``no-groups`` (the find failed). +- ``POST /prompt_manager/maintenance/preview {operation:"tag_cleanup", + options:{job_id, select:[{rule, tag_ids}]}}`` reviews the ticked findings + (``preview_tag_cleanup``): each selected tag must be a held finding of that + rule. The plan always takes a safety backup first (policy ``required``, + maintainer ruling 2026-11-22) and its apply, the ``maintenance`` job "Tag + cleanup", rechecks each tag and keeps, with its reason, each one that + changed (``py/api/maintenance.py``). +""" + +from aiohttp import web + +from .job_routes import busy_response +from .jobs import TAG_CLEANUP_GROUP_NAMES, TAG_CLEANUP_JOB_KIND, JobBusy +from .maintenance import _failure, _invalid + +try: + from ...database import tag_cleanup as rules +except ImportError: + from database import tag_cleanup as rules + +TAG_CLEANUP = rules.OPERATION +FIND_TITLE = "Find tags to clean up" +FIND_FAILED = "The tag search failed." +MAX_HELD_FINDS = 3 # finds whose findings the server keeps for review +MAX_JOB_ID = 64 + + +def _parse_select(entry, seen): + """``(rule_id, tag_ids, None)`` for one select entry, else a message.""" + if not isinstance(entry, dict) or set(entry) != {"rule", "tag_ids"}: + return None, None, "Each select entry is {rule, tag_ids}" + rule_id, tag_ids = entry["rule"], entry["tag_ids"] + if not isinstance(rule_id, str) or rule_id not in rules.RULE_IDS: + return None, None, "rule must be one of: " + ", ".join(rules.RULE_IDS) + if rule_id in seen: + return None, None, "Each rule is selected once" + limit = rules.MAX_FINDINGS + if not isinstance(tag_ids, list) or not 0 < len(tag_ids) <= limit: + return None, None, f"tag_ids must list 1 to {limit:,} tags" + for tag_id in tag_ids: + if type(tag_id) is not int or tag_id < 1: + return None, None, "tag_ids must be tag ids" + if len(set(tag_ids)) != len(tag_ids): + return None, None, "tag_ids must not repeat a tag" + return rule_id, tag_ids, None + + +def parse_options(options): + """``(job_id, {rule_id: [tag_id]}, None)`` or ``(None, None, message)``.""" + if not isinstance(options, dict) or set(options) != {"job_id", "select"}: + return None, None, "tag_cleanup takes options {job_id, select}" + job_id, select = options["job_id"], options["select"] + if not isinstance(job_id, str) or not 0 < len(job_id) <= MAX_JOB_ID: + return None, None, "job_id must be a tag search's job id" + if not isinstance(select, list) or not 0 < len(select) <= len(rules.RULES): + return None, None, f"select must list 1 to {len(rules.RULES)} rules" + chosen = {} + for entry in select: + rule_id, tag_ids, message = _parse_select(entry, chosen) + if message: + return None, None, message + chosen[rule_id] = tag_ids + return job_id, chosen, None + + +def _found_rows(result): + return [ + {"path": "", "detail": f"{f['name']} · {rules.rule(rule_id).title}"} + for rule_id in rules.RULE_IDS + for f in result["rules"][rule_id] + ] + + +def _public_rules(result): + return [ + { + "id": item.id, + "title": item.title, + "explanation": item.explanation, + "action_label": item.action_label, + "total": result["totals"][item.id], + "findings": [ + { + "tag_id": f["tag_id"], + "name": f["name"], + "detail": rules.finding_detail(f), + } + for f in result["rules"][item.id] + ], + } + for item in rules.RULES + ] + + +class TagCleanupMixin: + """Mixin providing the tag cleanup find, its findings and its plan.""" + + def _register_tag_cleanup_routes(self, routes): + @routes.post("/prompt_manager/jobs/tag_cleanup") + async def start_tag_cleanup_find_route(request): + return await self.start_tag_cleanup_find(request) + + @routes.get("/prompt_manager/maintenance/tag_cleanup/{job_id}") + async def tag_cleanup_findings_route(request): + return await self.tag_cleanup_findings(request) + + # ── find ────────────────────────────────────────────────────────── + + async def start_tag_cleanup_find(self, request): + """Start the tag search (202), or 409 naming the job in the way.""" + db = self.db + try: + job = self._jobs.start( + TAG_CLEANUP_JOB_KIND, + FIND_TITLE, + admission="read", + cancellable=False, + groups=TAG_CLEANUP_GROUP_NAMES, + runner=lambda job: self._run_tag_cleanup_find(job, db), + ) + except JobBusy as busy: + return busy_response(busy) + self._remember_tag_cleanup_find(job.id) + return web.json_response({"success": True, "job": job.summary()}, status=202) + + def _remember_tag_cleanup_find(self, job_id): + """Hold a slot for ``job_id`` (None until it found); keep the last few.""" + finds = self._tag_cleanup_finds + finds[job_id] = None + for held in list(finds): + if self._jobs.get(held) is None: + del finds[held] + while len(finds) > MAX_HELD_FINDS: + del finds[next(iter(finds))] + + async def _run_tag_cleanup_find(self, job, db): + job.update(status_line="Looking for tags to clean up") + try: + result = await self._run_in_executor( + rules.find_tag_cleanup, db.model.db_path + ) + except Exception: + self.logger.exception("Tag search failed") + job.update(status_line=FIND_FAILED) + job.log_line(FIND_FAILED) + job.finish("failed") + return + if job.id in self._tag_cleanup_finds: + self._tag_cleanup_finds[job.id] = result + count = sum(result["totals"].values()) + job.record_counted("found", count, _found_rows(result)) + line = ( + f"Found {count:,} {'tag' if count == 1 else 'tags'} to clean up" + if count + else "No tags need cleaning up" + ) + job.log_line(line) + job.update(progress=100, status_line=line) + + # ── findings ────────────────────────────────────────────────────── + + def _held_tag_cleanup(self, job_id): + """``(result, None)`` for a finished search's findings, else a reply.""" + job = self._jobs.get(job_id) + finds = self._tag_cleanup_finds + if job_id not in finds or job is None or job.kind != TAG_CLEANUP_JOB_KIND: + return None, _failure( + "No tag search with this id. Search again.", 404, "not-found" + ) + if job.running: + return None, _failure( + "The tag search is still running.", 409, "job-running" + ) + if finds[job_id] is None: + return None, _failure( + "This search did not finish. Search again.", 409, "no-groups" + ) + return finds[job_id], None + + async def tag_cleanup_findings(self, request): + job_id = request.match_info["job_id"] + result, error = self._held_tag_cleanup(job_id) + if error is not None: + return error + job = self._jobs.get(job_id) + return web.json_response( + { + "success": True, + "job": {"id": job.id, "state": job.state}, + "rules": _public_rules(result), + }, + headers={"Cache-Control": "no-store"}, + ) + + # ── review ──────────────────────────────────────────────────────── + + async def preview_tag_cleanup(self, options): + """The ``tag_cleanup`` plan for the ticked findings of one search.""" + job_id, chosen, message = parse_options(options) + if message: + return _invalid(message) + held, error = self._held_tag_cleanup(job_id) + if error is not None: + return error + for rule_id, tag_ids in chosen.items(): + listed = {f["tag_id"] for f in held["rules"][rule_id]} + if not listed.issuperset(tag_ids): + return _invalid("A selected tag is not a finding of its rule") + db = self.db + identity = self._database_identity(db) + try: + draft = await self._run_in_executor( + rules.plan_tag_cleanup, db.model.db_path, held, chosen + ) + except Exception: + self.logger.exception("Tag cleanup review failed") + return _failure("Failed to review maintenance", 500) + return await self._plan_response( + db, + identity, + TAG_CLEANUP, + draft.fingerprint, + draft.public(), + { + "targets": draft.targets, + "roots": [], + "held": rules.held_rows(draft), + "protected": draft.protected["count"], + "rows": len(draft.targets), + }, + ) diff --git a/tests/fixtures/legacy_contract_snapshot.json b/tests/fixtures/legacy_contract_snapshot.json index abd9dd84..dfaa8bde 100644 --- a/tests/fixtures/legacy_contract_snapshot.json +++ b/tests/fixtures/legacy_contract_snapshot.json @@ -63,6 +63,7 @@ "GET /prompt_manager/lora/status", "GET /prompt_manager/lora/trigger-words", "GET /prompt_manager/maintenance/duplicates/{job_id}", + "GET /prompt_manager/maintenance/tag_cleanup/{job_id}", "GET /prompt_manager/pairs", "GET /prompt_manager/pairs/export", "GET /prompt_manager/pairs/{pair_id}", @@ -134,6 +135,7 @@ "POST /prompt_manager/jobs/image-tags", "POST /prompt_manager/jobs/model-download", "POST /prompt_manager/jobs/scan", + "POST /prompt_manager/jobs/tag_cleanup", "POST /prompt_manager/jobs/thumbnails", "POST /prompt_manager/jobs/{job_id}/cancel", "POST /prompt_manager/library", diff --git a/tests/test_api_tag_cleanup.py b/tests/test_api_tag_cleanup.py new file mode 100644 index 00000000..f181c983 --- /dev/null +++ b/tests/test_api_tag_cleanup.py @@ -0,0 +1,369 @@ +"""Tag cleanup routes (#618, ``py/api/tag_cleanup.py``). + +``POST /prompt_manager/jobs/tag_cleanup`` finds tags to clean up as a ``read`` +Activity job; ``GET /prompt_manager/maintenance/tag_cleanup/{job_id}`` answers +every rule with the findings it holds; ``tag_cleanup`` previews the ticked +findings as a reviewed plan whose apply always takes a safety backup first, +whatever the setting, then deletes each target that is unchanged and keeps, +with its reason, each one that changed. +""" + +import asyncio +import json +import os + +try: + from tests.test_api_maintenance import APPLY, WAIT, ApplyTestCase +except ImportError: # discovered with tests/ as the top-level directory + from test_api_maintenance import APPLY, WAIT, ApplyTestCase + +from py.config import PromptManagerConfig # noqa: E402 + +FIND = "/prompt_manager/jobs/tag_cleanup" +FINDINGS = "/prompt_manager/maintenance/tag_cleanup/" + + +class TagCleanupTestCase(ApplyTestCase): + def tags(self, *names): + with self.api.db.model.get_connection() as conn: + for name in names: + conn.execute("INSERT INTO tags(name) VALUES(?)", (name,)) + + def names(self): + with self.api.db.model.get_connection() as conn: + return sorted(r[0] for r in conn.execute("SELECT name FROM tags")) + + def seed(self): + """Two comma tags (one on a prompt), two unused, one clean in use.""" + self.save("Owner", tags=["a, b", "clean"]) + self.tags("x,y", "ghost", "spirit") + + async def find(self): + response = await self.client.request("POST", FIND) + text = await response.text() + self.assertEqual(response.status, 202, text) + job = self.api._jobs.get(json.loads(text)["job"]["id"]) + await asyncio.wait_for(asyncio.shield(job.task), WAIT) + return job + + async def findings(self, job_id, status=200): + response = await self.client.request("GET", f"{FINDINGS}{job_id}") + text = await response.text() + self.assertEqual(response.status, status, text) + self.assertNotIn(self.tmpdir, text) + if status == 200: + self.assertEqual(response.headers.get("Cache-Control"), "no-store") + return json.loads(text) + + async def select(self, job, **by_rule): + """The preview body selecting every finding of the named rules.""" + body = await self.findings(job.id) + rules = {rule["id"]: rule for rule in body["rules"]} + return { + "job_id": job.id, + "select": [ + { + "rule": rule, + "tag_ids": [f["tag_id"] for f in rules[rule]["findings"]], + } + for rule in by_rule + ], + } + + async def plan(self, options, status=200): + return await self.preview("tag_cleanup", status=status, options=options) + + +class TestFindJob(TagCleanupTestCase): + async def test_find_is_a_read_job_that_records_one_row_per_tag(self): + self.seed() + job = await self.find() + self.assertEqual( + (job.kind, job.title, job.admission, job.cancellable), + ("tag_cleanup", "Find tags to clean up", "read", False), + ) + self.assertEqual(job.state, "finished", job.log) + self.assertEqual(job.counters, {"found": 4}) + self.assertEqual( + [row["detail"] for row in job.outcomes["found"]], + [ + "a, b · Tags containing a comma", + "x,y · Tags containing a comma", + "ghost · Tags with no links", + "spirit · Tags with no links", + ], + ) + self.assertEqual(job.status_line, "Found 4 tags to clean up") + self.assertIn(job.id, self.api._tag_cleanup_finds) + + async def test_a_clean_library_finds_nothing(self): + self.save("Owner", tags=["clean"]) + job = await self.find() + self.assertEqual(job.counters, {"found": 0}) + self.assertEqual(job.status_line, "No tags need cleaning up") + + async def test_a_failed_search_says_so_and_holds_nothing(self): + from database import tag_cleanup + + original = tag_cleanup.find_tag_cleanup + tag_cleanup.find_tag_cleanup = lambda path: 1 / 0 + try: + job = await self.find() + finally: + tag_cleanup.find_tag_cleanup = original + self.assertEqual(job.state, "failed") + self.assertEqual(job.status_line, "The tag search failed.") + body = await self.findings(job.id, status=409) + self.assertEqual(body["code"], "no-groups") + + async def test_a_second_find_while_one_runs_is_busy(self): + gate = asyncio.Event() + + async def hold(job, db): + await gate.wait() + + self.api._run_tag_cleanup_find = hold + response = await self.client.request("POST", FIND) + self.assertEqual(response.status, 202) + first = (await response.json())["job"]["id"] + response = await self.client.request("POST", FIND) + body = await response.json() + self.assertEqual((response.status, body["code"]), (409, "busy")) + reply = await self.findings(first, status=409) + self.assertEqual(reply["code"], "job-running") + gate.set() + await asyncio.wait_for(asyncio.shield(self.api._jobs.get(first).task), WAIT) + + async def test_only_the_last_three_finds_are_held(self): + jobs = [await self.find() for _ in range(4)] + self.assertEqual(list(self.api._tag_cleanup_finds), [j.id for j in jobs[1:]]) + body = await self.findings(jobs[0].id, status=404) + self.assertEqual(body["code"], "not-found") + + +class TestFindingsRoute(TagCleanupTestCase): + async def test_findings_list_every_rule_with_its_copy(self): + self.seed() + job = await self.find() + body = await self.findings(job.id) + self.assertTrue(body["success"]) + self.assertEqual(body["job"], {"id": job.id, "state": "finished"}) + comma, unused = body["rules"] + self.assertEqual( + {k: comma[k] for k in ("id", "title", "total")}, + {"id": "comma", "title": "Tags containing a comma", "total": 2}, + ) + self.assertTrue(comma["explanation"] and comma["action_label"]) + self.assertEqual( + [(f["name"], f["detail"]) for f in comma["findings"]], + [("a, b", "1 prompt"), ("x,y", "no links")], + ) + self.assertEqual(set(comma["findings"][0]), {"tag_id", "name", "detail"}) + self.assertEqual([f["name"] for f in unused["findings"]], ["ghost", "spirit"]) + + async def test_the_total_says_when_the_cap_cut_the_list(self): + from database import tag_cleanup + + self.tags("a", "b", "c") + original = tag_cleanup.MAX_FINDINGS + tag_cleanup.MAX_FINDINGS = 2 + try: + job = await self.find() + finally: + tag_cleanup.MAX_FINDINGS = original + unused = (await self.findings(job.id))["rules"][1] + self.assertEqual((unused["total"], len(unused["findings"])), (3, 2)) + + async def test_unknown_jobs_are_not_found(self): + self.assertEqual((await self.findings("nope", status=404))["code"], "not-found") + other = self.api._jobs.start( + "health", "Health", admission="read", runner=lambda job: asyncio.sleep(0) + ) + await other.task + self.assertEqual( + (await self.findings(other.id, status=404))["code"], "not-found" + ) + + +class TestPreview(TagCleanupTestCase): + async def test_the_plan_names_scope_protection_and_a_required_backup(self): + self.seed() + job = await self.find() + PromptManagerConfig.SAFETY_BACKUP = False + plan = await self.plan(await self.select(job, comma=True)) + self.assertEqual(plan["operation"], "tag_cleanup") + self.assertEqual( + plan["scope"], + { + "count": 2, + "label": "Delete 2 tags (removed from 1 prompt, 0 pairs and 0 images)", + }, + ) + self.assertEqual(plan["protected"], {"count": 0, "reasons": []}) + self.assertEqual(plan["backup"]["policy"], "required") + self.assertEqual( + plan["backup"]["destination_label"], "prompts.db.backup_" + ) + self.assertEqual(plan["backup"]["expected_bytes"], self.database_bytes()) + self.assertEqual( + plan["media"], {"deletes_files": False, "label": "No files are removed"} + ) + self.assertEqual( + [(d["label"], d["detail"]) for d in plan["details"]], + [ + ("a, b", "Tags containing a comma · 1 prompt"), + ("x,y", "Tags containing a comma · no links"), + ], + ) + self.assertNotIn('"links"', json.dumps(plan)) # the hash stays server-side + + async def test_every_bad_shape_is_invalid(self): + self.seed() + job = await self.find() + good = await self.select(job, comma=True) + comma_ids = good["select"][0]["tag_ids"] + cases = [ + [], + {}, + {"job_id": job.id}, + {**good, "extra": 1}, + {**good, "job_id": ""}, + {**good, "job_id": 3}, + {**good, "job_id": "x" * 65}, + {**good, "select": []}, + {**good, "select": "comma"}, + {**good, "select": [good["select"][0]] * 2}, + {**good, "select": [{"rule": "reboot", "tag_ids": comma_ids}]}, + {**good, "select": [{"rule": "comma"}]}, + {**good, "select": [{"rule": "comma", "tag_ids": comma_ids, "x": 1}]}, + {**good, "select": [{"rule": "comma", "tag_ids": []}]}, + {**good, "select": [{"rule": "comma", "tag_ids": [True]}]}, + {**good, "select": [{"rule": "comma", "tag_ids": ["1"]}]}, + {**good, "select": [{"rule": "comma", "tag_ids": [0]}]}, + {**good, "select": [{"rule": "comma", "tag_ids": comma_ids * 2}]}, + # A tag the search listed under the other rule. + {**good, "select": [{"rule": "unused", "tag_ids": comma_ids}]}, + {**good, "select": [{"rule": "comma", "tag_ids": [999999]}]}, + {**good, "select": [{"rule": "comma", "tag_ids": list(range(1, 2002))}]}, + {**good, "select": [{"rule": "comma", "tag_ids": comma_ids}] * 3}, + ] + for options in cases: + with self.subTest(options=options): + body = await self.plan(options, status=400) + self.assertEqual(body["code"], "invalid-request") + + async def test_a_held_find_is_needed(self): + self.seed() + options = {"job_id": "nope", "select": [{"rule": "comma", "tag_ids": [1]}]} + self.assertEqual((await self.plan(options, status=404))["code"], "not-found") + + async def test_hundreds_of_ids_are_not_too_large(self): + self.tags(*(f"tag {n:04}" for n in range(500))) + job = await self.find() + plan = await self.plan(await self.select(job, unused=True)) + self.assertEqual(plan["scope"]["count"], 500) + + async def test_a_finding_changed_since_the_search_is_protected(self): + self.seed() + job = await self.find() + options = await self.select(job, unused=True) + with self.api.db.model.get_connection() as conn: + conn.execute("UPDATE tags SET name='Ghost' WHERE name='ghost'") + plan = await self.plan(options) + self.assertEqual( + plan["protected"], + {"count": 1, "reasons": ["1 tag changed since the search"]}, + ) + self.assertEqual(plan["scope"]["count"], 1) + + +class TestApply(TagCleanupTestCase): + async def run_plan(self, options): + plan = await self.plan(options) + body = await self.post(APPLY, {"token": plan["token"]}, 202) + job = self.api._jobs.get(body["job"]["id"]) + await asyncio.wait_for(asyncio.shield(job.task), WAIT) + return plan, job + + async def test_apply_takes_a_backup_even_with_the_setting_off(self): + self.seed() + find = await self.find() + PromptManagerConfig.SAFETY_BACKUP = False + plan, job = await self.run_plan(await self.select(find, comma=True)) + self.assertEqual( + (job.kind, job.title, job.admission, job.cancellable), + ("maintenance", "Tag cleanup", "records", False), + ) + self.assertEqual(job.state, "finished", job.log) + [backup] = self.backups() + self.assertTrue(os.path.isfile(os.path.join(self.tmpdir, backup))) + self.assertEqual(job.counters, {"changed": 2, "protected": 0, "errors": 0}) + self.assertEqual(job.status_line, f"Deleted 2 tags · Safety backup {backup}") + self.assertEqual( + [row["detail"] for row in job.complete["changed"]], + [ + "Deleted tag “a, b” (Tags containing a comma) · removed from 1 prompt", + "Deleted tag “x,y” (Tags containing a comma)", + ], + ) + # Applying one rule leaves the other rule's tags. + self.assertEqual(self.names(), ["clean", "ghost", "spirit"]) + self.assertEqual(self.api.db.search_prompts()[0]["tags"], ["clean"]) + + async def test_changed_targets_are_kept_one_by_one_and_the_rest_apply(self): + self.seed() + find = await self.find() + plan = await self.plan(await self.select(find, unused=True)) + with self.api.db.model.get_connection() as conn: + conn.execute("DELETE FROM tags WHERE name='spirit'") + body = await self.post(APPLY, {"token": plan["token"]}, 202) + job = self.api._jobs.get(body["job"]["id"]) + await asyncio.wait_for(asyncio.shield(job.task), WAIT) + self.assertEqual(job.state, "finished", job.log) + self.assertEqual(job.counters, {"changed": 1, "protected": 1, "errors": 0}) + self.assertEqual( + [row["detail"] for row in job.complete["protected"]], + ["Kept tag “spirit”: already deleted"], + ) + self.assertEqual(self.names(), ["a, b", "clean", "x,y"]) + + async def test_findings_protected_at_review_are_in_the_job(self): + self.seed() + find = await self.find() + options = await self.select(find, unused=True) + with self.api.db.model.get_connection() as conn: + conn.execute("UPDATE tags SET name='Ghost' WHERE name='ghost'") + _plan, job = await self.run_plan(options) + self.assertEqual(job.counters["protected"], 1) + self.assertEqual( + [row["detail"] for row in job.complete["protected"]], + ["Kept tag “ghost”: changed since the search"], + ) + + async def test_a_plan_applies_once_and_expires(self): + self.seed() + find = await self.find() + plan, _job = await self.run_plan(await self.select(find, comma=True)) + used = await self.post(APPLY, {"token": plan["token"]}, 409) + self.assertEqual(used["code"], "plan-used") + expired = await self.post(APPLY, {"token": "f" * 32}, 410) + self.assertEqual(expired["code"], "plan-expired") + + async def test_a_failed_job_offers_the_maintenance_section(self): + self.seed() + find = await self.find() + plan = await self.plan(await self.select(find, comma=True)) + self.api.db.apply_maintenance = lambda *args: 1 / 0 + body = await self.post(APPLY, {"token": plan["token"]}, 202) + job = self.api._jobs.get(body["job"]["id"]) + await asyncio.wait_for(asyncio.shield(job.task), WAIT) + self.assertEqual(job.state, "failed") + self.assertEqual(job.status_line, "Maintenance failed; nothing was changed.") + self.assertEqual(job.scope["operation"], "tag_cleanup") + self.assertIn("a, b", self.names()) + + +class TestOperationEnum(TagCleanupTestCase): + async def test_the_operation_error_names_tag_cleanup(self): + body = await self.preview("reboot", status=400) + self.assertIn("tag_cleanup", body["error"]) diff --git a/tests/test_maintenance_plans.py b/tests/test_maintenance_plans.py index a8cbbfb8..499d5537 100644 --- a/tests/test_maintenance_plans.py +++ b/tests/test_maintenance_plans.py @@ -252,6 +252,13 @@ class TestPreviews(MaintenanceDatabaseCase): with self.assertRaises(ValueError): self.db.preview_maintenance("reboot", []) + def test_tag_cleanup_is_planned_from_a_find_not_previewed(self): + # #618: it needs a find's findings and a selection; without this + # refusal it would fall through to the unused-components plan. + self.assertIn("tag_cleanup", maintenance.MAINTENANCE_OPERATIONS) + with self.assertRaises(ValueError): + self.db.preview_maintenance("tag_cleanup", []) + def test_same_library_gives_the_same_fingerprint(self): self.populate() for operation in OPERATIONS: @@ -437,6 +444,27 @@ class TestApply(MaintenanceDatabaseCase): draft.operation, draft.fingerprint, draft.targets, roots ) + def test_tag_cleanup_apply_runs_the_per_target_rechecks(self): + from database import tag_cleanup + + with self.db.model.get_connection() as conn: + conn.execute("INSERT INTO tags(name) VALUES('a, b'), ('ghost')") + found = tag_cleanup.find_tag_cleanup(self.db_path) + select = { + r: [f["tag_id"] for f in found["rules"][r]] for r in ("comma", "unused") + } + draft = tag_cleanup.plan_tag_cleanup(self.db_path, found, select) + with self.db.model.get_connection() as conn: + conn.execute("UPDATE tags SET name='Ghost' WHERE name='ghost'") + result = self.db.apply_maintenance( + "tag_cleanup", draft.fingerprint, draft.targets, [] + ) + self.assertEqual([r["name"] for r in result["rows"]], ["a, b"]) + self.assertEqual( + [(k["name"], k["reason"]) for k in result["kept"]], + [("ghost", "renamed since the review")], + ) + def test_unused_components_apply_removes_exactly_the_reviewed_prompts(self): first, second = self.save("One"), self.save("Two") draft = self.preview("unused_components") diff --git a/tests/test_tag_cleanup.py b/tests/test_tag_cleanup.py new file mode 100644 index 00000000..4ec379b6 --- /dev/null +++ b/tests/test_tag_cleanup.py @@ -0,0 +1,432 @@ +"""Tag cleanup rules (#618, ``database/tag_cleanup.py``). + +Two rules ship: tags containing a comma (removed from every owner and +deleted; a ``lora:`` tag is never one) and tags with no links (deleted). A +tag belongs to the first rule that finds it. A find reads one snapshot; a +plan re-reads each selected finding and protects the ones that changed; the +apply rechecks every target in the caller's transaction and keeps the ones +that changed, with their reason, while the rest still apply. +""" + +import hashlib +import json +import os +import sqlite3 +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from database import tag_cleanup +from database.operations import PromptDatabase +from utils.hashing import generate_prompt_hash + +try: + from tests.open_handles import assert_closed +except ImportError: # discovered with tests/ as the top-level directory + from open_handles import assert_closed + + +class TagCleanupCase(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(os.path.realpath(self.temp.name)) + self.db_path = str(self.root / "prompts.db") + self.db = PromptDatabase(self.db_path) + self.epoch = self.db.get_execution_epoch() + + def tearDown(self): + self.db.close_all() + assert_closed(self, self.root) + self.temp.cleanup() + + def save(self, text, tags): + return self.db.save_prompt( + text, prompt_hash=generate_prompt_hash(text), tags=tags + ) + + def add_unused(self, *names): + with self.db.model.get_connection() as conn: + for name in names: + conn.execute("INSERT INTO tags(name) VALUES(?)", (name,)) + + def image(self, name, tags, digest="a"): + locator = os.path.normcase(str(self.root / name)) + self.db.replace_image_tags( + locator=locator, + sha256=hashlib.sha256(digest.encode()).hexdigest(), + size=1, + mtime_ns=1, + expected_epoch=self.db.get_execution_epoch(), + expected_tag_revision=0, + tags=tags, + ) + return locator + + def image_with(self, name, tag): + """An image set carrying ``tag``, which the image API refuses when it + holds a comma: the link row is written as older builds could.""" + self.image(name, ["placeholder"], digest=name) + with self.db.model.get_connection() as conn: + conn.execute("INSERT OR IGNORE INTO tags(name) VALUES(?)", (tag,)) + conn.execute( + "INSERT INTO media_image_tags(byte_id, tag_id, position) " + "SELECT b.id, t.id, 1 FROM media_annotation_bytes b, tags t " + "WHERE t.name=? AND b.sha256=?", + (tag, hashlib.sha256(name.encode()).hexdigest()), + ) + + def tag_id(self, name): + with self.db.model.get_connection() as conn: + row = conn.execute("SELECT id FROM tags WHERE name=?", (name,)).fetchone() + return row[0] if row else None + + def names(self): + with self.db.model.get_connection() as conn: + return sorted(r[0] for r in conn.execute("SELECT name FROM tags")) + + def find(self): + return tag_cleanup.find_tag_cleanup(self.db_path) + + def found(self, rule): + return [f["name"] for f in self.find()["rules"][rule]] + + def plan(self, result, select): + return tag_cleanup.plan_tag_cleanup(self.db_path, result, select) + + def apply(self, targets): + with self.db._pair_transaction() as conn: + return tag_cleanup.apply_tag_cleanup(conn, targets) + + def select_all(self, result, rule): + return {rule: [f["tag_id"] for f in result["rules"][rule]]} + + +class TestRegistry(TagCleanupCase): + def test_rules_ship_in_order_with_their_copy(self): + self.assertEqual([r.id for r in tag_cleanup.RULES], ["comma", "unused"]) + comma, unused = tag_cleanup.RULES + self.assertEqual(comma.title, "Tags containing a comma") + self.assertEqual(unused.title, "Tags with no links") + for rule in tag_cleanup.RULES: + for text in (rule.explanation, rule.action_label): + self.assertTrue(text and "\n" not in text) + self.assertIs(comma.apply, unused.apply) + + +class TestFinders(TagCleanupCase): + def test_comma_rule_finds_ascii_and_fullwidth_commas(self): + self.save("a", ["score_9, score_8_up", "clean"]) + self.save("b", ["赛博朋克,霓虹", "realistic,"]) + self.assertEqual( + self.found("comma"), ["realistic,", "score_9, score_8_up", "赛博朋克,霓虹"] + ) + + def test_comma_rule_skips_lora_identity_tags(self): + # Maintainer ruling Q1: a lora: tag is never a comma finding. + self.save("a", ["lora:Style, v2", "a, b"]) + self.add_unused("lora:Old, model") + found = self.find() + self.assertEqual([f["name"] for f in found["rules"]["comma"]], ["a, b"]) + # The unused rule still lists an unused lora: tag. + self.assertEqual( + [f["name"] for f in found["rules"]["unused"]], ["lora:Old, model"] + ) + + def test_unused_rule_counts_prompt_pair_and_image_links(self): + self.save("a", ["on-prompt"]) + self.db.save_prompt_pair("pos", "neg", tags=["on-pair"]) + self.image("one.png", ["on-image"]) + self.add_unused("nowhere", "Also nowhere") + self.assertEqual(self.found("unused"), ["Also nowhere", "nowhere"]) + + def test_an_autotag_mark_is_not_a_link(self): + self.image("one.png", [], digest="z") + with self.db.model.get_connection() as conn: + byte = conn.execute("SELECT id FROM media_annotation_bytes").fetchone()[0] + conn.execute("INSERT INTO media_image_autotags(byte_id) VALUES(?)", (byte,)) + self.add_unused("lonely") + self.assertEqual(self.found("unused"), ["lonely"]) + + def test_a_comma_tag_without_links_is_listed_once_under_comma(self): + self.add_unused("a, b", "plain") + found = self.find() + self.assertEqual([f["name"] for f in found["rules"]["comma"]], ["a, b"]) + self.assertEqual([f["name"] for f in found["rules"]["unused"]], ["plain"]) + self.assertEqual(found["totals"], {"comma": 1, "unused": 1}) + + def test_findings_carry_counts_saved_views_and_a_links_hash(self): + prompt = self.save("a", ["x, y"]) + self.save("b", ["x, y"]) + self.db.save_prompt_pair("pos", "neg", tags=["x, y"]) + self.image_with("one.png", "x, y") + self.add_unused("ghost") + self.db.create_saved_view( + "images", + "Ghosts", + { + "q": "", + "category": "", + "sort": "newest", + "source": "all", + "folder": "", + "media": "all", + "tags": ["ghost"], + "favorites": False, + "collection": "", + }, + ) + found = self.find() + [comma] = found["rules"]["comma"] + self.assertEqual( + {k: comma[k] for k in ("rule", "name", "prompts", "pairs", "images")}, + {"rule": "comma", "name": "x, y", "prompts": 2, "pairs": 1, "images": 1}, + ) + self.assertEqual(comma["saved_views"], 0) + self.assertEqual(comma["tag_id"], self.tag_id("x, y")) + self.assertRegex(comma["links"], r"^[0-9a-f]{64}$") + self.assertEqual( + tag_cleanup.finding_detail(comma), "2 prompts · 1 pair · 1 image" + ) + [ghost] = found["rules"]["unused"] + self.assertEqual(ghost["saved_views"], 1) + self.assertEqual(ghost["links"], tag_cleanup.NO_LINKS) + self.assertEqual( + tag_cleanup.finding_detail(ghost), "no links · in 1 saved view" + ) + self.assertIsNotNone(prompt) + + def test_cap_holds_the_first_findings_by_name_and_totals_stay_exact(self): + self.add_unused("b", "A", "c", "d") + with patch.object(tag_cleanup, "MAX_FINDINGS", 2): + found = self.find() + self.assertEqual([f["name"] for f in found["rules"]["unused"]], ["A", "b"]) + self.assertEqual(found["totals"]["unused"], 4) + + def test_find_writes_nothing_and_closes_its_connection(self): + self.add_unused("a, b") + before = self.names() + with patch.object(sqlite3, "connect", wraps=sqlite3.connect) as connect: + self.find() + self.assertEqual(connect.call_count, 1) + self.assertEqual(self.names(), before) + + +class TestPlan(TagCleanupCase): + def test_plan_lists_targets_scope_and_details(self): + self.save("a", ["x, y"]) + self.save("b", ["x, y", "q, r"]) + self.add_unused("ghost") + found = self.find() + draft = self.plan(found, self.select_all(found, "comma")) + self.assertEqual(draft.operation, "tag_cleanup") + self.assertEqual( + [(t["rule"], t["name"]) for t in draft.targets], + [("comma", "q, r"), ("comma", "x, y")], + ) + self.assertEqual( + draft.scope, + { + "count": 2, + "label": "Delete 2 tags (removed from 3 prompts, 0 pairs and 0 images)", + }, + ) + self.assertEqual(draft.protected, {"count": 0, "reasons": []}) + self.assertEqual( + draft.media, {"deletes_files": False, "label": "No files are removed"} + ) + self.assertEqual( + draft.details[0], + {"label": "q, r", "detail": "Tags containing a comma · 1 prompt"}, + ) + self.assertTrue(draft.fingerprint.startswith("sha256:")) + + def test_one_tag_reads_in_the_singular(self): + self.add_unused("ghost") + found = self.find() + draft = self.plan(found, self.select_all(found, "unused")) + self.assertEqual( + draft.scope["label"], + "Delete 1 tag (removed from 0 prompts, 0 pairs and 0 images)", + ) + + def test_a_finding_changed_since_the_search_is_protected(self): + first = self.save("a", ["x, y"]) + second = self.save("b", ["q, r"]) + found = self.find() + # Moved to another prompt: the count stays 1, the links differ. + with self.db.model.get_connection() as conn: + conn.execute( + "UPDATE prompt_tags SET prompt_id=? WHERE prompt_id=? AND tag_id=?", + (second, first, self.tag_id("x, y")), + ) + draft = self.plan(found, self.select_all(found, "comma")) + self.assertEqual([t["name"] for t in draft.targets], ["q, r"]) + self.assertEqual( + draft.protected, + {"count": 1, "reasons": ["1 tag changed since the search"]}, + ) + self.assertEqual( + [(h["name"], h["reason"]) for h in tag_cleanup.held_rows(draft)], + [("x, y", "changed since the search")], + ) + + def test_a_renamed_or_deleted_finding_is_protected(self): + self.add_unused("ghost", "spirit") + found = self.find() + with self.db.model.get_connection() as conn: + conn.execute("UPDATE tags SET name='GHOST' WHERE name='ghost'") + conn.execute("DELETE FROM tags WHERE name='spirit'") + draft = self.plan(found, self.select_all(found, "unused")) + self.assertEqual(draft.targets, []) + self.assertEqual( + draft.protected["reasons"], ["2 tags changed since the search"] + ) + + +class TestApply(TagCleanupCase): + def planned(self, rule): + found = self.find() + return self.plan(found, self.select_all(found, rule)).targets + + def test_apply_deletes_the_tag_and_its_three_kinds_of_links(self): + prompt = self.save("a", ["x, y", "keep"]) + pair = self.db.save_prompt_pair("pos", "neg", tags=["x, y"]) + self.image_with("one.png", "x, y") + with self.db.model.get_connection() as conn: + byte = conn.execute("SELECT id FROM media_annotation_bytes").fetchone()[0] + conn.execute("INSERT INTO media_image_autotags(byte_id) VALUES(?)", (byte,)) + revision = conn.execute( + "SELECT image_index_revision FROM media_annotation_metadata" + ).fetchone()[0] + targets = self.planned("comma") + result = self.apply(targets) + self.assertEqual(result["changed"], 1) + self.assertEqual([r["name"] for r in result["rows"]], ["x, y"]) + self.assertEqual(result["kept"], []) + self.assertIsNone(self.tag_id("x, y")) + with self.db.model.get_connection() as conn: + for table in ("prompt_tags", "prompt_pair_tags", "media_image_tags"): + names = conn.execute( + f"SELECT t.name FROM {table} x JOIN tags t ON t.id=x.tag_id" + ).fetchall() + self.assertNotIn(("x, y",), [tuple(n) for n in names], table) + self.assertEqual( + conn.execute( + "SELECT tag_revision FROM media_annotation_bytes" + ).fetchone()[0], + 2, + ) + self.assertEqual( + conn.execute( + "SELECT image_index_revision FROM media_annotation_metadata" + ).fetchone()[0], + revision + 1, + ) + self.assertEqual( + conn.execute("SELECT COUNT(*) FROM media_image_autotags").fetchone()[0], + 1, + ) + self.assertIsNotNone(self.db.get_prompt_by_id(prompt)) + self.assertIsNotNone(self.db.get_prompt_pair(pair)) + self.assertIn("keep", self.names()) + + def test_saved_views_are_never_rewritten(self): + self.add_unused("ghost") + state = { + "q": "", + "category": "", + "sort": "newest", + "tags": ["ghost"], + "tag_mode": "all", + "folder": "", + } + self.db.create_saved_view("library", "Ghosts", state) + self.apply(self.planned("unused")) + [view] = self.db.list_saved_views() + self.assertEqual(view["state"]["tags"], ["ghost"]) + + def test_each_recheck_keeps_the_target_with_its_reason(self): + self.add_unused("gone", "renamed", "used") + first = self.save("first", ["moved, tag"]) + second = self.save("second", ["anchor"]) + self.save("third", ["relinked, tag"]) + unused = self.planned("unused") + comma = self.planned("comma") + with self.db.model.get_connection() as conn: + conn.execute("DELETE FROM tags WHERE name='gone'") + conn.execute("UPDATE tags SET name='Renamed' WHERE name='renamed'") + conn.execute( + "INSERT INTO prompt_tags(prompt_id, tag_id) VALUES(?, ?)", + (first, self.tag_id("used")), + ) + # Same count, other prompt: its links changed. + conn.execute( + "UPDATE prompt_tags SET prompt_id=? WHERE prompt_id=? AND tag_id=?", + (second, first, self.tag_id("moved, tag")), + ) + result = self.apply(unused + comma) + kept = {k["name"]: k["reason"] for k in result["kept"]} + self.assertEqual( + kept, + { + "gone": "already deleted", + "renamed": "renamed since the review", + "used": "it is used now", + "moved, tag": "its links changed since the review", + }, + ) + # The rest of the plan still applied. + self.assertEqual([r["name"] for r in result["rows"]], ["relinked, tag"]) + self.assertEqual(result["changed"], 1) + self.assertIsNone(self.tag_id("relinked, tag")) + + def test_the_last_tag_is_kept_while_legacy_json_tags_remain(self): + self.add_unused("only") + with self.db.model.get_connection() as conn: + conn.execute( + "INSERT INTO prompts(text, tags) VALUES('legacy', ?)", + (json.dumps(["old"]),), + ) + result = self.apply(self.planned("unused")) + self.assertEqual( + [(k["name"], k["reason"]) for k in result["kept"]], + [("only", "kept so the old tag migration does not run again")], + ) + self.assertEqual(self.names(), ["only"]) + + def test_the_last_tag_goes_when_no_legacy_tags_remain(self): + self.add_unused("only") + result = self.apply(self.planned("unused")) + self.assertEqual(result["changed"], 1) + self.assertEqual(self.names(), []) + + def test_an_exception_rolls_everything_back(self): + self.add_unused("a", "b") + targets = self.planned("unused") + calls = [] + real = tag_cleanup._delete_target + + def fail_second(conn, target): + calls.append(target["name"]) + if len(calls) == 2: + raise sqlite3.OperationalError("disk I/O error") + real(conn, target) + + with patch.object(tag_cleanup, "_delete_target", fail_second): + with self.assertRaises(sqlite3.OperationalError): + self.apply(targets) + self.assertEqual(self.names(), ["a", "b"]) + + def test_names_with_quotes_and_percent_signs(self): + name = 'it\'s 100% "real", ok' + self.save("a", [name]) + self.add_unused("50%_off") + self.assertEqual(self.found("comma"), [name]) + self.assertEqual(self.found("unused"), ["50%_off"]) + self.apply(self.planned("comma") + self.planned("unused")) + self.assertEqual(self.names(), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_vocabulary.py b/tests/test_vocabulary.py index d3036371..fd3b83c7 100644 --- a/tests/test_vocabulary.py +++ b/tests/test_vocabulary.py @@ -871,6 +871,18 @@ class TestVocabularyTagCommands(unittest.TestCase): ], 3, ) + with self.db.model.get_connection() as conn: + # The sets that carried it moved revision (a Tag dialog opened + # before sees tag-conflict); so did the image index once. + self.assertEqual( + sorted( + r[0] + for r in conn.execute( + "SELECT tag_revision FROM media_annotation_bytes" + ) + ), + [2, 2, 2], + ) renamed = self.command( "rename_vocabulary_tag", self.tag_id("keep"), diff --git a/tests/trash_route_audit.py b/tests/trash_route_audit.py index ab5a5186..190bf8bc 100644 --- a/tests/trash_route_audit.py +++ b/tests/trash_route_audit.py @@ -103,6 +103,9 @@ ROUTE_AUDIT = { "POST /prompt_manager/maintenance/apply", ), "no media file": ( + # #618: tag cleanup reads and deletes tag rows only. + "POST /prompt_manager/jobs/tag_cleanup", + "GET /prompt_manager/maintenance/tag_cleanup/{job_id}", "DELETE /prompt_manager/collections/{collection_id}", "DELETE /prompt_manager/delete/{prompt_id}", "DELETE /prompt_manager/pairs/{pair_id}",