* test(inspect): use a neutral unknown class in the pass-through fixtures The #381 fixtures used rgthree's Any Switch as their example of an unknown node. The table is about to describe that class (#657), so the stand-in becomes PMTest Unknown Multi and any_switch_graph becomes unknown_multi_graph. Resolver results are unchanged. * feat(inspect): resolve rgthree Any Switch by its first proven input (#657) rgthree's Any Switch outputs the first any_* input that is not None. The inspection resolver treated it as an unknown node, so the model-compare sweep (PromptManagerText into any_01, the same text joined after a LoRA trigger into any_02) was ambiguous in Inspect. The table gains a first-present selector strategy and lists the switch under it. The resolver takes the first participating input when it is a literal or its traced path proves a value (every node is a PromptManager, code-traced, default-adapter or encoders/strings/conditioning/composites class). Otherwise each input is one choice, unless all of them trace to one text; limits and upstream divergences propagate, and no PromptManager path is preferred. A missing or null input does not take part. The browser resolver and its table compiler follow the same rules, with the same strict entry check as the server. Only graphs holding the class change their class projection, so only their pending inspection items move; INSPECTION_RESOLVER_VERSION stays 2. * fix(inspect): list a repeated Any Switch outcome once (#657) A switch with three or more inputs can offer one text through two of them (a, b, a). Each input was its own candidate, so one text read as a choice between two, and two equal resolved candidates beside a failed one would count as reviewable. Like an unknown node passing several texts, a first-present divergence now collapses equal outcomes. The browser resolver does the same. The table compiler test also checks the 128-character prefix bound in code points, as Python counts it. * feat(inspect): show a role every candidate shares (#658) An ambiguous file used to withhold both roles, even when every candidate had the same negative. Inspect now judges each role on its own: a role is shown resolved when every candidate is resolved with the same text, stored recipe and left-out parts for it, using the first candidate's text and source. A role that differs, or any unresolved candidate, keeps the ambiguous line, and resolution.state stays ambiguous, so Send pair, ingestion and Needs review behave as before. The browser-local resolver applies the same rule; the footer Send to ComfyUI still needs both roles. A multistage detailer run whose stages share one negative (fixture f19) now shows that negative. * feat(monitor): ask the ladder for PromptManager runs nothing else links A PromptManager output whose metadata and tracked run cannot name its prompt now takes the ladder path foreign outputs use: decided at settle under the monitor policy, or after its run is sealed through the ladder wait. Wait entries carry their run kind; the kind selects the settings gate (SAVE_FOREIGN_RUNS for foreign entries, MONITORING_ENABLED for PromptManager ones) and the marks of a created prompt. Keyless images, placeholder batch entries and unreadable metadata never enter the wait. Every final unlinked outcome hands the file to the review recorder. Refs #659 * test(monitor): pin the final unlinked outcomes that reach Needs review The sweep, joined-text and shared-prefix graphs move to a shared fixture module. New tests pin when the monitor hands a file to its review recorder: after the sealed re-check, a settle lookup that found the run's record, a file outside ComfyUI's output folder and the keyless re-check; never before the run is sealed, and never for a linked file. A PromptManager output waiting for its run now logs that at INFO. Refs #659 * feat(review): offer inspection choices for default-unresolved files Decision.default_unresolved marks a file the default profile itself calls unresolved (a blank positive does not count). With inspection on, record_ambiguous_file now sends such a captured file with a prompt graph straight to the inspection-profile branch: a reviewable ambiguous or saver-anchored result is recorded, anything else is untraced. Apply is unchanged; it re-resolves with the item's recorded profile. Refs #659 * feat(review): one review dispatch and a review worker for monitor outputs review_dispatch holds the scan's per-file Needs review decision and is now also used by the monitor. The scan replaces its inline dispatch with it (and offers default-unresolved files their inspection choices). record_review_file runs the scan's per-file steps for one file, read only: the scan-policy ladder with the sealed history and the recorded-run check. A file the scan would link is skipped; otherwise the dispatch's record outcome is the answer. The monitor queues paths through queue_review_file onto one daemon worker (pm-review-recorder) with a bounded queue that coalesces by path and a bounded deferred set it replays once no job blocker remains. The package teardown stops it right after the monitor and reports it as part review once started. Refs #659 * docs(testing): the monitor queues what the scan would (#659) Rewrite the Needs review paragraph for the 2026-11-19 decision: the final-outcome points, the review worker and its bounds, the deferred replay and the default-unresolved rule. Document the PromptManager-run ladder path, the review step of the package teardown and the proven-value allowlist every future semantics table entry must keep. Refs #659 * fix(review): lock the untraced memory the scan and review worker share Refs #659 * feat(inspect): name the file's Needs review item in the inspection responses Inspect and the run-history current-file inspection gain a review field: {"state": "pending", "item_id": ...} for the newest pending item at the stat the inspection took, {"state": "decided"} once its item was decided, and null otherwise. It is read only when a role is ambiguous and the file is unlinked, by locator and stat (review_item_at), so Inspect never hashes the file. A LoRA root, a failed read and any malformed value give null. Refs #659 * feat(review): a single-item mode for the review controller and a shared option list createReviewController({api, itemId}) holds one named item: it never reads the queue, loads that item's detail, ends in phase decided (decided: true) after a recorded decision or for an item already decided, and re-reads the detail after a review-conflict, review-missing or restore refusal. The queue mode is unchanged. The Sampler context option list moves into renderReviewOptions (review-options.mjs, re-exported by review.mjs), so Needs review and the Inspect picker render the same options without Inspect importing the Needs review page. Refs #659 * feat(inspect): choose the prompt of an ambiguous file in Inspect When the inspection names the file's pending Needs review item, the inspector shows a Choose prompt section after its prompt blocks (Images panel, viewer details, recorded run current file). It reads the item's detail through the review controller's single-item mode: one Sampler context option per candidate (unusable ones disabled with their reason), the chosen option's prompt blocks with Copy and Send, Use this prompt and Leave unresolved over the Needs review apply flow. A recorded decision shows Needs review's toast and re-reads the inspection, so the file shows its link; an item with nothing to choose offers Open in Needs review. Refs #659 * fix(inspect): read the history review item only when Inspect asks The run-history reader locates the file under the scan roots inside the read, so an unambiguous or linked file costs no realpath of the output folders. The docstring names the linked-subfolder limit, and the newest pending item test pins the rowid tie-break. Refs #659 * fix(inspect): end Choose prompt on another read and on a decision made elsewhere The inspector disposes the section when it reads another file, fails or defers, so a decision in flight never re-reads the next file. A decided item hides the section and re-reads the inspection once, also when it was decided in another tab or in Needs review. Refs #659 * test(inspect): the rooted inspect shape gains the review facet Refs #659 * docs(testing): first-present candidates and per-role results (#657, #658) * test(review): keep the review cases ambiguous now that Any Switch resolves Part 1 resolves rgthree's Any Switch, so the sweep fixture links. The review and monitor tests that need a default-unresolved, inspection-ambiguous file now use ambiguous_sweep_graph(): Part A's any_switch_sweep_graph() with its switch class replaced by the never-listed PMTest Unknown Multi (one sweep graph instead of two). A new test pins that the real sweep links at settle from the inspector. Refs #657 #659 * fix(review): start the review worker again after an unexpected error * fix(inspect): pass the inspection refresh to Choose prompt by reference * feat(review): queue an ambiguous file with one readable choice (#657) An ambiguous result is reviewable when at least one candidate carries a resolved prompt (MIN_CHOOSABLE = 1). The sweep with an LLM enhancer on Any Switch any_01 now records an item, by the scan and the monitor, with the run-time branch listed beside the readable one. A file with no choosable candidate still records nothing. * feat(review): collapse too many candidates into the most used prompts (#657) More than 16 distinct candidates no longer make a limited item without choices. The choosable ones are grouped by their positive and negative texts, ordered by group size then first appearance, and the first 16 are kept, one real candidate each. The evidence names collapsed: {shown, total, paths} and the item detail returns it. Limited stays for evidence that cannot be projected or is over 8 MiB. REVIEW_EVIDENCE_VERSION is folded into every item version (default items now carry RESOLVER_VERSION + 1, inspection items fold it into their seed), so the next scan supersedes pending, undecided items of the old shape; decided items are kept. RESOLVER_VERSION, the ingestion's provenance version, is unchanged. * feat(inspect): record the Needs review item when Inspect finds none (#657) When Inspect asks for the review facet (an ambiguous role, an unlinked file under an output root) and no item exists at the inspected stat, the images and History current-file inspections run record_review_file, the review worker's own per-file path, in the executor and read the item again. A file the scan would link or that offers nothing to choose records nothing; a deferred or failed recording leaves review null and a failure is logged, never failing the response. * docs(testing): one readable choice, collapsed candidates, Inspect records (#657) * feat(review): say when a file's prompts were shortened to the most used (#657) The item detail now passes the stored evidence's optional `collapsed` counts ({shown, total, paths}) through to the page, null when absent, malformed, or when the detail was capped for size. Needs review and Inspect's Choose prompt show one line under Sampler context: "Showing the n most used of t prompts in this file." * feat(review): list the image's own prompts first in Link to a prompt (#657) With an empty search the dialog now lists the item's choosable candidates under "From this image" (positive / negative, one per prompt pair), then the Library's prompts under "Library". Choosing one of the image's prompts and pressing Link image applies that candidate by its hash, the same decision as Apply association (new controller.applyCandidate); no negative is asked for, the candidate carries its own. Typing searches the Library only. Items with no choosable candidate show the dialog as before. A refusal stays in the dialog with the server's sentence. * feat(review): load more of the queue on scroll (#657) The Needs review continuation now works like the Images page: an IntersectionObserver (250 px ahead) loads the next page when the end of the queue scrolls into view, and the line reads "40 of 45 images · more load as you scroll" without a button. Nothing loads behind an open dialog or the viewer; when one closes, focus returning to the page checks again. A failed page shows the failure line and a Retry button. Without IntersectionObserver the Load more images button stays. * fix(review): ask the inspection profile when the default choice is partial (#657) With one readable choice enough, a default result with one choice beside unresolved branches was recorded as is, so the inspection profile, which may read those branches (a Qwen image-edit sampler), was never asked and a rescan replaced older inspection items with the poorer default ones. Such a partial result now yields to the inspection result when that offers more choosable candidates. * fix(review): collapse only too many prompts, and apply any offered one (#657) Collapsing triggered on more than 16 distinct candidates, sampler ids included, so twenty samplers sharing three texts lost their run-time branches behind a collapsed note. Now only more than 16 choosable texts collapse; otherwise one candidate per text is kept and the branches without a prompt fill the remaining places, as an ordinary item. Apply's still-offered check compared the chosen hash with a fresh collapse, so a reorder that changed the representatives refused Apply. It now checks every projected, de-duplicated candidate hash (candidate_hashes). * fix(inspect): keep Inspect's recording quiet, bounded and current (#657) A busy capture store (the worker copying a fresh output) is an expected outcome: Inspect logs it at debug level and reads the item once more, also after a failed recording. A file Inspect found unrecordable (the scan would link it, or it offers nothing to choose) is remembered by its locator, stat and review versions, at most 4,096 files, so a repeated Inspect does not copy it again. A pending item of an older item version is recorded again, so the current record supersedes it. * docs(testing): partial default choices, bounded candidates, Inspect recording (#657) * fix(review): Link to a prompt drops an image choice it no longer shows (#657) Typing in the search box hid the "From this image" list but kept its chosen prompt, so Link image applied a candidate the reviewer could no longer see. Typing now drops that choice; Link image waits for a Library prompt and sends a Library link. Emptying the box lists the image's prompts again, none chosen. When the item's detail is read again while the dialog is open, the list follows what it offers now; a chosen prompt no longer offered is dropped with "This prompt is no longer offered for this file. Choose again." applyCandidate says the same when the hash cannot be chosen, and an unanswered apply from the dialog asks to press Link image again. * fix(review): keep the panel in place when Info brings it into view at one column (#657) At one column, Info scrolls the panel into view past the queue, which could bring the continuation into view and load the next page, pushing the panel away. As on the Images page, loading now waits for the reader's next wheel, touch move or key press. * docs(review): say why the review worker's recorder is a lambda * test(review): open the dialog of the D5 dialog test beside the queue (#657) At one column (touch) the review panel follows the queue just above the continuation, so scrolling Link to a prompt… into view brings the continuation within the observer's 250 px margin. The next page then loads before the dialog opens whenever the observer's callback runs first (CI shard 4/4, touch), and the test found no continuation to scroll to. That load is the page working as designed: the reader has reached the end of the queue. The test is about loading behind an open dialog, so it now runs at two columns, where Link sits in the sticky panel beside the queue, and it checks that the continuation is out of range before the dialog opens.
518 lines
20 KiB
Python
518 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 none there is nothing to choose (maintainer test of
|
|
# #284/#288: 39 items whose candidates were all "unresolved"). One is enough
|
|
# (#657 addendum D1, 2026-11-20): the other branches stay listed, disabled,
|
|
# and the user may still leave the file unresolved.
|
|
MIN_CHOOSABLE = 1
|
|
|
|
|
|
def evidence_offers_choice(evidence: Any) -> bool:
|
|
"""False when stored evidence provably offers nothing to choose.
|
|
|
|
Unlimited evidence must list ``MIN_CHOOSABLE`` choosable candidates (the
|
|
saver anchor's one pair, #390, counts like any other). A limited item
|
|
stores none, only ``candidate_total``; it may offer a choice unless that
|
|
total is too small.
|
|
"""
|
|
if not isinstance(evidence, dict):
|
|
return False
|
|
needed = MIN_CHOOSABLE
|
|
if evidence.get("limited"):
|
|
total = evidence.get("candidate_total")
|
|
return type(total) is int and total >= needed
|
|
candidates = evidence.get("candidates")
|
|
if not isinstance(candidates, list):
|
|
return False
|
|
return sum(1 for c in candidates if choosable(c)) >= needed
|
|
|
|
|
|
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.
|
|
|
|
Rows are read with ``fetchone``: iterating a managed connection's cursor
|
|
would prefetch ``ITER_CHUNK`` (128) rows (``database/managed_connection.py``).
|
|
"""
|
|
items = conn.execute(
|
|
f"SELECT evidence_hash, evidence FROM {ITEMS_TABLE}" # nosec B608
|
|
)
|
|
while (row := items.fetchone()) is not None:
|
|
evidence_hash, text = row[0], row[1]
|
|
if not _is_canonical(text) or evidence_digest(text) != evidence_hash:
|
|
return f"Review queue table {ITEMS_TABLE} contains invalid evidence"
|
|
decisions = conn.execute(f"SELECT evidence FROM {DECISIONS_TABLE}") # nosec B608
|
|
while (row := decisions.fetchone()) is not None:
|
|
text = row[0]
|
|
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
|