* 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
508 lines
20 KiB
Python
508 lines
20 KiB
Python
"""Needs review schema group (#249): capture-bound ambiguous items and decisions.
|
|
|
|
The group installs like ``image_annotations``: optional in old backups,
|
|
required once a database is current, and valid only beside a valid image
|
|
annotation group, because every item cites one annotation byte record. It owns
|
|
|
|
- ``media_review_metadata``: one row, the group's schema version and the
|
|
review index revision (moved by every queue change);
|
|
- ``media_review_items``: one ambiguous resolver result for one byte record,
|
|
keyed by ``(byte_id, resolver_version, evidence_hash)``, with the file's
|
|
spelling when it was recorded (the locator is case-folded on Windows, a
|
|
target is not), its canonical evidence, candidate count, ``limited`` flag,
|
|
state and revision;
|
|
- ``media_review_decisions``: the auditable decision history of an item, one
|
|
row per decision revision, with optional navigation to the pair and image
|
|
the decision linked (nulled, never cascaded, when those are deleted).
|
|
|
|
Evidence is canonical JSON (:func:`canonical_evidence`): one object, sorted
|
|
keys, no whitespace, ASCII only (so characters, bytes and the 8 MiB bound
|
|
agree and lone surrogates survive), no NaN or infinity. ``evidence_hash`` is
|
|
the SHA-256 of the item's evidence text.
|
|
|
|
Installation never backfills anything and never touches the filesystem.
|
|
Validation reads only: catalog objects compared after whitespace compaction,
|
|
columns and foreign keys through the PRAGMAs, persisted values in single
|
|
bounded SQL passes, then one streamed pass that re-canonicalizes each evidence
|
|
document (one row in memory at a time).
|
|
"""
|
|
|
|
import hashlib
|
|
import json
|
|
import re
|
|
import sqlite3
|
|
from typing import Any, Optional
|
|
|
|
from .annotation_schema import BYTES_TABLE
|
|
from .annotation_schema import TABLES as ANNOTATION_TABLES
|
|
from .annotation_schema import _catalog as _annotation_catalog
|
|
from .annotation_schema import annotation_schema_error
|
|
|
|
try:
|
|
from ..utils.json_strict import dumps_strict
|
|
except ImportError:
|
|
from utils.json_strict import dumps_strict
|
|
|
|
SCHEMA_VERSION = 1
|
|
METADATA_TABLE = "media_review_metadata"
|
|
ITEMS_TABLE = "media_review_items"
|
|
DECISIONS_TABLE = "media_review_decisions"
|
|
TABLES = (METADATA_TABLE, ITEMS_TABLE, DECISIONS_TABLE)
|
|
MAX_EVIDENCE_BYTES = 8 * 1024 * 1024
|
|
MAX_CANDIDATES = 16
|
|
# The file's own spelling when it was recorded (bytes of UTF-8 text). Locators
|
|
# are case-folded on Windows, so a target is formatted from this instead.
|
|
MAX_SPELLED_PATH_BYTES = 16384
|
|
ITEM_STATES = ("pending", "selected", "unresolved")
|
|
DECISION_OUTCOMES = ("selected", "unresolved")
|
|
_TIMESTAMP_BYTES = 64
|
|
_HEX64 = "length({c})=64 AND {c} NOT GLOB '*[^0-9a-f]*'"
|
|
_EVIDENCE_CHECK = f"CHECK(length(CAST(evidence AS BLOB)) <= {MAX_EVIDENCE_BYTES})"
|
|
|
|
_TABLE_DDL = {
|
|
METADATA_TABLE: (
|
|
f"CREATE TABLE {METADATA_TABLE} (singleton_id INTEGER PRIMARY KEY "
|
|
"CHECK(singleton_id=1), schema_version INTEGER NOT NULL "
|
|
f"CHECK(schema_version={SCHEMA_VERSION}), "
|
|
"review_index_revision INTEGER NOT NULL DEFAULT 0 "
|
|
"CHECK(review_index_revision>=0))"
|
|
),
|
|
ITEMS_TABLE: (
|
|
f"CREATE TABLE {ITEMS_TABLE} (id TEXT PRIMARY KEY CHECK(length(id)=36), "
|
|
f"byte_id TEXT NOT NULL REFERENCES {BYTES_TABLE}(id) ON DELETE RESTRICT, "
|
|
"spelled_path TEXT NOT NULL CHECK(length(CAST(spelled_path AS BLOB)) "
|
|
f"BETWEEN 1 AND {MAX_SPELLED_PATH_BYTES}), "
|
|
"resolver_version INTEGER NOT NULL, evidence_hash TEXT NOT NULL "
|
|
f"CHECK({_HEX64.format(c='evidence_hash')}), "
|
|
f"evidence TEXT NOT NULL {_EVIDENCE_CHECK}, "
|
|
"candidate_count INTEGER NOT NULL "
|
|
f"CHECK(candidate_count BETWEEN 0 AND {MAX_CANDIDATES}), "
|
|
"limited INTEGER NOT NULL CHECK(limited IN (0,1)), "
|
|
"state TEXT NOT NULL CHECK(state IN ('pending','selected','unresolved')), "
|
|
"revision INTEGER NOT NULL CHECK(revision>=0), created_at TEXT NOT NULL, "
|
|
"updated_at TEXT NOT NULL, UNIQUE(byte_id, resolver_version, evidence_hash))"
|
|
),
|
|
DECISIONS_TABLE: (
|
|
f"CREATE TABLE {DECISIONS_TABLE} (id TEXT PRIMARY KEY "
|
|
"CHECK(length(id)=36), item_id TEXT NOT NULL "
|
|
f"REFERENCES {ITEMS_TABLE}(id) ON DELETE RESTRICT, "
|
|
"decision_revision INTEGER NOT NULL, created_at TEXT NOT NULL, "
|
|
"outcome TEXT NOT NULL CHECK(outcome IN ('selected','unresolved')), "
|
|
"candidate_hash TEXT CHECK(candidate_hash IS NULL OR "
|
|
f"({_HEX64.format(c='candidate_hash')})), "
|
|
f"evidence TEXT NOT NULL {_EVIDENCE_CHECK}, "
|
|
"pair_id INTEGER REFERENCES prompt_pairs(id) ON DELETE SET NULL, "
|
|
"image_id INTEGER REFERENCES generated_images(id) ON DELETE SET NULL, "
|
|
"UNIQUE(item_id, decision_revision), "
|
|
"CHECK((outcome='selected') = (candidate_hash IS NOT NULL)))"
|
|
),
|
|
}
|
|
_INDEX_DDL = {
|
|
# The queue reads pending items oldest first with a stable tiebreak.
|
|
"idx_media_review_items_queue": (
|
|
"CREATE INDEX idx_media_review_items_queue ON "
|
|
f"{ITEMS_TABLE}(state, created_at, id)"
|
|
),
|
|
# Deleting a pair or an image nulls decision navigation by index, not scan.
|
|
"idx_media_review_decisions_pair": (
|
|
"CREATE INDEX idx_media_review_decisions_pair ON " f"{DECISIONS_TABLE}(pair_id)"
|
|
),
|
|
"idx_media_review_decisions_image": (
|
|
"CREATE INDEX idx_media_review_decisions_image ON "
|
|
f"{DECISIONS_TABLE}(image_id)"
|
|
),
|
|
}
|
|
# ``sqlite_autoindex_<table>_<n>``: the TEXT primary key and the UNIQUE key.
|
|
_AUTOINDEXES = {ITEMS_TABLE: 2, DECISIONS_TABLE: 2}
|
|
# (name, declared type, not null, default, primary key position)
|
|
_COLUMNS = {
|
|
METADATA_TABLE: (
|
|
("singleton_id", "INTEGER", 0, None, 1),
|
|
("schema_version", "INTEGER", 1, None, 0),
|
|
("review_index_revision", "INTEGER", 1, "0", 0),
|
|
),
|
|
ITEMS_TABLE: (
|
|
("id", "TEXT", 0, None, 1),
|
|
("byte_id", "TEXT", 1, None, 0),
|
|
("spelled_path", "TEXT", 1, None, 0),
|
|
("resolver_version", "INTEGER", 1, None, 0),
|
|
("evidence_hash", "TEXT", 1, None, 0),
|
|
("evidence", "TEXT", 1, None, 0),
|
|
("candidate_count", "INTEGER", 1, None, 0),
|
|
("limited", "INTEGER", 1, None, 0),
|
|
("state", "TEXT", 1, None, 0),
|
|
("revision", "INTEGER", 1, None, 0),
|
|
("created_at", "TEXT", 1, None, 0),
|
|
("updated_at", "TEXT", 1, None, 0),
|
|
),
|
|
DECISIONS_TABLE: (
|
|
("id", "TEXT", 0, None, 1),
|
|
("item_id", "TEXT", 1, None, 0),
|
|
("decision_revision", "INTEGER", 1, None, 0),
|
|
("created_at", "TEXT", 1, None, 0),
|
|
("outcome", "TEXT", 1, None, 0),
|
|
("candidate_hash", "TEXT", 0, None, 0),
|
|
("evidence", "TEXT", 1, None, 0),
|
|
("pair_id", "INTEGER", 0, None, 0),
|
|
("image_id", "INTEGER", 0, None, 0),
|
|
),
|
|
}
|
|
# (column, parent table, parent column, on delete)
|
|
_FOREIGN_KEYS = {
|
|
METADATA_TABLE: set(),
|
|
ITEMS_TABLE: {("byte_id", BYTES_TABLE, "id", "RESTRICT")},
|
|
DECISIONS_TABLE: {
|
|
("item_id", ITEMS_TABLE, "id", "RESTRICT"),
|
|
("pair_id", "prompt_pairs", "id", "SET NULL"),
|
|
("image_id", "generated_images", "id", "SET NULL"),
|
|
},
|
|
}
|
|
|
|
|
|
class _NonCanonical(ValueError):
|
|
pass
|
|
|
|
|
|
def _reject_constant(name: str) -> Any:
|
|
raise _NonCanonical(f"JSON constant {name} is not allowed")
|
|
|
|
|
|
# Built once: validation re-encodes every stored document at startup.
|
|
_ENCODER = json.JSONEncoder(
|
|
sort_keys=True, separators=(",", ":"), ensure_ascii=True, allow_nan=False
|
|
)
|
|
_DECODER = json.JSONDecoder(parse_constant=_reject_constant)
|
|
|
|
|
|
def canonical_evidence(value: Any) -> str:
|
|
"""Serialize one evidence object canonically; ``ValueError`` when invalid.
|
|
|
|
The text is a JSON object with sorted keys, no whitespace, ASCII only and
|
|
no NaN/infinity, at most ``MAX_EVIDENCE_BYTES`` bytes. A non-finite number
|
|
(ComfyUI stamps ``NaN`` into graphs) is written as ``null``, the store's
|
|
policy everywhere (``utils.json_strict.dumps_strict``).
|
|
"""
|
|
if not isinstance(value, dict):
|
|
raise ValueError("Review evidence must be a JSON object")
|
|
try:
|
|
try:
|
|
text = _ENCODER.encode(value)
|
|
except ValueError as error:
|
|
if "Out of range float" not in str(error):
|
|
raise
|
|
text = dumps_strict(
|
|
value, sort_keys=True, separators=(",", ":"), ensure_ascii=True
|
|
)
|
|
except (TypeError, RecursionError) as error:
|
|
raise ValueError(f"Review evidence is not serializable: {error}") from None
|
|
if len(text) > MAX_EVIDENCE_BYTES:
|
|
raise ValueError("Review evidence is larger than 8 MiB")
|
|
return text
|
|
|
|
|
|
def choosable(candidate: Any) -> bool:
|
|
"""True when a candidate offers a prompt to choose: it is ``resolved`` and
|
|
its positive side carries non-blank text. The page disables any other
|
|
candidate, so it is never something to choose.
|
|
"""
|
|
if not isinstance(candidate, dict) or candidate.get("state") != "resolved":
|
|
return False
|
|
positive = candidate.get("positive")
|
|
if not isinstance(positive, dict):
|
|
return False
|
|
text = positive.get("text")
|
|
return isinstance(text, str) and bool(text.strip())
|
|
|
|
|
|
# An item is worth a decision only when at least this many candidates offer
|
|
# a prompt; with fewer there is nothing to choose between (maintainer test of
|
|
# #284/#288: 39 items whose candidates were all "unresolved").
|
|
MIN_CHOOSABLE = 2
|
|
|
|
|
|
def evidence_offers_choice(evidence: Any) -> bool:
|
|
"""False when stored evidence provably offers nothing to choose.
|
|
|
|
Unlimited evidence must list ``MIN_CHOOSABLE`` choosable candidates. A
|
|
limited item stores none, only ``candidate_total``; it may offer a choice
|
|
(more than ``MAX_CANDIDATES`` prompts) unless that total is too small.
|
|
"""
|
|
if not isinstance(evidence, dict):
|
|
return False
|
|
if evidence.get("limited"):
|
|
total = evidence.get("candidate_total")
|
|
return type(total) is int and total >= MIN_CHOOSABLE
|
|
candidates = evidence.get("candidates")
|
|
if not isinstance(candidates, list):
|
|
return False
|
|
return sum(1 for c in candidates if choosable(c)) >= MIN_CHOOSABLE
|
|
|
|
|
|
def evidence_digest(text: str) -> str:
|
|
"""SHA-256 of canonical evidence text (ASCII, hence UTF-8 identical)."""
|
|
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
|
|
|
|
|
def _is_canonical(text: Any) -> bool:
|
|
if not isinstance(text, str):
|
|
return False
|
|
try:
|
|
value = _DECODER.decode(text)
|
|
return canonical_evidence(value) == text
|
|
except (ValueError, RecursionError):
|
|
return False
|
|
|
|
|
|
def _compact(sql: str) -> str:
|
|
return re.sub(r"\s+", "", sql).lower()
|
|
|
|
|
|
def _uuid(column: str) -> str:
|
|
"""SQL: *column* is a lowercase hyphenated 36-character UUID string."""
|
|
return (
|
|
f"typeof({column}) = 'text' AND length({column}) = 36 "
|
|
f"AND substr({column}, 9, 1) = '-' AND substr({column}, 14, 1) = '-' "
|
|
f"AND substr({column}, 19, 1) = '-' AND substr({column}, 24, 1) = '-' "
|
|
f"AND length(replace({column}, '-', '')) = 32 "
|
|
f"AND replace({column}, '-', '') NOT GLOB '*[^0-9a-f]*'"
|
|
)
|
|
|
|
|
|
def _timestamp(column: str) -> str:
|
|
return (
|
|
f"typeof({column}) = 'text' "
|
|
f"AND length(CAST({column} AS BLOB)) <= {_TIMESTAMP_BYTES}"
|
|
)
|
|
|
|
|
|
def _non_negative(column: str) -> str:
|
|
return f"typeof({column}) = 'integer' AND {column} >= 0"
|
|
|
|
|
|
def _hex64(column: str) -> str:
|
|
return f"typeof({column}) = 'text' AND " + _HEX64.format(c=column)
|
|
|
|
|
|
def _evidence(column: str) -> str:
|
|
# Type and size only: the streamed pass below proves the text canonical
|
|
# (which implies printable ASCII), so a pattern scan here would read every
|
|
# document a second time.
|
|
return (
|
|
f"typeof({column}) = 'text' "
|
|
f"AND length(CAST({column} AS BLOB)) BETWEEN 2 AND {MAX_EVIDENCE_BYTES}"
|
|
)
|
|
|
|
|
|
def _nullable_integer(column: str) -> str:
|
|
return f"({column} IS NULL OR typeof({column}) = 'integer')"
|
|
|
|
|
|
def _in(column: str, values: tuple) -> str:
|
|
return f"typeof({column}) = 'text' AND {column} IN ({repr(values)[1:-1]})"
|
|
|
|
|
|
# Every row of a table must satisfy its predicate; one pass each, LIMIT 1.
|
|
_ROW_PREDICATES = {
|
|
ITEMS_TABLE: " AND ".join(
|
|
(
|
|
_uuid("id"),
|
|
_uuid("byte_id"),
|
|
"typeof(spelled_path) = 'text' AND length(CAST(spelled_path AS BLOB)) "
|
|
f"BETWEEN 1 AND {MAX_SPELLED_PATH_BYTES}",
|
|
"typeof(resolver_version) = 'integer'",
|
|
_hex64("evidence_hash"),
|
|
_evidence("evidence"),
|
|
_non_negative("candidate_count"),
|
|
f"candidate_count <= {MAX_CANDIDATES}",
|
|
"typeof(limited) = 'integer' AND limited IN (0, 1)",
|
|
_in("state", ITEM_STATES),
|
|
_non_negative("revision"),
|
|
_timestamp("created_at"),
|
|
_timestamp("updated_at"),
|
|
)
|
|
),
|
|
DECISIONS_TABLE: " AND ".join(
|
|
(
|
|
_uuid("id"),
|
|
_uuid("item_id"),
|
|
_non_negative("decision_revision"),
|
|
_timestamp("created_at"),
|
|
_in("outcome", DECISION_OUTCOMES),
|
|
"(CASE WHEN outcome = 'selected' THEN "
|
|
f"{_hex64('candidate_hash')} ELSE candidate_hash IS NULL END)",
|
|
_evidence("evidence"),
|
|
_nullable_integer("pair_id"),
|
|
_nullable_integer("image_id"),
|
|
)
|
|
),
|
|
}
|
|
|
|
|
|
def _expected_catalog() -> set:
|
|
objects = {("table", name, _compact(sql)) for name, sql in _TABLE_DDL.items()}
|
|
objects |= {("index", name, _compact(sql)) for name, sql in _INDEX_DDL.items()}
|
|
objects |= {
|
|
("index", f"sqlite_autoindex_{table}_{n}", "")
|
|
for table, count in _AUTOINDEXES.items()
|
|
for n in range(1, count + 1)
|
|
}
|
|
return objects
|
|
|
|
|
|
def _catalog(conn: sqlite3.Connection) -> list:
|
|
names = TABLES + tuple(_INDEX_DDL)
|
|
marks = ",".join("?" * len(names))
|
|
table_marks = ",".join("?" * len(TABLES))
|
|
return conn.execute( # only "?" placeholders are interpolated
|
|
"SELECT type,name,sql FROM sqlite_master "
|
|
f"WHERE name IN ({marks}) OR tbl_name IN ({table_marks})", # nosec B608
|
|
names + TABLES,
|
|
).fetchall()
|
|
|
|
|
|
def _structure_error(conn: sqlite3.Connection) -> Optional[str]:
|
|
for table, expected in _COLUMNS.items():
|
|
columns = tuple(
|
|
(row[1], row[2].upper(), row[3], row[4], row[5])
|
|
for row in conn.execute(f"PRAGMA table_info({table})")
|
|
)
|
|
if columns != expected:
|
|
return f"Review queue table {table} has invalid columns"
|
|
foreign_keys = {
|
|
(row[3], row[2], row[4], row[6])
|
|
for row in conn.execute(f"PRAGMA foreign_key_list({table})")
|
|
}
|
|
if foreign_keys != _FOREIGN_KEYS[table]:
|
|
return f"Review queue table {table} has invalid foreign keys"
|
|
if conn.execute(f"PRAGMA foreign_key_check({table})").fetchone():
|
|
return f"Review queue table {table} contains foreign key violations"
|
|
return None
|
|
|
|
|
|
def _evidence_error(conn: sqlite3.Connection) -> Optional[str]:
|
|
"""Stream every evidence document once; one row is held at a time."""
|
|
for evidence_hash, text in conn.execute(
|
|
f"SELECT evidence_hash, evidence FROM {ITEMS_TABLE}" # nosec B608
|
|
):
|
|
if not _is_canonical(text) or evidence_digest(text) != evidence_hash:
|
|
return f"Review queue table {ITEMS_TABLE} contains invalid evidence"
|
|
for (text,) in conn.execute(
|
|
f"SELECT evidence FROM {DECISIONS_TABLE}" # nosec B608
|
|
):
|
|
if not _is_canonical(text):
|
|
return f"Review queue table {DECISIONS_TABLE} contains invalid evidence"
|
|
return None
|
|
|
|
|
|
def _value_error(conn: sqlite3.Connection) -> Optional[str]:
|
|
# Only this module's constants are interpolated into the SQL below.
|
|
rows = conn.execute(
|
|
"SELECT COUNT(*), MIN(typeof(singleton_id) = 'integer' " # nosec B608
|
|
"AND singleton_id = 1 AND typeof(schema_version) = 'integer' "
|
|
f"AND schema_version = {SCHEMA_VERSION} "
|
|
f"AND {_non_negative('review_index_revision')}) FROM {METADATA_TABLE}"
|
|
).fetchone()
|
|
if rows[0] != 1 or rows[1] != 1:
|
|
return "Review queue metadata is invalid"
|
|
for table, predicate in _ROW_PREDICATES.items():
|
|
if conn.execute(
|
|
f"SELECT 1 FROM {table} WHERE NOT ({predicate}) LIMIT 1" # nosec B608
|
|
).fetchone():
|
|
return f"Review queue table {table} contains invalid values"
|
|
return _evidence_error(conn)
|
|
|
|
|
|
def review_without_annotations_error(conn: sqlite3.Connection) -> Optional[str]:
|
|
"""Catalog only: a review group present without its annotation tables.
|
|
|
|
Startup asks this before the annotation group installs, which would make
|
|
a review group copied without it look valid. It reads no rows; the full
|
|
validation runs once in :func:`migrate_review_state`.
|
|
"""
|
|
if not _catalog(conn):
|
|
return None
|
|
present = {
|
|
name for kind, name, _sql in _annotation_catalog(conn) if kind == "table"
|
|
}
|
|
if present != set(ANNOTATION_TABLES):
|
|
return (
|
|
"Review queue schema requires a valid image annotation schema: "
|
|
"Missing image annotation schema"
|
|
)
|
|
return None
|
|
|
|
|
|
def review_schema_error(
|
|
conn: sqlite3.Connection,
|
|
*,
|
|
allow_missing: bool = True,
|
|
annotations_valid: bool = False,
|
|
) -> Optional[str]:
|
|
"""Reject partial or unsupported review schemas and invalid rows.
|
|
|
|
Reads only: nothing is ever repaired. A database without any of the
|
|
group's objects is acceptable for backups that predate it unless
|
|
``allow_missing`` is false. A present group requires a present, valid
|
|
image annotation group; ``annotations_valid`` says the caller has just
|
|
validated it (startup's annotation install), so only its presence is
|
|
checked again.
|
|
"""
|
|
objects = _catalog(conn)
|
|
if not objects:
|
|
return None if allow_missing else "Missing review queue schema"
|
|
if annotations_valid:
|
|
annotation_error = review_without_annotations_error(conn)
|
|
else:
|
|
annotation_error = annotation_schema_error(conn, allow_missing=False)
|
|
if annotation_error:
|
|
annotation_error = (
|
|
"Review queue schema requires a valid image annotation schema: "
|
|
+ annotation_error
|
|
)
|
|
if annotation_error:
|
|
return annotation_error
|
|
present = {name for kind, name, _sql in objects if kind == "table"}
|
|
if present != set(TABLES):
|
|
return "Incomplete review queue schema"
|
|
actual = {(kind, name, _compact(sql or "")) for kind, name, sql in objects}
|
|
if actual != _expected_catalog():
|
|
return "Review queue has an invalid schema definition"
|
|
return _structure_error(conn) or _value_error(conn)
|
|
|
|
|
|
def migrate_review_state(conn: sqlite3.Connection) -> None:
|
|
"""Install the group atomically; validate before and after creating it.
|
|
|
|
Runs after ``migrate_annotation_state`` (which has just validated the
|
|
annotation group): the group is only valid beside the annotation group it
|
|
cites. A present group is validated once, evidence included.
|
|
"""
|
|
conn.execute("SAVEPOINT media_review_schema")
|
|
try:
|
|
installed = bool(_catalog(conn))
|
|
error = review_schema_error(conn, annotations_valid=True)
|
|
if error:
|
|
raise sqlite3.DatabaseError(error)
|
|
if installed:
|
|
# Already complete and valid: nothing to create, and the evidence
|
|
# pass is the expensive part of validation, so it runs once.
|
|
conn.execute("RELEASE media_review_schema")
|
|
return
|
|
for sql in _TABLE_DDL.values():
|
|
conn.execute(sql.replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS", 1))
|
|
for sql in _INDEX_DDL.values():
|
|
conn.execute(sql.replace("INDEX", "INDEX IF NOT EXISTS", 1))
|
|
conn.execute(
|
|
f"INSERT OR IGNORE INTO {METADATA_TABLE} "
|
|
"(singleton_id, schema_version, review_index_revision) VALUES (1, ?, 0)",
|
|
(SCHEMA_VERSION,),
|
|
)
|
|
error = review_schema_error(conn, allow_missing=False, annotations_valid=True)
|
|
if error:
|
|
raise sqlite3.DatabaseError(error)
|
|
conn.execute("RELEASE media_review_schema")
|
|
except BaseException:
|
|
conn.execute("ROLLBACK TO media_review_schema")
|
|
conn.execute("RELEASE media_review_schema")
|
|
raise
|