* 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.
160 lines
5.9 KiB
Python
160 lines
5.9 KiB
Python
"""Immutable run-owned output references, independent of mutable galleries."""
|
|
|
|
import sqlite3
|
|
from contextlib import ExitStack
|
|
from typing import Callable, ContextManager
|
|
|
|
from .run_attribution import notify_outputs_sealed
|
|
|
|
try:
|
|
from ..utils.execution_history_events import RunFinish, encode_command
|
|
from ..utils.execution_outputs import OutputBundle, validate_output_bundle
|
|
except ImportError:
|
|
from utils.execution_history_events import RunFinish, encode_command
|
|
from utils.execution_outputs import OutputBundle, validate_output_bundle
|
|
|
|
|
|
_REFERENCE_FIELDS = (
|
|
"output_node_id",
|
|
"image_ordinal",
|
|
"folder_type",
|
|
"subfolder",
|
|
"filename",
|
|
"path_style",
|
|
"root_key",
|
|
)
|
|
_REFERENCE_COLUMNS = ",".join(_REFERENCE_FIELDS)
|
|
|
|
|
|
def _capture(conn: sqlite3.Connection, run_id: str) -> sqlite3.Row | None:
|
|
capture = conn.execute(
|
|
"SELECT state,reason,format_version,source FROM execution_output_capture "
|
|
"WHERE run_id=?",
|
|
(run_id,),
|
|
).fetchone()
|
|
# Legacy callers may disable FK enforcement; never adopt orphan evidence.
|
|
if capture is None:
|
|
if conn.execute(
|
|
"SELECT 1 FROM execution_run_outputs WHERE run_id=? LIMIT 1", (run_id,)
|
|
).fetchone():
|
|
raise sqlite3.DatabaseError("Output references have no capture header")
|
|
elif (
|
|
conn.execute(
|
|
"SELECT 1 FROM execution_runs WHERE run_id=?", (run_id,)
|
|
).fetchone()
|
|
is None
|
|
):
|
|
raise sqlite3.DatabaseError("Output capture has no execution parent")
|
|
return capture
|
|
|
|
|
|
def _references(conn: sqlite3.Connection, run_id: str) -> list[tuple]:
|
|
return [
|
|
tuple(row)
|
|
for row in conn.execute(
|
|
f"SELECT {_REFERENCE_COLUMNS} FROM execution_run_outputs "
|
|
"WHERE run_id=? ORDER BY output_node_id,image_ordinal",
|
|
(run_id,),
|
|
)
|
|
]
|
|
|
|
|
|
class ExecutionOutputOperations:
|
|
"""Compose with ExecutionHistoryOperations on PromptDatabase."""
|
|
|
|
def write_execution_outputs_for_finish(
|
|
self,
|
|
command: RunFinish,
|
|
bundle: OutputBundle,
|
|
*,
|
|
generation_guard: Callable[[], ContextManager[bool]] | None = None,
|
|
) -> bool:
|
|
encode_command(command)
|
|
if type(command) is not RunFinish:
|
|
raise ValueError("Expected execution finish command")
|
|
validate_output_bundle(bundle)
|
|
header = (bundle.state, bundle.reason, bundle.format_version, bundle.source)
|
|
prepared = [
|
|
tuple(getattr(reference, field) for field in _REFERENCE_FIELDS)
|
|
for reference in bundle.references
|
|
]
|
|
# Enter after BEGIN and retain the guard until COMMIT/ROLLBACK finishes.
|
|
with ExitStack() as guards:
|
|
with self._execution_transaction(command.storage_epoch) as conn:
|
|
if generation_guard is not None and not guards.enter_context(
|
|
generation_guard()
|
|
):
|
|
return False
|
|
parent = conn.execute(
|
|
"SELECT run_id FROM execution_runs WHERE session_id=? "
|
|
"AND queue_item_id=? AND storage_epoch=?",
|
|
(command.session_id, command.queue_item_id, command.storage_epoch),
|
|
).fetchone()
|
|
if parent is None:
|
|
return False
|
|
run_id = parent[0]
|
|
capture = _capture(conn, run_id)
|
|
if capture is not None:
|
|
if capture[0] != "conflicting" and (
|
|
tuple(capture) != header
|
|
or _references(conn, run_id) != prepared
|
|
):
|
|
conn.execute(
|
|
"UPDATE execution_output_capture SET "
|
|
"state='conflicting',reason='conflicting' WHERE run_id=?",
|
|
(run_id,),
|
|
)
|
|
return True
|
|
conn.execute(
|
|
"INSERT INTO execution_output_capture "
|
|
"(run_id,state,reason,format_version,source) VALUES(?,?,?,?,?)",
|
|
(run_id, *header),
|
|
)
|
|
conn.executemany(
|
|
f"INSERT INTO execution_run_outputs (run_id,{_REFERENCE_COLUMNS}) "
|
|
"VALUES(?,?,?,?,?,?,?,?)",
|
|
[(run_id, *reference) for reference in prepared],
|
|
)
|
|
# Committed: images waiting for this run may now be attributed (#342)
|
|
notify_outputs_sealed(
|
|
run_id, [dict(zip(_REFERENCE_FIELDS, row)) for row in prepared]
|
|
)
|
|
return True
|
|
|
|
def get_execution_outputs(self, run_id: str) -> dict:
|
|
"""Read frozen evidence in one snapshot without resolving its locators."""
|
|
conn = self.model.get_connection()
|
|
own_transaction = not conn.in_transaction
|
|
if own_transaction:
|
|
conn.execute("BEGIN")
|
|
try:
|
|
capture = _capture(conn, run_id)
|
|
if capture is None:
|
|
return {
|
|
"state": "not_captured",
|
|
"reason": None,
|
|
"format_version": None,
|
|
"source": None,
|
|
"references": [],
|
|
}
|
|
references = []
|
|
for row in _references(conn, run_id):
|
|
reference = dict(zip(_REFERENCE_FIELDS, row))
|
|
reference.update(
|
|
file_identity="unverified",
|
|
newly_generated="unknown",
|
|
context_membership="unknown",
|
|
transient=reference["folder_type"] == "temp",
|
|
)
|
|
references.append(reference)
|
|
return {
|
|
"state": capture[0],
|
|
"reason": capture[1],
|
|
"format_version": capture[2],
|
|
"source": capture[3],
|
|
"references": references,
|
|
}
|
|
finally:
|
|
if own_transaction:
|
|
conn.rollback()
|