* fix(ingestion): link an image only to a prompt that provably produced it An LLM fed a PromptManagerPair's prepend_text while its text editor was empty. The node refused to save (an empty positive raised and logged a warning), and the image monitor then linked the image to a stale tracker entry or to the newest prompt in the database. - Nodes: an empty text editor saves and tracks nothing (prepend and append text are never the stored prompt), logs at info, and marks the node's run key empty so no earlier entry can be used for its images. - Tracker entries carry a run key: a digest of the prompt node and its whole upstream graph, the identity ComfyUI's cache uses. The monitor computes the same key from the image's embedded graph and uses a queued or snapshot entry only when the keys match (a snapshot also needs a known run with one entry, so a batch's last item is never applied to every image). - The recency fallback is gone; anything uncertain stays unlinked and is logged at info. - Recorded execution history attributes a file when exactly one run reported it, the file was written during that run, and the run's positive contexts name one stored prompt. The monitor and the output scan use it as their last certain source. - The scan and pair ingestion treat a resolved pair with an empty stored positive as unresolved instead of raising. - tools/review_image_links.py reviews selected links by these rules; dry run by default, --apply changes only named ids after a backup. Closes #342 * test(ingestion): real-host attribution case and the #342 testing contract The managed host disables the image monitor, so the owned fixture pack gains a route that starts and stops the plugin's monitor singleton for the attribution case only. The case runs in both renderers: a typed Pair image links, a Pair image whose positive is only linked prepend text stays unlinked with nothing stored, an unknown node feeding text links through its run key, and its cached re-run links again. * fix(ingestion): take a queued entry only from the run the image appeared in Dropping a key's older queue entries whenever the node ran again let a later queued run, executing during the monitor's processing delay, take the earlier image's entry. The snapshot taken when the image appears now names the key's latest run, and the queue is popped by key and run: same-key entries of earlier runs ahead of it are stale, entries of later runs wait for their own images. Also keeps the attribution case out of the stock real-host suite. * test(ingestion): host lookups degrade to no proof * fix(ingestion): address the #344 review (history re-check, keys, repair) - Images without an embedded API graph: the scan now asks recorded history before skipping a file with no prompt metadata, and the monitor gives a keyless unlinked image one history-only re-check when its run's outputs are recorded (a seal notification from the outputs write; at most 1000 waiting images, each for an hour). - Run keys: an image is unkeyable when any positive node has no key, so a two-pass graph is never linked through the other pass; links follow ComfyUI's is_link exactly. - A failed save marks the node's run key like an empty editor, so an older entry of that key can't stand in for this run. - A placeholder is the latest entry: the image stays unlinked without falling through to history, the same rule as a popped placeholder. - An index on execution_run_outputs(filename, subfolder, root_key, path_style) for the history lookup, added by migration and accepted by the output schema check (any other index is still refused). - Repair tool: unlink removes only the link record and only while the image is still linked to the prompt it was judged on; every run prints what --apply does. - Real-host case proves the re-run's PromptManager node was cached. * test(ingestion): real-host bare-output re-check and the review-round contract A metadata-disabled save, held open behind the fixture gate after SaveImage, waits unlinked while its run is open and links once the run's outputs are recorded. The fixture's monitor route lists the waiting files. TESTING.md covers the history re-check, the read index and what the repair tool's --apply does. * fix(ingestion): batch history lookups instead of adding an index An index on execution_run_outputs would make the library unopenable by older builds, whose schema check refuses any extra index there. The migration and the schema-check allowance are reverted, so the history schema is exactly main's. stored_run_prompts instead looks up a batch of files with one parameterized filename IN (...) query per chunk of at most 500 names and matches in memory; the scan computes it once per scan batch. * fix(ingestion): address the #344 re-review (seal race, linked roots) - A sealed history re-check that can't be scheduled yet (the image's own pass still pending, or the pending set full) is kept due and scheduled when a pending image finishes, instead of being dropped. - History matches a file through ComfyUI's spelling of its output folder first, then with both sides resolved, so a symlinked or junction output folder still attributes the scan's resolved paths; waiting files are keyed by their resolved path. - The scan makes its batch history lookup only when a file needs it. - set_current_prompt pushes to the queue last, so marking a failed execution never adds a second queue slot. - A keyless image outside the output folder doesn't take a waiting slot.
138 lines
5.4 KiB
Python
138 lines
5.4 KiB
Python
"""Bounded read-only SQLite inspection for the owned execution fixture."""
|
|
|
|
import argparse
|
|
from contextlib import closing
|
|
import json
|
|
from pathlib import Path
|
|
import sqlite3
|
|
import sys
|
|
from types import SimpleNamespace
|
|
from uuid import UUID
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
|
from database.execution_contexts import ExecutionContextOperations # noqa: E402
|
|
from database.execution_history import ExecutionHistoryOperations # noqa: E402
|
|
from database.execution_outputs import ExecutionOutputOperations # noqa: E402
|
|
|
|
|
|
class _ReadOnlyHistory(
|
|
ExecutionContextOperations, ExecutionHistoryOperations, ExecutionOutputOperations
|
|
):
|
|
def __init__(self, connection: sqlite3.Connection) -> None:
|
|
self.model = SimpleNamespace(get_connection=lambda: connection)
|
|
|
|
|
|
def read_runs(database: str, job_id: str, session_id: str | None = None) -> dict:
|
|
job_id = str(UUID(job_id))
|
|
if session_id is not None:
|
|
session_id = str(UUID(session_id))
|
|
uri = Path(database).resolve().as_uri() + "?mode=ro"
|
|
with sqlite3.connect(uri, uri=True, timeout=0.25) as connection:
|
|
connection.row_factory = sqlite3.Row
|
|
connection.execute("PRAGMA query_only=ON")
|
|
table = connection.execute(
|
|
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='execution_runs'"
|
|
).fetchone()
|
|
if table is None:
|
|
return {"schemaAvailable": False, "rows": []}
|
|
sql = "SELECT * FROM execution_runs WHERE job_id=?"
|
|
parameters = [job_id]
|
|
if session_id is not None:
|
|
sql += " AND session_id=?"
|
|
parameters.append(session_id)
|
|
rows = connection.execute(
|
|
sql + " ORDER BY rowid LIMIT 257", parameters
|
|
).fetchall()
|
|
if len(rows) > 256:
|
|
raise ValueError("Execution query exceeds the 256-row bound")
|
|
reader = _ReadOnlyHistory(connection)
|
|
captures = {
|
|
row["run_id"]: reader.get_execution_contexts(row["run_id"]) for row in rows
|
|
}
|
|
usage = {}
|
|
snapshot_ids = {}
|
|
for run_id, capture in captures.items():
|
|
usage[run_id] = []
|
|
snapshot_ids[run_id] = []
|
|
for context in capture["contexts"]:
|
|
for role in ("positive", "negative"):
|
|
prompt_id = context[f"{role}_prompt_id"]
|
|
if prompt_id is not None:
|
|
count = connection.execute(
|
|
"SELECT run_count FROM prompts WHERE id=?", (prompt_id,)
|
|
).fetchone()[0]
|
|
usage[run_id].append({"role": role, "run_count": count})
|
|
pair_id = context["pair_id"]
|
|
if pair_id is not None:
|
|
count = connection.execute(
|
|
"SELECT run_count FROM prompt_pairs WHERE id=?", (pair_id,)
|
|
).fetchone()[0]
|
|
usage[run_id].append({"role": "pair", "run_count": count})
|
|
snapshot_ids[run_id].append(
|
|
dict(
|
|
connection.execute(
|
|
"SELECT positive_snapshot_id,negative_snapshot_id "
|
|
"FROM execution_contexts WHERE context_id=?",
|
|
(context["context_id"],),
|
|
).fetchone()
|
|
)
|
|
)
|
|
return {
|
|
"schemaAvailable": True,
|
|
"rows": [dict(row) for row in rows],
|
|
"captures": captures,
|
|
"usage": usage,
|
|
"snapshotIds": snapshot_ids,
|
|
"outputs": {
|
|
row["run_id"]: reader.get_execution_outputs(row["run_id"])
|
|
for row in rows
|
|
},
|
|
}
|
|
|
|
|
|
def read_links(database: str, filenames: list, texts: list) -> dict:
|
|
"""Each output file's linked prompt text (None: unlinked), and which texts
|
|
are stored as prompts (#342)."""
|
|
uri = Path(database).resolve().as_uri() + "?mode=ro"
|
|
with closing(sqlite3.connect(uri, uri=True, timeout=0.25)) as connection:
|
|
connection.execute("PRAGMA query_only=ON")
|
|
links = {}
|
|
for name in filenames[:64]:
|
|
rows = connection.execute(
|
|
"SELECT p.text FROM generated_images g JOIN prompts p "
|
|
"ON p.id = g.prompt_id WHERE g.filename = ? LIMIT 2",
|
|
(name,),
|
|
).fetchall()
|
|
values = [row[0] for row in rows]
|
|
links[name] = values[0] if len(values) == 1 else None
|
|
if len(values) > 1:
|
|
links[name] = "<several links>"
|
|
stored = {
|
|
text: connection.execute(
|
|
"SELECT 1 FROM prompts WHERE text = ? LIMIT 1", (text,)
|
|
).fetchone()
|
|
is not None
|
|
for text in texts[:64]
|
|
}
|
|
return {"links": links, "stored": stored}
|
|
|
|
|
|
if __name__ == "__main__":
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("database")
|
|
parser.add_argument("job_id", nargs="?")
|
|
parser.add_argument("--session-id")
|
|
parser.add_argument("--links", nargs="*", default=None)
|
|
parser.add_argument("--texts", nargs="*", default=[])
|
|
arguments = parser.parse_args()
|
|
if arguments.links is not None:
|
|
print(
|
|
json.dumps(read_links(arguments.database, arguments.links, arguments.texts))
|
|
)
|
|
else:
|
|
print(
|
|
json.dumps(
|
|
read_runs(arguments.database, arguments.job_id, arguments.session_id)
|
|
)
|
|
)
|