* feat(review): add review queue schema with restore validation
Add the Needs review schema group (media_review_metadata,
media_review_items, media_review_decisions) beside the image annotation
group it cites. review_schema_error validates the catalog, columns,
foreign keys, row values and canonical 8 MiB evidence read-only;
migrate_review_state installs it in a SAVEPOINT after the annotation
group, and verify_database_file requires it under require_library_state.
A review group without a valid annotation group is refused. Decisions
null their pair and image navigation through indexes when those are
deleted. Old backups and annotation-era backups restore and gain the
group; browser fixtures clear the new tables on reset.
* feat(review): persist ambiguous sampler evidence from scans and new outputs
The output scan and the live monitor now queue every file the ingestion
resolver finds ambiguous for Needs review. The file is captured, its metadata
is read again from the capture and resolved with the default profile, and only
an ambiguous result is stored, bound to the capture's annotation byte record
and fenced by its storage epoch. Evidence holds one hashed projection per
selectable candidate; none, more than 16 or over 8 MiB is a limited item.
Recording is idempotent per bytes and evidence and never touches a decision.
Scan statuses, counters, outcome rows and legacy SSE events are unchanged; the
job scope gains review_items/review_errors and the log a Needs review line.
The monitor records after its fallback link, best effort.
* feat(review): explicit association decisions with compatible linking
Needs review gains its queue reads and decisions:
- GET /prompt_manager/review/items lists pending items oldest first with
the exact pending total and an HMAC keyset cursor bound to the storage
epoch and the review index revision.
- GET /prompt_manager/review/items/{id} adds the candidates (role texts,
label, selectability), the dependency fingerprint and the digest.
- POST /prompt_manager/review/items/{id}/decision applies a candidate only
for a capture of the item's bytes that the current file still hashes to
and whose evidence is unchanged, through the ingester's compatible-only
rules in the same transaction as the decision row; a conflict writes
nothing. Leave unresolved records the decision and links nothing.
ingest_resolved_pair keeps its contract; its body moves into
_ingest_resolved_pair_in, which runs in the caller's transaction.
Items keep the file's recorded spelling so targets keep their case on
Windows, and a rescan skips the copy and hash of a file whose size and
mtime match the bytes an item already cites.
* fix(review): build the spelling validation test from native paths
On Windows the locator is case-folded and uses backslashes, so the fixed
POSIX pair /out/a.png no longer folded to itself and the new spelling
check refused the good case. The test now spells a mixed-case native path
and folds it with os.path.normcase, and also refuses a locator of another
file.
* fix(review): Apply sees the file under every spelling and rechecks only its choice
Apply now finds the legacy rows of the same physical file however its root
is reached. The roots are real paths while the monitor links under the
directory it watches, so a symlinked or junctioned root, subst or a mapped
drive used to hide the monitor's row and Apply added a second, differently
linked row. Same-name rows are resolved to their physical identity
(normcase(realpath), else samefile); the dependency fingerprint covers all
of them, two rows refuse the choice, one row is enriched under the
ingester's compatible-only rules, and a same-name row the request did not
classify is a changed association.
Apply re-verifies only what the decision depends on: the bytes are still
ambiguous and still offer the chosen candidate. A resolver change that
rewords the reason or reorders candidates leaves pending items applicable.
The resolver version is one constant in prompt_pair_resolver, shared by
ingestion provenance and Needs review.
The transaction's byte check receives the re-hashed digest (or the body's
for Leave unresolved), every Apply refusal branch is tested with zero
writes, and the root listing and realpath calls run on a worker thread.
* fix(review): validate stored review evidence once per startup
Startup used to run the full review validation twice (the early guard and
the install) and the annotation group's row checks inside each, so every
evidence document was parsed and re-encoded twice. The early guard is now
catalog-only (a review group without annotation tables), and the install
validates the group once, trusting the annotation group it has just
validated. The evidence predicate no longer pattern-scans every document in
SQL, because the streamed canonical pass proves it, and the codec is built
once.
Measured on a database with 40,000 items of 4 KiB evidence: startup open
went from 7.7 s to 2.5 s. A test pins one evidence pass per reopen.
Restore and verify_database_file keep the full validation.
* fix(review): keep one capture worker for interactive requests
Needs review recording from the scan and the monitor shared the capture
store's two workers with the Tag dialog and Apply, so a busy scan could
answer a user's preview or decision with "Too many previews are open".
Background captures now never take the last worker or capture slot, and
wait up to two seconds for room before counting the file as not added.
Interactive captures are admitted or refused at once, as before.
* fix(review): refresh the recorded spelling when a file is seen under a new one
A case-only rename on Windows or macOS keeps size and mtime_ns, so the
rescan skipped the file and the item kept the old spelling. Its target was
then formatted from a name the directory no longer lists, the capture
refused it, and the item stayed pending with no way to apply it. The skip
path and a duplicate insert now record the current spelling for every item
at the locator and move the review index revision; item revisions do not
change, so an open decision stays valid. Tested under case-folding
semantics on every platform.
* fix(review): final capture store close and recoverable stale cursors
Closing the capture store at shutdown now runs under the store lock and is
final: a monitor recording or scan batch still in flight gets a capture
error instead of creating a new temp directory and restore subscription
after the cleanup.
A well-formed queue cursor this process cannot verify (opened before a
ComfyUI restart, whose cursor secret is per process) now answers 409
review-conflict with the current total, like any other stale page, instead
of an uncoded 400. Malformed cursors stay 400.
* fix(review): make only the shutdown cleanup final
The previous commit made every close of the capture store final, which
also refused the explicit closes that swap in a fresh store. Only the host's
on_cleanup hook is final now; an observe after it answers a coded capture
error instead of an unhandled 500.
* refactor(admin): move Needs review recording into its own mixin
_record_scanned_review, _record_review_sync, record_review_file and
_log_review_items move unchanged from py/api/admin.py to
py/api/review_recording.py (ReviewRecordingMixin), keeping admin.py from
growing further past the size ceiling. No behaviour change.
* fix(review): record the review fix round and the skip's residual risks in TESTING.md
The Needs review paragraphs now state the rescan skip's residual risks (an
in-place rewrite that keeps size and mtime_ns is never re-queued; a deleted
or moved file leaves its pending item counted), the physical identity rule
for Apply, the candidate-only recheck and shared resolver version, the
spelling refresh, background capture admission, the final shutdown close,
the stale-cursor answer and the measured startup validation cost.
* fix(review): refuse monitor recording beside record-changing jobs
System S1 (#289) gives every record change a registry admission class. The
scan already records Needs review items under its own records job. The
monitor's recording lasts one file and is not a job, so it now checks the
records admission: while a records or guarded job or hold runs it records
nothing, logs that the file waits for the next scan, and answers deferred.
The fallback link stands and the next "new" scan reads the ambiguous file
again, because a fallback link is not a resolved one.
JobRegistry.blocker and active iterate a snapshot of the jobs, since the
monitor's worker thread now asks them too.
* test(backup): wait for the restore, not a 5 s timer, in the thread test
test_database_is_usable_from_every_thread_after_restore let its worker
wait 5 s for the restore. On a stalled Windows runner (py3.11, where the
previous restore test also took 25 s instead of 0.3 s) the restore took
longer, the wait timed out, and the worker read the old database before
the restore ran. The worker now waits for the event under a 120 s bound
that only a hung test reaches, reports a timeout as an error, and the
main thread releases it even when the restore raises. With a restore
delayed by 6 s the old test fails and the new one passes.
* fix(review): store non-finite evidence as null and count pending items
canonical_evidence now follows main's non-finite policy (#303): NaN and
±Infinity are written as null instead of raising, so a NaN-stamped graph
never turns a review item limited. The System Overview reports the review
queue's pending total in needs_review.pending, read in the same snapshot
as the Library counts.
* fix(review): show the pending count on the System Overview review row
The Overview's review row now reads "N ambiguous image links" with the
concept's line, from needs_review.pending. Its Review metadata action
stays aria-disabled until the Needs review page ships. The system specs
and their concept comparison follow the real count.
* fix(system): answer the Overview and Statistics only after every read ended
asyncio.gather answered at the first failed read while its sibling
executor reads were still inside SQLite. In the suite the test teardown
then deleted the database under the running read, and py3.10 on Ubuntu
segfaulted in get_statistics (test_statistics_failure_is_an_error_envelope).
Both routes now wait for all their reads before answering.
* fix(review): queue only ambiguous files that nothing links, and heal the queue
The maintainer's live scan (19,908 files, scope "new") reported 4,677 files
under Needs review, but the queue held 10,232 items: every file the strict
resolver found ambiguous was queued, including the ones the legacy
browser-parser fallback then linked (all sampled "added" rows) and the ones
already linked to a known prompt (135 of 200 sampled "known" rows).
A file is now queued only when its final outcome is ambiguous and unlinked:
the resolver finds it ambiguous, the fallback links nothing and no saved row
links it already. An ambiguous file that a saved row links is reported as
unchanged ("Already linked to its prompt"), not as Needs review.
The queue heals itself. After each batch, the scan removes the pending items
of every listed file (read, or skipped as known) that a saved row now links.
The monitor does the same for each ambiguous output it links, and never
queues one. Only an undecided item is removed (pending, revision 0, no
decision row), so a decision is never deleted or changed and the schema
needs no new state.
The scan job's scope.review_items now counts this scan's files that are in
the pending queue after it, new or already there, so it agrees with the
review group's ambiguous rows and with the queue total. review_added and
review_settled are new, and the log gains "already in Needs review" and
"left Needs review · now linked" lines. A duplicate whose item is decided is
reported as "decided" and is not counted.
* fix(review): never queue an ambiguous file with nothing to choose
The maintainer's live queue held 39 items whose candidates all read
"unresolved" ("No positive / No negative"). An ambiguous result is now
reviewable only when at least two candidates are resolved with non-blank
positive text. With none the file could not be traced; with exactly one,
the untraced branches may still have made the file, so that text is not
certain either. Both are reported unresolved, never linked and never
queued (also the A1111 two-delimiter case, which has no candidates).
A rescan removes the pending items of such files whose own evidence
offers no choice, with the same safe delete as the linked settle
(pending, revision 0, no decision row). A limited item (over 16 candidates) that holds at least two
candidates is kept. The job scope gains review_untraced and the log
"= N images left Needs review · nothing to choose".
* test(scan): pin only the per-source scope keys beside the review counters
* test(system): match the scan scope keys beside the review counters
623 lines
25 KiB
Python
623 lines
25 KiB
Python
"""Scan scope (#249 Activity-2 Task 4): new and unresolved files by default.
|
|
|
|
A "Scan for metadata" job started without ``scope`` (or with ``"new"``) skips
|
|
the files the Library already links with a resolved link, before their
|
|
metadata is read, and counts them as Already known. ``"all"`` reads every file
|
|
again, as the legacy ``/prompt_manager/scan`` route always does.
|
|
"""
|
|
|
|
import asyncio
|
|
import json
|
|
import os
|
|
import sqlite3
|
|
import unittest
|
|
from unittest.mock import patch
|
|
|
|
try:
|
|
from tests.test_api_admin import AdminAPITestCase, _sse_payloads, _write_png
|
|
except ImportError: # discovered with tests/ as the top-level directory
|
|
from test_api_admin import AdminAPITestCase, _sse_payloads, _write_png
|
|
|
|
from database import operations # noqa: E402
|
|
from database.pair_ingestion import ingest_resolved_pair # noqa: E402
|
|
from py.config import GalleryConfig # noqa: E402
|
|
from utils.prompt_pair_resolver import resolve_prompt_pair # noqa: E402
|
|
|
|
SKIPPED_DETAIL = "Skipped · already linked"
|
|
ON_DISK = object() # _link_resolved: store the file's size on disk
|
|
|
|
|
|
def _graph(text):
|
|
return {
|
|
"1": {"class_type": "CLIPTextEncode", "inputs": {"text": text}},
|
|
"2": {"class_type": "CLIPTextEncode", "inputs": {"text": "bad"}},
|
|
"3": {
|
|
"class_type": "KSampler",
|
|
"inputs": {"positive": ["1", 0], "negative": ["2", 0]},
|
|
},
|
|
}
|
|
|
|
|
|
def _scope_part(scope):
|
|
"""The per-source scope keys this module pins (other features add counters)."""
|
|
return {key: scope[key] for key in ("files", "roots", "output_folders")}
|
|
|
|
|
|
class ScanScopeTestCase(AdminAPITestCase):
|
|
"""Helpers: link files the way the scan and the monitor do, spy on reads."""
|
|
|
|
def _link_resolved(self, path, text, size=ON_DISK):
|
|
"""``path`` linked with a resolved pair link (what a resolved scan writes).
|
|
|
|
The row stores ``size`` as its file size: by default the file's size on
|
|
disk (None when the file does not exist).
|
|
"""
|
|
if size is ON_DISK:
|
|
size = os.path.getsize(path) if os.path.exists(path) else None
|
|
metadata = {"prompt": _graph(text)}
|
|
if size is not None:
|
|
metadata["file_info"] = {"size": size}
|
|
result = ingest_resolved_pair(
|
|
self.api.db, str(path), metadata, resolve_prompt_pair(metadata)
|
|
)
|
|
self.assertEqual(result["status"], "added")
|
|
|
|
def _link_without_pair(self, path, text):
|
|
"""``path`` linked to a prompt with no pair link (fallback / FIFO link)."""
|
|
prompt_id = self.api.db.save_prompt(text, None, [], None, None)
|
|
self.assertTrue(self.api.db.link_image_to_prompt(prompt_id, str(path)))
|
|
return prompt_id
|
|
|
|
def _spy_reads(self):
|
|
reads = []
|
|
original = self.api._extract_comfyui_metadata
|
|
|
|
def spy(path):
|
|
reads.append(os.path.basename(path))
|
|
return original(path)
|
|
|
|
self.api._extract_comfyui_metadata = spy
|
|
return reads
|
|
|
|
async def _scan(self, body=None):
|
|
kwargs = {} if body is None else {"json": body}
|
|
resp = await self.client.request("POST", "/prompt_manager/jobs/scan", **kwargs)
|
|
data = await resp.json()
|
|
self.assertEqual(resp.status, 202, data)
|
|
await asyncio.wait_for(self.api._scan_job.task, 10)
|
|
detail = await self.client.request(
|
|
"GET", f"/prompt_manager/jobs/{data['job']['id']}"
|
|
)
|
|
return (await detail.json())["job"]
|
|
|
|
|
|
class TestScanScope(ScanScopeTestCase):
|
|
|
|
async def test_new_scope_skips_known_resolved_files_without_reading_them(self):
|
|
GalleryConfig.MONITORING_DIRECTORIES = [self._root(self.output_dir)]
|
|
known = self.output_dir / "known.png"
|
|
_write_png(known, prompt_text="a red square")
|
|
_write_png(self.output_dir / "new.png", prompt_text="a blue circle")
|
|
self._link_resolved(known, "a red square")
|
|
reads = self._spy_reads()
|
|
|
|
job = await self._scan()
|
|
|
|
self.assertEqual(reads, ["new.png"])
|
|
self.assertEqual(job["scope"]["files"], "new")
|
|
self.assertEqual(job["counters"]["known"], 1)
|
|
self.assertEqual(job["counters"]["added"], 1)
|
|
self.assertEqual(job["processed"], 2)
|
|
self.assertEqual(
|
|
job["outcomes"]["known"],
|
|
[
|
|
{
|
|
"path": "known.png",
|
|
"root": "output",
|
|
"root_index": 0,
|
|
"detail": SKIPPED_DETAIL,
|
|
}
|
|
],
|
|
)
|
|
self.assertIn(f"= output/known.png · {SKIPPED_DETAIL}", "\n".join(job["log"]))
|
|
self.assertTrue(
|
|
job["log"][0].endswith(
|
|
"Scan started · 1 output folder · new and unresolved files"
|
|
)
|
|
)
|
|
legacy = self.api._scan_job.last_event
|
|
self.assertEqual((legacy["processed"], legacy["unchanged"]), (2, 1))
|
|
self.assertTrue(job["status_line"].startswith("Processing file 2 of 2"))
|
|
|
|
async def test_whole_known_batch_skips_the_executor_reads(self):
|
|
from py.api import admin
|
|
|
|
GalleryConfig.MONITORING_DIRECTORIES = [self._root(self.output_dir)]
|
|
for name in ("a.png", "b.png"):
|
|
_write_png(self.output_dir / name, prompt_text=f"prompt {name}")
|
|
self._link_resolved(self.output_dir / name, f"prompt {name}")
|
|
_write_png(self.output_dir / "c.png", prompt_text="prompt c")
|
|
reads = self._spy_reads()
|
|
|
|
with patch.object(admin, "SCAN_BATCH_SIZE", 1):
|
|
job = await self._scan({"scope": "new"})
|
|
|
|
self.assertEqual(reads, ["c.png"])
|
|
self.assertEqual(job["counters"]["known"], 2)
|
|
self.assertEqual(job["counters"]["added"], 1)
|
|
|
|
async def test_unresolved_files_are_rescanned_in_new_scope(self):
|
|
GalleryConfig.MONITORING_DIRECTORIES = [self._root(self.output_dir)]
|
|
names = ("fallback.png", "conflict.png", "unlinked.png")
|
|
for name in names:
|
|
_write_png(self.output_dir / name, prompt_text=f"text of {name}")
|
|
# Linked without a resolved pair link (the monitor's fallback / FIFO link).
|
|
self._link_without_pair(self.output_dir / "fallback.png", "text of fallback")
|
|
# Resolved once, then also linked to a second prompt: ambiguous.
|
|
conflict = self.output_dir / "conflict.png"
|
|
self._link_resolved(conflict, "text of conflict.png")
|
|
self._link_without_pair(conflict, "another prompt")
|
|
reads = self._spy_reads()
|
|
|
|
job = await self._scan()
|
|
|
|
self.assertEqual(sorted(reads), sorted(names))
|
|
self.assertNotIn(SKIPPED_DETAIL, json.dumps(job["outcomes"]))
|
|
|
|
async def test_all_scope_reads_everything(self):
|
|
GalleryConfig.MONITORING_DIRECTORIES = [self._root(self.output_dir)]
|
|
known = self.output_dir / "known.png"
|
|
_write_png(known, prompt_text="a red square")
|
|
self._link_resolved(known, "a red square")
|
|
reads = self._spy_reads()
|
|
|
|
job = await self._scan({"scope": "all"})
|
|
|
|
self.assertEqual(reads, ["known.png"])
|
|
self.assertEqual(job["scope"]["files"], "all")
|
|
self.assertEqual(job["counters"]["known"], 1)
|
|
self.assertNotEqual(job["outcomes"]["known"][0]["detail"], SKIPPED_DETAIL)
|
|
self.assertTrue(
|
|
job["log"][0].endswith("Scan started · 1 output folder · all files")
|
|
)
|
|
|
|
async def test_legacy_scan_route_reads_everything(self):
|
|
GalleryConfig.MONITORING_DIRECTORIES = [self._root(self.output_dir)]
|
|
known = self.output_dir / "known.png"
|
|
_write_png(known, prompt_text="a red square")
|
|
self._link_resolved(known, "a red square")
|
|
reads = self._spy_reads()
|
|
|
|
resp = await self.client.request("POST", "/prompt_manager/scan", data="{}")
|
|
payloads = _sse_payloads(await resp.text())
|
|
|
|
self.assertEqual(reads, ["known.png"])
|
|
self.assertEqual(self.api._scan_job.scope["files"], "all")
|
|
self.assertEqual(payloads[-1]["type"], "complete")
|
|
self.assertEqual(payloads[-1]["unchanged"], 1)
|
|
|
|
async def test_file_replaced_at_a_known_path_is_reread_and_needs_review(self):
|
|
GalleryConfig.MONITORING_DIRECTORIES = [self._root(self.output_dir)]
|
|
path = self.output_dir / "out_00012.png"
|
|
_write_png(path, prompt_text="the first prompt")
|
|
self._link_resolved(path, "the first prompt")
|
|
before = os.path.getsize(path)
|
|
# ComfyUI reused the name for a new image with another prompt.
|
|
_write_png(path, prompt_text="a much longer second prompt for the same name")
|
|
self.assertNotEqual(os.path.getsize(path), before)
|
|
reads = self._spy_reads()
|
|
|
|
job = await self._scan()
|
|
|
|
self.assertEqual(reads, ["out_00012.png"])
|
|
self.assertEqual(job["counters"]["review"], 1)
|
|
self.assertEqual(job["counters"]["known"], 0)
|
|
self.assertIn("different prompt", job["outcomes"]["review"][0]["detail"])
|
|
|
|
async def test_scanned_files_store_their_size_so_the_next_new_scan_skips(self):
|
|
GalleryConfig.MONITORING_DIRECTORIES = [self._root(self.output_dir)]
|
|
_write_png(self.output_dir / "fresh.png", prompt_text="a fresh prompt")
|
|
first = await self._scan()
|
|
self.assertEqual(first["counters"]["added"], 1)
|
|
reads = self._spy_reads()
|
|
|
|
second = await self._scan()
|
|
|
|
self.assertEqual(reads, [])
|
|
self.assertEqual(second["outcomes"]["known"][0]["detail"], SKIPPED_DETAIL)
|
|
|
|
async def test_stored_null_size_is_reread(self):
|
|
GalleryConfig.MONITORING_DIRECTORIES = [self._root(self.output_dir)]
|
|
path = self.output_dir / "old.png"
|
|
_write_png(path, prompt_text="an old prompt")
|
|
self._link_resolved(path, "an old prompt", size=None)
|
|
reads = self._spy_reads()
|
|
|
|
job = await self._scan()
|
|
|
|
self.assertEqual(reads, ["old.png"])
|
|
# The read stores the size it was missing, so the file is known next time.
|
|
self.assertEqual(job["counters"]["added"], 1)
|
|
self.assertEqual(
|
|
self.api.db.get_known_resolved_paths({str(path): os.path.getsize(path)}),
|
|
{str(path)},
|
|
)
|
|
|
|
async def test_known_set_failure_falls_back_to_reading_every_file(self):
|
|
GalleryConfig.MONITORING_DIRECTORIES = [self._root(self.output_dir)]
|
|
known = self.output_dir / "known.png"
|
|
_write_png(known, prompt_text="a red square")
|
|
self._link_resolved(known, "a red square")
|
|
reads = self._spy_reads()
|
|
|
|
def broken(files):
|
|
raise sqlite3.OperationalError("database is locked")
|
|
|
|
self.api.db.get_known_resolved_paths = broken
|
|
with self.assertLogs("prompt_manager.api", level="WARNING"):
|
|
job = await self._scan()
|
|
|
|
self.assertEqual(job["state"], "finished")
|
|
self.assertEqual(reads, ["known.png"])
|
|
self.assertIn(
|
|
"Known files could not be read · reading every file", "\n".join(job["log"])
|
|
)
|
|
|
|
async def test_empty_read_body_asks_for_the_default_scope(self):
|
|
"""A chunked POST with no bytes can read a body: still the default."""
|
|
from py.api.job_routes import _scan_request
|
|
|
|
class Request:
|
|
can_read_body = True
|
|
|
|
def __init__(self, text):
|
|
self._text = text
|
|
|
|
async def text(self):
|
|
return self._text
|
|
|
|
default = ({"files": "new", "roots": None}, None)
|
|
self.assertEqual(await _scan_request(Request("")), default)
|
|
self.assertEqual(await _scan_request(Request(" \n")), default)
|
|
self.assertEqual(
|
|
await _scan_request(
|
|
Request(
|
|
'{"scope": "all", "roots": [2, 0, 2],'
|
|
' "paths": ["output/c", "output/a", "output/c"]}'
|
|
)
|
|
),
|
|
({"files": "all", "roots": {0: "output/a", 2: "output/c"}}, None),
|
|
)
|
|
request, error = await _scan_request(Request("{"))
|
|
self.assertIsNone(request)
|
|
self.assertIsInstance(error, str)
|
|
|
|
async def test_invalid_scope_is_refused(self):
|
|
for body in ({"scope": "everything"}, {"scope": 1}, ["new"]):
|
|
with self.subTest(body=body):
|
|
resp = await self.client.request(
|
|
"POST", "/prompt_manager/jobs/scan", json=body
|
|
)
|
|
self.assertEqual(resp.status, 400)
|
|
data = await resp.json()
|
|
self.assertFalse(data["success"])
|
|
resp = await self.client.request(
|
|
"POST", "/prompt_manager/jobs/scan", data="not json"
|
|
)
|
|
self.assertEqual(resp.status, 400)
|
|
self.assertIsNone(self.api._scan_job)
|
|
|
|
|
|
class TestPerSourceScope(ScanScopeTestCase):
|
|
"""``roots``: scan only the selected effective sources (#249 S4 Task 10)."""
|
|
|
|
async def asyncSetUp(self):
|
|
await super().asyncSetUp()
|
|
self.a = self.output_dir / "a"
|
|
self.b = self.output_dir / "b"
|
|
self.a.mkdir()
|
|
self.b.mkdir()
|
|
_write_png(self.a / "in_a.png", prompt_text="a prompt in a")
|
|
_write_png(self.b / "in_b.png", prompt_text="a prompt in b")
|
|
GalleryConfig.MONITORING_DIRECTORIES = [self._root(self.a), self._root(self.b)]
|
|
|
|
async def _refused(self, body):
|
|
resp = await self.client.request("POST", "/prompt_manager/jobs/scan", json=body)
|
|
data = await resp.json()
|
|
self.assertEqual(resp.status, 400, data)
|
|
self.assertFalse(data["success"])
|
|
self.assertNotIn(self.tmpdir, json.dumps(data))
|
|
self.assertIsNone(self.api._scan_job)
|
|
self.assertEqual(self.api._jobs.list(), [])
|
|
return data
|
|
|
|
async def test_scoped_scan_only_walks_selected_root(self):
|
|
walked = []
|
|
original = self.api._collect_output_media_sync
|
|
|
|
def spy(output_dirs):
|
|
walked.append([os.path.basename(str(d)) for d in output_dirs])
|
|
return original(output_dirs)
|
|
|
|
self.api._collect_output_media_sync = spy
|
|
reads = self._spy_reads()
|
|
|
|
job = await self._scan({"scope": "all", "roots": [1], "paths": ["output/b"]})
|
|
|
|
self.assertEqual(walked, [["b"]])
|
|
self.assertEqual(reads, ["in_b.png"])
|
|
self.assertEqual(
|
|
_scope_part(job["scope"]),
|
|
{"files": "all", "roots": [1], "output_folders": 1},
|
|
)
|
|
self.assertEqual(
|
|
job["outcomes"]["added"],
|
|
[
|
|
{
|
|
"path": "in_b.png",
|
|
"root": "output/b",
|
|
"root_index": 1,
|
|
"detail": job["outcomes"]["added"][0]["detail"],
|
|
}
|
|
],
|
|
)
|
|
self.assertEqual(job["counters"]["added"], 1)
|
|
self.assertEqual(self.api._scan_job.last_event["directories"], ["output/b"])
|
|
|
|
async def test_duplicate_roots_are_one_selection(self):
|
|
job = await self._scan(
|
|
{"roots": [1, 0, 1], "paths": ["output/b", "output/a", "output/b"]}
|
|
)
|
|
self.assertEqual(job["scope"]["roots"], [0, 1])
|
|
self.assertEqual(job["scope"]["output_folders"], 2)
|
|
self.assertEqual(job["counters"]["added"], 2)
|
|
|
|
async def test_scope_line_counts_selected_folders(self):
|
|
job = await self._scan({"roots": [0], "paths": ["output/a"]})
|
|
self.assertTrue(
|
|
job["log"][0].endswith(
|
|
"Scan started · 1 output folder · new and unresolved files"
|
|
),
|
|
job["log"][0],
|
|
)
|
|
self.assertEqual(job["scope"]["output_folders"], 1)
|
|
|
|
unscoped = await self._scan({"scope": "all"})
|
|
self.assertEqual(
|
|
_scope_part(unscoped["scope"]),
|
|
{"files": "all", "roots": None, "output_folders": 2},
|
|
)
|
|
self.assertIn("Scan started · 2 output folders · all files", unscoped["log"][0])
|
|
|
|
async def _stale(self, body):
|
|
resp = await self.client.request("POST", "/prompt_manager/jobs/scan", json=body)
|
|
data = await resp.json()
|
|
self.assertEqual(resp.status, 409, data)
|
|
self.assertEqual(data["code"], "sources-changed")
|
|
self.assertFalse(data["success"])
|
|
self.assertNotIn(self.tmpdir, json.dumps(data))
|
|
self.assertIsNone(self.api._scan_job)
|
|
self.assertEqual(self.api._jobs.list(), [])
|
|
return data
|
|
|
|
async def test_index_past_the_sources_is_409_without_job(self):
|
|
await self._stale({"roots": [2], "paths": ["output/c"]})
|
|
await self._stale({"roots": [0, 64], "paths": ["output/a", "output/x"]})
|
|
|
|
async def test_stale_index_never_scans_another_source(self):
|
|
"""The list changed after the page read it: source 0 was removed, so
|
|
old index 1 (b) is past the end and old index 0 now names b."""
|
|
GalleryConfig.MONITORING_DIRECTORIES = [self._root(self.b)]
|
|
await self._stale({"roots": [1], "paths": ["output/b"]})
|
|
await self._stale({"roots": [0], "paths": ["output/a"]})
|
|
|
|
job = await self._scan({"roots": [0], "paths": ["output/b"]})
|
|
self.assertEqual(job["outcomes"]["added"][0]["root"], "output/b")
|
|
|
|
async def test_roots_need_their_paths(self):
|
|
for body in (
|
|
{"roots": [0]},
|
|
{"roots": [0], "paths": None},
|
|
{"roots": [0], "paths": "output/a"},
|
|
{"roots": [0], "paths": []},
|
|
{"roots": [0, 1], "paths": ["output/a"]},
|
|
{"roots": [0], "paths": [0]},
|
|
{"roots": [0, 0], "paths": ["output/a", "output/b"]},
|
|
):
|
|
with self.subTest(body=body):
|
|
await self._refused(body)
|
|
|
|
async def test_bool_and_float_roots_rejected(self):
|
|
for roots in (
|
|
[True],
|
|
[False],
|
|
[0.0],
|
|
[1.5],
|
|
["0"],
|
|
[None],
|
|
[-1],
|
|
[0, None],
|
|
[],
|
|
None,
|
|
0,
|
|
"0",
|
|
{"0": 0},
|
|
list(range(65)),
|
|
):
|
|
with self.subTest(roots=roots):
|
|
paths = ["output/a"] * len(roots) if isinstance(roots, list) else []
|
|
await self._refused({"roots": roots, "paths": paths})
|
|
|
|
async def test_legacy_scan_unscoped_unchanged(self):
|
|
from py.api.admin import SCAN_COUNT_KEYS
|
|
|
|
resp = await self.client.request("POST", "/prompt_manager/scan", data="{}")
|
|
payloads = _sse_payloads(await resp.text())
|
|
|
|
final = payloads[-1]
|
|
self.assertEqual(set(final), set(SCAN_COUNT_KEYS) | {"type", "directories"})
|
|
self.assertEqual(final["directories"], ["output/a", "output/b"])
|
|
self.assertEqual(final["added"], 2)
|
|
self.assertEqual(
|
|
_scope_part(self.api._scan_job.scope),
|
|
{"files": "all", "roots": None, "output_folders": 2},
|
|
)
|
|
|
|
async def test_legacy_scan_attaches_to_a_scoped_job_as_is(self):
|
|
import threading
|
|
|
|
from py.api.admin import SCAN_COUNT_KEYS
|
|
|
|
gate = threading.Event()
|
|
original = self.api._collect_output_media_sync
|
|
|
|
def gated(output_dirs):
|
|
gate.wait(5)
|
|
return original(output_dirs)
|
|
|
|
self.api._collect_output_media_sync = gated
|
|
# The legacy route has decided to attach once it streams the job.
|
|
attached = asyncio.Event()
|
|
stream = self.api._stream_scan_job
|
|
|
|
async def attaching(request, job):
|
|
attached.set()
|
|
return await stream(request, job)
|
|
|
|
self.api._stream_scan_job = attaching
|
|
resp = await self.client.request(
|
|
"POST",
|
|
"/prompt_manager/jobs/scan",
|
|
json={"roots": [0], "paths": ["output/a"]},
|
|
)
|
|
self.assertEqual(resp.status, 202)
|
|
started = (await resp.json())["job"]
|
|
legacy = asyncio.ensure_future(
|
|
self.client.request("POST", "/prompt_manager/scan", data="{}")
|
|
)
|
|
try:
|
|
await asyncio.wait_for(attached.wait(), 10)
|
|
finally:
|
|
gate.set()
|
|
payloads = _sse_payloads(await (await legacy).text())
|
|
await asyncio.wait_for(self.api._scan_job.task, 10)
|
|
|
|
self.assertEqual(self.api._scan_job.id, started["id"])
|
|
self.assertEqual(len(self.api._jobs.list()), 1)
|
|
final = payloads[-1]
|
|
self.assertEqual(set(final), set(SCAN_COUNT_KEYS) | {"type", "directories"})
|
|
self.assertEqual(final["directories"], ["output/a"])
|
|
self.assertEqual(final["added"], 1)
|
|
|
|
async def test_scoped_scan_uses_the_sources_it_was_started_with(self):
|
|
"""Sources saved after the start never change what the job walks."""
|
|
resolved = []
|
|
original = self.api._get_all_output_dirs
|
|
|
|
def counting():
|
|
resolved.append(1)
|
|
return original()
|
|
|
|
self.api._get_all_output_dirs = counting
|
|
job = await self._scan({"roots": [1], "paths": ["output/b"]})
|
|
self.assertEqual(len(resolved), 1) # the request's own resolution only
|
|
self.assertEqual(job["outcomes"]["added"][0]["root_index"], 1)
|
|
|
|
|
|
class TestKnownResolvedPaths(ScanScopeTestCase):
|
|
"""``PromptDatabase.get_known_resolved_paths``: one streamed query."""
|
|
|
|
async def test_returns_the_given_paths_that_are_known_and_resolved(self):
|
|
known, fallback = self.output_dir / "known.png", self.output_dir / "fb.png"
|
|
self._link_resolved(known, "a red square", size=10)
|
|
self._link_without_pair(fallback, "a fallback")
|
|
asked = {str(known): 10, str(fallback): 10, str(self.output_dir / "n.png"): 10}
|
|
|
|
self.assertEqual(self.api.db.get_known_resolved_paths(asked), {str(known)})
|
|
self.assertEqual(self.api.db.get_known_resolved_paths({}), set())
|
|
|
|
async def test_size_must_match_and_a_stored_null_size_is_not_known(self):
|
|
same, other = self.output_dir / "same.png", self.output_dir / "other.png"
|
|
unknown = self.output_dir / "unknown.png"
|
|
self._link_resolved(same, "same size", size=10)
|
|
self._link_resolved(other, "other size", size=10)
|
|
self._link_resolved(unknown, "no stored size", size=None)
|
|
asked = {str(same): 10, str(other): 11, str(unknown): 10}
|
|
|
|
self.assertEqual(self.api.db.get_known_resolved_paths(asked), {str(same)})
|
|
# A file the walk could not stat is not known either.
|
|
self.assertEqual(self.api.db.get_known_resolved_paths({str(same): None}), set())
|
|
|
|
async def test_row_without_file_path_matches_through_image_path(self):
|
|
known = self.output_dir / "legacy.png"
|
|
self._link_resolved(known, "a legacy row", size=10)
|
|
with sqlite3.connect(self.api.db.model.db_path) as conn:
|
|
conn.execute("UPDATE generated_images SET file_path=NULL")
|
|
conn.close()
|
|
|
|
found = self.api.db.get_known_resolved_paths({str(known): 10})
|
|
self.assertEqual(found, {str(known)})
|
|
|
|
async def test_stored_spelling_is_normalized_like_the_scanned_path(self):
|
|
known = self.output_dir / "sub" / "known.png"
|
|
self._link_resolved(known, "a red square", size=10)
|
|
spelled = os.path.join(str(self.output_dir), "sub", "..", "sub", "known.png")
|
|
with sqlite3.connect(self.api.db.model.db_path) as conn:
|
|
conn.execute("UPDATE generated_images SET file_path=?", (spelled,))
|
|
conn.close()
|
|
|
|
found = self.api.db.get_known_resolved_paths({str(known): 10})
|
|
self.assertEqual(found, {str(known)})
|
|
|
|
async def test_one_query_streamed_in_small_fetches(self):
|
|
paths = [self.output_dir / f"{index}.png" for index in range(5)]
|
|
for path in paths:
|
|
self._link_resolved(path, f"prompt {path.name}", size=10)
|
|
original = self.api.db.model.get_connection
|
|
opened = []
|
|
|
|
def counting():
|
|
opened.append(1)
|
|
return original()
|
|
|
|
self.api.db.model.get_connection = counting
|
|
with patch.object(operations, "KNOWN_PATHS_FETCH_SIZE", 2):
|
|
found = self.api.db.get_known_resolved_paths({str(p): 10 for p in paths})
|
|
self.assertEqual(found, {str(p) for p in paths})
|
|
self.assertEqual(len(opened), 1)
|
|
|
|
async def test_windows_path_case_matches_known_set(self):
|
|
stored = self.output_dir / "Sub" / "Known.PNG"
|
|
self._link_resolved(stored, "a red square", size=10)
|
|
# A row written before paths were case-folded keeps its own spelling.
|
|
with sqlite3.connect(self.api.db.model.db_path) as conn:
|
|
conn.execute(
|
|
"UPDATE generated_images SET file_path=?", (str(stored).upper(),)
|
|
)
|
|
conn.close()
|
|
asked = str(self.output_dir / "sub" / "known.png")
|
|
|
|
with patch("os.path.normcase", lambda path: path.lower()):
|
|
self.assertEqual(self.api.db.get_known_resolved_paths({asked: 10}), {asked})
|
|
if os.path.normcase("A") == "A": # a case-sensitive platform
|
|
self.assertEqual(self.api.db.get_known_resolved_paths({asked: 10}), set())
|
|
|
|
|
|
class TestSkippedOutcome(unittest.TestCase):
|
|
|
|
def test_skipped_file_is_already_known_with_its_own_detail(self):
|
|
from py.api.admin import _scan_outcome
|
|
|
|
root = os.path.abspath("out")
|
|
group, row, line = _scan_outcome(
|
|
os.path.join(root, "a", "b.png"), [(root, "output", 0)], "skipped"
|
|
)
|
|
self.assertEqual(group, "known")
|
|
self.assertEqual(row["detail"], SKIPPED_DETAIL)
|
|
self.assertEqual(row["path"], "a/b.png")
|
|
self.assertEqual(line, f"= output/a/b.png · {SKIPPED_DETAIL}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|