Files
ComfyAssets-ComfyUI_PromptM…/py/api/annotations.py
T
Vito 3f11ea6168 feat(annotations): Needs review queue backend (#284)
* 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
2026-10-23 14:19:11 -07:00

782 lines
31 KiB
Python

"""Image annotation routes: observe, capture preview and byte-exact tag saves.
Every route names its file through the listing identity ``{root_index,
root_scope, path}`` and checks the scope against the current gallery roots
before any file access. Observe copies the file into a private capture (the
token the preview and Save refer to), Save re-hashes the current file and
writes only when the bytes are still the captured ones. Responses carry no
server path and no locator.
"""
import asyncio
import datetime
import functools
import os
import re
import threading
from pathlib import Path
from aiohttp import web
from .annotation_suggest import (
SUGGEST_FIELDS,
OptionError,
run_suggestions,
suggestion_rows,
unavailable_message,
validate_options,
)
from .autotag_routes import model_busy_response
from .images import _forbidden, _has_traversal, _unavailable_link, _verified_title
from .prompts import bad_request
from .. import model_gate
try:
from ...database.annotations import (
MAX_IMAGE_TAGS,
AnnotationCommandError,
ImageTagLimitError,
normalize_image_tags,
)
from ...database.execution_history import subscribe_history_restore
from ...database.library_commands import LibraryCommandError
from ...utils.media_capture import CAPTURE_EXTENSIONS, CaptureError, CaptureStore
except ImportError:
from database.annotations import (
MAX_IMAGE_TAGS,
AnnotationCommandError,
ImageTagLimitError,
normalize_image_tags,
)
from database.execution_history import subscribe_history_restore
from database.library_commands import LibraryCommandError
from utils.media_capture import CAPTURE_EXTENSIONS, CaptureError, CaptureStore
# Request bodies of the annotation routes are small (a target plus a tag set).
MAX_BODY_BYTES = 64 * 1024
MAX_TARGET_PATH = 1024
CAPTURE_URL = "/prompt_manager/image-annotations/capture/"
_PREVIEW_CHUNK = 64 * 1024
_TARGET_FIELDS = frozenset({"root_index", "root_scope", "path"})
_OBSERVE_FIELDS = frozenset({"target"})
_SAVE_FIELDS = frozenset(
{
"target",
"capture_token",
"sha256",
"expected_epoch",
"expected_tag_revision",
"tags",
}
)
_HEX64 = re.compile(r"[0-9a-f]{64}")
_UUID = re.compile(r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}")
# secrets.token_urlsafe(32) is 43 characters; the bound only rejects junk.
_TOKEN = re.compile(r"[A-Za-z0-9_-]{1,128}")
# The store is created on first use by the event loop, the scan's executor or
# the monitor's worker (Needs review), so its creation is serialized.
_CAPTURE_STORE_LOCK = threading.Lock()
_PREVIEW_TYPES = {
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".webp": "image/webp",
".gif": "image/gif",
".bmp": "image/bmp",
".tiff": "image/tiff",
".tif": "image/tiff",
".mp4": "video/mp4",
".m4v": "video/mp4",
".webm": "video/webm",
".mov": "video/quicktime",
".mkv": "video/x-matroska",
".avi": "video/x-msvideo",
".wmv": "video/x-ms-wmv",
}
_STATUS = {
"review-capacity": 429,
"unsupported-media": 415,
"file-changed": 409,
"source-changed": 409,
"storage-changed": 409,
"tag-conflict": 409,
"capture-expired": 409,
"model-unavailable": 409,
"tag-limit": 400,
"metadata-conflict": 409,
"vocabulary-conflict": 409,
}
_MESSAGES = {
"source-changed": (
"The source changed. Refresh the image collection before tagging this file."
),
"file-changed": "The file changed since it was previewed. Reopen the Tag dialog.",
"review-capacity": "Too many previews are open. Close a Tag dialog and try again.",
"storage-changed": "Prompt storage was restored; reopen the Tag dialog.",
"tag-conflict": (
"The tags of this image changed since the dialog opened; review them first."
),
"capture-expired": "The preview expired. Open the Tag dialog again.",
"tag-limit": f"An image can carry at most {MAX_IMAGE_TAGS} tags.",
}
# Any other storage code (a conflict a later command adds) still answers a
# coded envelope rather than a bare 500.
_DEFAULT_STATUS = 409
_DEFAULT_MESSAGE = "The tags could not be saved. Reopen the Tag dialog and try again."
_OTHER_FILE = "The preview belongs to another file. Open the Tag dialog again."
def preview_content_type(extension: str) -> str:
"""The media type the preview is served as; never sniffed from bytes."""
return _PREVIEW_TYPES.get(extension.lower(), "application/octet-stream")
def _error(status: int, code: str, message: str, **extra) -> web.Response:
return web.json_response(
{"success": False, "code": code, "error": message, **extra},
status=status,
headers={"Cache-Control": "no-store"},
)
def _coded(code: str, message: str | None = None, **extra) -> web.Response:
status = _STATUS.get(code, _DEFAULT_STATUS)
return _error(
status, code, message or _MESSAGES.get(code, _DEFAULT_MESSAGE), **extra
)
def _open_capture(path: str):
"""Worker thread: the capture file opened for reading."""
return open(path, "rb")
async def _settled(future, cleanup):
"""Await an executor *future*; a cancelled caller still cleans up after it.
The future is shielded, so the worker call always runs to its end. When the
caller is cancelled first, ``cleanup(result)`` runs once the call is done
(``cleanup(None)`` when it failed): a handle is closed, a capture released.
"""
try:
return await asyncio.shield(future)
except asyncio.CancelledError:
future.add_done_callback(functools.partial(_cleanup_result, cleanup))
raise
def _cleanup_result(cleanup, future) -> None:
if future.cancelled() or future.exception() is not None:
cleanup(None)
else:
cleanup(future.result())
def _submit(func, *args, **kwargs):
return asyncio.get_running_loop().run_in_executor(
None, functools.partial(func, *args, **kwargs)
)
def _capture_error(exc: CaptureError) -> web.Response:
"""The envelope for a capture outcome; messages never name a path."""
if exc.code not in _STATUS:
return _error(500, exc.code, "The file could not be captured.")
return _coded(exc.code, _MESSAGES.get(exc.code) or str(exc))
def _target(data: object):
"""``((index, scope, relative), None)`` for a target, else ``(None, error)``.
Only the listing identity is accepted: an int root index, the root's
64-hex scope and a bounded root-relative POSIX media path, never an
absolute, drive-qualified, backslash or ``..`` path. Nothing here touches
the filesystem or the database.
"""
if not isinstance(data, dict) or set(data) != _TARGET_FIELDS:
return None, bad_request("target must name root_index, root_scope and path")
index, scope, relative = data["root_index"], data["root_scope"], data["path"]
if type(index) is not int or index < 0:
return None, bad_request("Invalid gallery root")
if not isinstance(scope, str) or _HEX64.fullmatch(scope) is None:
return None, bad_request("Invalid gallery root scope")
if not isinstance(relative, str) or not relative or len(relative) > MAX_TARGET_PATH:
return None, bad_request("path must be a relative media path")
parts = relative.split("/")
if (
"\0" in relative
or "\\" in relative
or relative.startswith("/")
or _has_traversal(relative)
or any(part in ("", ".", "..") or ":" in part for part in parts)
):
return None, _forbidden()
if os.path.splitext(parts[-1])[1].lower() not in CAPTURE_EXTENSIONS:
return None, _forbidden("Only media files can be tagged")
return (index, scope, relative), None
def _expires_at(seconds: float | None) -> str:
moment = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
seconds=max(0.0, seconds or 0.0)
)
return moment.replace(microsecond=0).isoformat().replace("+00:00", "Z")
def _capture_info(store: CaptureStore, capture) -> dict:
return {
"token": capture.token,
"expires_at": _expires_at(store.expires_in(capture.token)),
"preview_url": CAPTURE_URL + capture.token,
"sha256": capture.sha256,
"size": capture.size,
"width": capture.width,
"height": capture.height,
"media_type": capture.media_type,
"generate": {
"supported": capture.inferable,
"reason": capture.inferable_reason,
},
}
class AnnotationRoutesMixin:
"""Observe, capture preview and tag save routes over PR A's storage."""
def _register_annotation_routes(self, routes: web.RouteTableDef) -> None:
routes.post("/prompt_manager/image-annotations/observe")(self.observe_image)
routes.get(CAPTURE_URL + "{token}")(self.get_capture_preview)
routes.delete(CAPTURE_URL + "{token}")(self.release_capture)
routes.put("/prompt_manager/image-annotations/tags")(self.save_image_tags)
routes.post("/prompt_manager/image-annotations/suggest")(
self.suggest_image_tags
)
# -- capture store lifetime ------------------------------------------------
def _capture_store(self) -> CaptureStore:
"""The process's capture store, created on first use.
Created lazily so an API object that never observes a file (most tests,
a server that never opens the Tag dialog) owns no temp directory. A
restore of the database dooms every capture (``invalidate_all``).
Thread-safe: Needs review recording calls it off the event loop.
Raises ``CaptureError`` after ``close_annotation_captures``.
"""
with _CAPTURE_STORE_LOCK:
if getattr(self, "_captures_closed", False):
# A recording still in flight at shutdown must not create a
# new temp directory after the cleanup removed the old one.
raise CaptureError("The capture store is closed")
if self._captures is None:
self._captures = CaptureStore()
if self._captures_unsubscribe is None:
self._captures_unsubscribe = subscribe_history_restore(
self.db.model.db_path, self._invalidate_captures
)
return self._captures
def _invalidate_captures(self) -> None:
store = self._captures
if store is not None:
store.invalidate_all()
def close_annotation_captures(self, *, final: bool = False) -> None:
"""Remove every capture file and the owned directory. Idempotent.
Taken under the store lock. ``final`` (the shutdown cleanup) also makes
``_capture_store`` refuse to create another store, so a recording
still in flight cannot leak a new temp directory after it.
"""
with _CAPTURE_STORE_LOCK:
if final:
self._captures_closed = True
unsubscribe, self._captures_unsubscribe = self._captures_unsubscribe, None
store, self._captures = self._captures, None
if unsubscribe is not None:
unsubscribe()
if store is not None:
store.close()
async def cleanup_annotation_captures(self, app: web.Application) -> None:
self.close_annotation_captures(final=True)
# -- shared request steps --------------------------------------------------
async def _annotation_body(self, request: web.Request, fields: frozenset):
data, error = await self._read_json_body(request, max_bytes=MAX_BODY_BYTES)
if error is not None:
return None, error
if set(data) != fields:
return None, bad_request(
"Request must contain exactly " + ", ".join(sorted(fields))
)
return data, None
def _scoped_root(self, index: int, scope: str):
"""``(root, None)`` when the scope names a current root, else an error."""
roots = list(self._get_all_output_dirs())
error = self._gallery_scope_error(
{"root_scope": scope, "root": str(index)}, roots
)
if error is not None:
if error.status == 409:
return None, _coded("source-changed")
return None, error
return roots[index], None
# -- observe ---------------------------------------------------------------
async def observe_image(self, request: web.Request) -> web.Response:
"""POST ``{target}``: capture the file and answer its saved tag set.
The capture is the byte-exact copy the preview and Save refer to; the
tags are those of exactly these bytes (an empty set at revision 0 for
unseen bytes). Observing never writes tags; equal bytes refresh the
record's verified fingerprint (S1).
"""
data, error = await self._annotation_body(request, _OBSERVE_FIELDS)
if error is not None:
return error
target, error = _target(data["target"])
if error is not None:
return error
index, scope, relative = target
root, error = self._scoped_root(index, scope)
if error is not None:
return error
try:
store = self._capture_store()
except CaptureError as exc: # the server is shutting down
return _capture_error(exc)
try:
epoch = await self._run_in_executor(self.db.get_execution_epoch)
capture = await _settled(
_submit(
store.capture,
root,
relative,
epoch=epoch,
scope=scope,
root_index=index,
),
# A cancelled observe never hands its capture out: release it.
lambda made: made is not None and store.release(made.token),
)
except CaptureError as exc:
return _capture_error(exc)
except Exception:
self.logger.exception("Image observation failed")
return _error(500, "observe-failed", "The image could not be observed.")
try:
stored, title = await self._run_in_executor(
self._observe_capture, store, capture, root, relative
)
except asyncio.CancelledError:
store.release(capture.token)
raise
except Exception:
store.release(capture.token)
self.logger.exception("Image observation failed")
return _error(500, "observe-failed", "The image could not be observed.")
return web.json_response(
{
"success": True,
"library_epoch": capture.epoch,
"target": {"root_index": index, "root_scope": scope, "path": relative},
"capture": _capture_info(store, capture),
"title": title,
"filename": relative.rsplit("/", 1)[-1],
"tags": stored["tags"],
"tag_revision": stored["tag_revision"],
},
headers={"Cache-Control": "no-store"},
)
def _observe_capture(self, store: CaptureStore, capture, root, relative: str):
"""Blocking part of observe: fingerprint refresh, tag read, title."""
self.db.refresh_image_fingerprint(
capture.locator, capture.sha256, capture.size, capture.mtime_ns
)
stored = self.db.read_image_tags(capture.locator, capture.sha256)
return stored, self._observed_title(store, capture, root, relative)
def _observed_title(self, store: CaptureStore, capture, root, relative: str):
"""The dialog's title under the card and inspector rule (``_verified_title``).
A stored Library title always shows; a first-line title only when the
captured bytes' own records confirm it. An ambiguous association has no
title. Videos read no card metadata, so only a stored title shows.
"""
path = str(Path(root) / relative)
summary = self._workspace_link_summaries([path]).get(path)
if summary is None:
summary = _unavailable_link()
positive_title = None
if (
capture.media_type != "video"
and summary.get("title_source") == "text"
and store.acquire(capture.token) is not None
):
try:
facts = self._read_card_facts(Path(capture.path), parse=True)
finally:
store.release_use(capture.token)
positive_title = facts.positive_title if facts is not None else None
return _verified_title(summary, positive_title)
# -- capture preview -------------------------------------------------------
async def get_capture_preview(self, request: web.Request) -> web.StreamResponse:
"""GET the captured bytes; the token is pinned while they stream."""
token = request.match_info["token"]
store = self._captures
if store is None or _TOKEN.fullmatch(token) is None:
return _error(404, "capture-expired", _MESSAGES["capture-expired"])
capture = store.acquire(token)
if capture is None:
return _error(404, "capture-expired", _MESSAGES["capture-expired"])
pinned = True
try:
_root, error = self._scoped_root(capture.root_index, capture.scope)
if error is not None:
# The roots changed under the token: it is no longer usable.
store.release(token)
return error
try:
handle = await _settled(
_submit(_open_capture, capture.path),
functools.partial(_close_then_release, store, token),
)
except asyncio.CancelledError:
# Cancelled while the file opens: the pin ends only after the
# handle closes (Windows cannot unlink an open file).
pinned = False
raise
except OSError:
store.release(token)
return _error(404, "capture-expired", _MESSAGES["capture-expired"])
try:
return await self._stream_capture(request, capture, handle)
finally:
handle.close()
finally:
if pinned:
store.release_use(token)
@staticmethod
async def _stream_capture(request, capture, handle) -> web.StreamResponse:
"""The capture's bytes, or the one byte range a ``Range`` header asks for.
The response is written here, inside the caller's pin, so the handle
is closed and the pin ended only after the last byte is sent.
"""
size = capture.size
headers = {
"Content-Type": preview_content_type(Path(capture.path).suffix),
"Accept-Ranges": "bytes",
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff",
}
status, start, end = 200, 0, size
if "Range" in request.headers:
wanted = _byte_range(request, size)
if wanted is None:
return web.Response(
status=416,
headers={**headers, "Content-Range": f"bytes */{size}"},
)
status, (start, end) = 206, wanted
headers["Content-Range"] = f"bytes {start}-{end - 1}/{size}"
headers["Content-Length"] = str(end - start)
response = web.StreamResponse(status=status, headers=headers)
await response.prepare(request)
loop = asyncio.get_running_loop()
if start:
await loop.run_in_executor(None, handle.seek, start)
remaining = end - start
while remaining > 0 and request.method != "HEAD":
chunk = await loop.run_in_executor(
None, handle.read, min(_PREVIEW_CHUNK, remaining)
)
if not chunk:
break
remaining -= len(chunk)
await response.write(chunk)
await response.write_eof()
return response
async def release_capture(self, request: web.Request) -> web.Response:
"""DELETE a capture token; releasing an unknown token is a success."""
token = request.match_info["token"]
store = self._captures
if store is not None and _TOKEN.fullmatch(token) is not None:
store.release(token)
return web.json_response(
{"success": True}, headers={"Cache-Control": "no-store"}
)
# -- save ------------------------------------------------------------------
async def save_image_tags(self, request: web.Request) -> web.Response:
"""PUT the tag set of the previewed bytes, re-hashing the current file.
Writes only when the file still holds the captured bytes
(``file-changed`` with zero writes otherwise), under the storage epoch
and the tag revision the dialog read; an identical retry is
``replayed``. The hash never runs inside a database transaction.
"""
data, error = await self._annotation_body(request, _SAVE_FIELDS)
if error is not None:
return error
target, error = _target(data["target"])
if error is not None:
return error
guards, error = _save_guards(data)
if error is not None:
return error
token, sha256, expected_epoch, revision, tags = guards
index, scope, relative = target
root, error = self._scoped_root(index, scope)
if error is not None:
return error
store = self._captures
capture = store.get(token) if store is not None else None
if capture is None:
return _coded("capture-expired")
if capture.root_index != index or capture.scope != scope:
return _coded("capture-expired", _OTHER_FILE)
if sha256 != capture.sha256:
return bad_request("sha256 does not match the preview")
if expected_epoch != capture.epoch:
current = await self._run_in_executor(self.db.get_execution_epoch)
return _coded("storage-changed", library_epoch=current)
try:
facts = await self._run_in_executor(
_verify_captured_file, store, capture, root, relative
)
except CaptureError as exc:
return _capture_error(exc)
if facts is None or facts.locator != capture.locator:
return _coded("capture-expired", _OTHER_FILE)
if facts.sha256 != capture.sha256:
return _coded("file-changed")
try:
receipt = await self._run_in_executor(
self.db.replace_image_tags,
locator=facts.locator,
sha256=facts.sha256,
size=facts.size,
mtime_ns=facts.mtime_ns,
expected_epoch=expected_epoch,
expected_tag_revision=revision,
tags=tags,
)
except AnnotationCommandError as exc:
current = exc.current or {}
return _coded(
exc.code,
library_epoch=exc.epoch,
tags=current.get("tags", []),
tag_revision=current.get("tag_revision", 0),
)
except LibraryCommandError as exc:
return _coded(exc.code, library_epoch=exc.epoch)
except ValueError as exc:
return bad_request(str(exc))
except Exception:
self.logger.exception("Image tag save failed")
return _error(500, "save-failed", "The tags could not be saved.")
return web.json_response(
{"success": True, **receipt}, headers={"Cache-Control": "no-store"}
)
# -- suggest ---------------------------------------------------------------
async def suggest_image_tags(self, request: web.Request) -> web.Response:
"""POST: the top N tags of the captured bytes from one legacy engine.
Runs only on the private capture (pinned for the whole inference),
under the shared model gate (``model-busy`` while anything else holds
it, including a legacy batch), never downloads (``model-unavailable``)
and never writes.
"""
from ..autotag import MODELS, get_autotag_service
from ..config import MAX_SUGGESTION_LIMIT, AutotagConfig
data, error = await self._annotation_body(request, SUGGEST_FIELDS)
if error is not None:
return error
target, error = _target(data["target"])
if error is not None:
return error
try:
model_type, options = validate_options(
data["model_type"],
data["options"],
default_limit=AutotagConfig.suggestion_limit(),
max_limit=MAX_SUGGESTION_LIMIT,
)
except OptionError as exc:
return bad_request(str(exc))
token, epoch = data["capture_token"], data["expected_epoch"]
if not isinstance(token, str) or _TOKEN.fullmatch(token) is None:
return bad_request("Invalid capture token")
if not isinstance(epoch, str) or _UUID.fullmatch(epoch) is None:
return bad_request("expected_epoch must be a canonical UUID")
index, scope, relative = target
root, error = self._scoped_root(index, scope)
if error is not None:
return error
store = self._captures
capture = store.acquire(token) if store is not None else None
if capture is None:
return _coded("capture-expired")
started = False
try:
error = await self._suggest_guards(capture, target, root, epoch)
if error is not None:
return error
service = get_autotag_service()
status = await self._run_in_executor(service.get_models_status)
if not status.get(model_type, {}).get("downloaded"):
name = MODELS.get(model_type, {}).get("name", model_type)
return _coded("model-unavailable", unavailable_message(name))
owner = model_gate.new_owner("image-annotations")
if not model_gate.try_acquire(owner):
return model_busy_response()
try:
# From here the pin is the gate's to end: the worker ends it,
# or ``on_skipped`` does when the worker never starts.
started = True
pairs = await model_gate.run(
owner,
_pinned_suggestions,
store,
token,
service,
capture,
model_type,
options,
on_skipped=functools.partial(store.release_use, token),
)
except Exception:
self.logger.exception("Tag suggestion failed")
return _error(
500,
"suggest-failed",
"Auto-tagging failed. Check server logs for details.",
)
finally:
model_gate.release(owner)
finally:
if not started:
store.release_use(token)
return web.json_response(
{
"success": True,
"model_type": model_type,
"options": options,
"suggestions": suggestion_rows(pairs),
},
headers={"Cache-Control": "no-store"},
)
async def _suggest_guards(self, capture, target, root, epoch):
"""The capture must be this target's, of this epoch, and inferable."""
index, scope, relative = target
expected = os.path.normcase(
os.path.join(os.path.realpath(root), *relative.split("/"))
)
if (
capture.root_index != index
or capture.scope != scope
or capture.locator != expected
):
return _coded("capture-expired", _OTHER_FILE)
if epoch != capture.epoch:
current = await self._run_in_executor(self.db.get_execution_epoch)
return _coded("storage-changed", library_epoch=current)
if not capture.inferable:
return _coded("unsupported-media", capture.inferable_reason)
return None
def _close_then_release(store: CaptureStore, token: str, handle) -> None:
"""Close a preview handle a cancelled request opened, then end its pin."""
try:
if handle is not None:
handle.close()
finally:
store.release_use(token)
def _byte_range(request: web.Request, size: int):
"""``(start, end)`` of the one satisfiable byte range asked for, else None.
A malformed, multi-range or unsatisfiable header is None (416), as
aiohttp's own file responses answer it.
"""
try:
wanted = request.http_range
except ValueError:
return None
start, stop = wanted.start, wanted.stop
if start is None:
return None
if start < 0: # a suffix: the last -start bytes
start = max(0, size + start)
stop = size
stop = size if stop is None else min(stop, size)
if start >= size or stop <= start:
return None
return start, stop
def _pinned_suggestions(store, token, service, capture, model_type, options):
"""Worker thread: infer on the capture, then end its pin (even on error)."""
try:
return run_suggestions(service, capture.path, model_type, options)
finally:
store.release_use(token)
def _verify_captured_file(store: CaptureStore, capture, root, relative: str):
"""Re-hash the current file, or None when the token names another file.
The cheap locator comparison runs first, so a token sent for another
target never costs a whole-file hash.
"""
expected = os.path.normcase(
os.path.join(os.path.realpath(root), *relative.split("/"))
)
if expected != capture.locator:
return None
return store.verify(root, relative)
def _save_guards(data: dict):
"""Validated ``(token, sha256, epoch, revision, tags)`` or ``(None, error)``."""
token = data["capture_token"]
if not isinstance(token, str) or _TOKEN.fullmatch(token) is None:
return None, bad_request("Invalid capture token")
sha256 = data["sha256"]
if not isinstance(sha256, str) or _HEX64.fullmatch(sha256) is None:
return None, bad_request("sha256 must be 64 lowercase hexadecimal characters")
epoch = data["expected_epoch"]
if not isinstance(epoch, str) or _UUID.fullmatch(epoch) is None:
return None, bad_request("expected_epoch must be a canonical UUID")
revision = data["expected_tag_revision"]
if type(revision) is not int or revision < 0:
return None, bad_request("expected_tag_revision must be a non-negative integer")
try:
tags = normalize_image_tags(data["tags"])
except ImageTagLimitError as exc:
return None, _error(400, "tag-limit", str(exc))
except ValueError as exc:
return None, bad_request(str(exc))
return (token, sha256, epoch, revision, tags), None