diff --git a/calliope-backend/scripts/audit_reference_conversion.py b/calliope-backend/scripts/audit_reference_conversion.py index f3ccc698..bb2f4a89 100644 --- a/calliope-backend/scripts/audit_reference_conversion.py +++ b/calliope-backend/scripts/audit_reference_conversion.py @@ -11,13 +11,18 @@ from __future__ import annotations import argparse import hashlib import json +from collections import Counter, defaultdict from pathlib import Path -from compare_frontend_exports import differences +try: + from scripts.compare_frontend_exports import differences +except ModuleNotFoundError: + from compare_frontend_exports import differences from calliope.comfyui.companions import load_companions from calliope.comfyui.delivery_scope import exclusion_for from calliope.comfyui.serialization_reference import ( + ASR_PROFILE, AUX_PROFILE, CASE04_PROFILE, PREVIEW_PROFILE, @@ -269,13 +274,324 @@ def audit(repo: Path, profile: str = PROFILE) -> dict: } +REFERENCE_PROFILES = ( + PROFILE, + AUX_PROFILE, + PRIMITIVE_PROFILE, + PREVIEW_PROFILE, + *STRUCTURE_PROFILES, + *PROMOTED_PROFILES, + CASE04_PROFILE, + ASR_PROFILE, +) + + +def canonical_sha(value): + """SHA256 of UTF-8 JSON, sorted keys, compact separators, no ASCII escaping.""" + return hashlib.sha256( + json.dumps( + value, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=False, + allow_nan=False, + ).encode("utf-8") + ).hexdigest() + + +def node_inventory(source): + rows = [] + graphs = [("", source)] + [ + (f"/definitions/subgraphs/{i}", graph) + for i, graph in enumerate((source.get("definitions") or {}).get("subgraphs", [])) + ] + for prefix, graph in graphs: + for i, node in enumerate(graph.get("nodes", [])): + props = node.get("properties") or {} + rows.append( + { + "pointer": f"{prefix}/nodes/{i}", + "node_id": str(node.get("id")), + "type": node.get("type"), + "provider": props.get("cnr_id"), + "version": props.get("ver"), + "mode": node.get("mode", 0), + "widget_count": len(node.get("widgets_values", [])), + "widget_layout": type(node.get("widgets_values", [])).__name__, + "ue_version": (props.get("ue_properties") or {}).get("version"), + } + ) + return rows + + +def asr_field_evidence(source, prompt): + """Bind every final ASR-profile input to original bytes or fixed UI rules.""" + fields = [] + for index, node in enumerate(source["nodes"]): + nid = str(node["id"]) + if nid not in prompt: + continue + names = { + "AILab_Qwen3ASR": ("model", "precision", "language", "hints", "unload_models"), + "LoadAudio": ("audio",), + "PreviewAny": ("previewMode",), + }[node["type"]] + for name, value in prompt[nid]["inputs"].items(): + socket = next((s for s in node.get("inputs", []) if s["name"] == name), {}) + if socket.get("link") is not None: + li, link = next( + (i, link) for i, link in enumerate(source["links"]) if link[0] == socket["link"] + ) + expected = [str(link[1]), link[2]] + pointer, rule = f"/links/{li}", "upstream ID to string; original output slot" + elif name in names: + wi = names.index(name) + expected = node["widgets_values"][wi] + pointer, rule = f"/nodes/{index}/widgets_values/{wi}", "fixed constructor identity" + else: + assert name in ("audioUI", "preview") + expected = "" + pointer, rule = None, "1.37.11 DOM without getValue; options.serialize boundary" + assert value == expected and type(value) is type(expected) + fields.append( + { + "node_id": nid, + "class_type": node["type"], + "field": name, + "value": value, + "json_type": type(value).__name__, + "source_pointer": pointer, + "rule": rule, + } + ) + return fields + + +def profile_attempt(source, profile): + expected = {**STRUCTURE_PROFILES, **PROMOTED_PROFILES, CASE04_PROFILE: "1.53.6"}.get( + profile, "1.37.11" + ) + assumptions = { + "frontend": expected, + "unmodified_frontend_and_widgets": True, + "target_version_match": "unknown", + "ue_serializer_match": "unknown", + "dynamic_options_and_files_available": "unknown", + "qwen_commit": "b037d7be121111a1ba6f40a4d99f6b43ac6411b6" + if profile in (ASR_PROFILE, PREVIEW_PROFILE, PRIMITIVE_PROFILE) + else None, + "qwen_missing_declaration": "explicit_reference_assumption_only", + "aux_commit": "e8b689a513c3e6b63edc44066560ca5919c0576e" + if profile == AUX_PROFILE + else None, + "aux_release_artifact_match": "unknown" if profile == AUX_PROFILE else "not_used", + "reference_sources": [ + "serialization-evidence/sources.json", + "structure-reference/sources.json", + "controlnet-reference/sources.json", + "promoted-reference/sources.json", + "case04-reference/sources.json", + ], + } + base = {"profile": profile, "assumptions": assumptions} + declared_frontend = (source.get("extra") or {}).get("frontendVersion") + assumptions["source_frontend_declaration"] = declared_frontend + assumptions["missing_frontend_policy"] = ( + "explicit_legacy_reference_assumption" + if profile in (PROFILE, AUX_PROFILE, PRIMITIVE_PROFILE) + else "requires_explicit_declaration" + ) + assumptions["missing_node_declarations"] = [ + n["pointer"] + for n in node_inventory(source) + if n["type"] not in ("Note", "MarkdownNote", "Reroute", "PrimitiveNode") + and (n["provider"] is None or n["version"] is None) + ] + if declared_frontend != expected and not ( + declared_frontend is None and profile in (PROFILE, AUX_PROFILE, PRIMITIVE_PROFILE) + ): + return { + **base, + "status": "not_applicable", + "issues": [ + { + "code": "frontend_not_applicable", + "message": "前端声明缺失或版本不匹配", + } + ], + } + result = convert_reference(source, profile) + if result.prompt is None: + return { + **base, + "status": "rejected", + "rejection_class": "missing_contract" + if any(i["code"] == "reference_node_unsupported" for i in result.issues) + else "serializer_or_structure_rejected", + "issues": result.issues, + "unresolved_boundaries": result.unresolved_boundaries, + } + # Legacy core serializers explicitly assume absent declarations. Record + # that assumption instead of implying that a type-name match proved it. + return { + **base, + "status": "complete_reference_candidate", + "issues": [], + "serialization_stage": result.serialization_stage + or "restored_saved_state_before_queue_hooks", + "candidate_sha256": canonical_sha(result.prompt), + "candidate_prompt": result.prompt, + **( + {"field_evidence": asr_field_evidence(source, result.prompt)} + if profile == ASR_PROFILE + else {} + ), + } + + +def audit_library(repo: Path, profiles=REFERENCE_PROFILES): + """Actually invoke every version-applicable profile; never choose first success. + + The immutable manifest/SHA binding and delivery_scope define the partition. + Candidates remain embedded in this isolated report, never the production DB. + """ + manifest = json.loads((repo / "docs/hel-892/offline/manifest.json").read_text()) + source_paths = { + p.relative_to(repo).as_posix() + for p in (repo / "example_ComfyUI_workflows").rglob("*") + if p.is_file() + } + manifest_paths = [r["path"] for r in manifest] + if len(manifest_paths) != len(set(manifest_paths)) or set(manifest_paths) != source_paths: + raise ValueError("源目录与manifest集合不一致或路径重复") + companions = load_companions(repo / "docs/hel-892/supplied-api/manifest.json") + rows, excluded, api_paths, gap_groups = [], [], [], defaultdict(list) + for record in manifest: + path = record["path"] + raw = (repo / path).read_bytes() + if hashlib.sha1(raw).hexdigest() != record["source_sha"]: + raise ValueError(f"源SHA与固定manifest不符:{path}") + if exclusion_for(path): + excluded.append(path) + continue + source = json.loads(raw) + if "nodes" not in source: + api_paths.append(path) + continue + inventory = node_inventory(source) + attempts = [profile_attempt(source, profile) for profile in profiles] + complete = [a for a in attempts if a["status"] == "complete_reference_candidate"] + hashes = sorted({a["candidate_sha256"] for a in complete}) + status = ( + "candidate_conflict" + if len(hashes) > 1 + else ("complete_reference_candidate" if complete else "blocked") + ) + companion = companions.get(path) + row = { + "source_path": path, + "source_sha1": record["source_sha"], + "source_sha256": hashlib.sha256(raw).hexdigest(), + "frontend_version": (source.get("extra") or {}).get("frontendVersion"), + "cohort": "with_companion" if companion else "without_companion", + "comparison_status": "comparison_available" if companion else "comparison_unavailable", + "status": status, + "inventory": inventory, + "attempts": attempts, + "complete_profiles": [a["profile"] for a in complete], + "candidate_hashes": hashes, + "target_version_match": "unknown", + "production_prompt_available": convert(source).prompt is not None, + "execution_verified": False, + } + if companion: + api = json.loads(companion["raw"]) + row["comparisons"] = [ + { + "profile": a["profile"], + "api_sha256": companion["binding"]["export_sha256"], + "differences": differences(api, a["candidate_prompt"]), + } + for a in complete + ] + rows.append(row) + if status == "blocked": + for attempt in attempts: + if attempt["status"] != "rejected": + continue + for issue in attempt["issues"]: + matches = [n for n in inventory if n["node_id"] == issue.get("node_id")] + for node in matches or [{}]: + key = ( + node.get("type"), + node.get("provider"), + node.get("version"), + attempt["profile"], + issue["code"], + issue["message"], + ) + gap_groups[key].append( + { + "source_path": path, + "node_pointer": node.get("pointer"), + "node_id": node.get("node_id"), + } + ) + summary = { + cohort: dict(Counter(r["status"] for r in rows if r["cohort"] == cohort)) + for cohort in ("without_companion", "with_companion") + } + old_complete = { + row["source_path"] + for row in rows + if any( + a["status"] == "complete_reference_candidate" and a["profile"] != ASR_PROFILE + for a in row["attempts"] + ) + } + now_complete = {row["source_path"] for row in rows if row["complete_profiles"]} + return { + "authority": "public_reference_only_not_object_info", + "source_total": len(manifest), + "target_total": len(rows) + len(api_paths), + "coverage_delta": { + "baseline": "all previous profiles excluding ASR_PROFILE; applied this run", + "previous_complete_paths": sorted(old_complete), + "current_complete_paths": sorted(now_complete), + "new_complete_paths": sorted(now_complete - old_complete), + }, + "ui_total": len(rows), + "api_paths": api_paths, + "excluded": excluded, + "summary": summary, + "profiles": list(profiles), + "cases": rows, + "gap_groups": [ + { + "type": k[0], + "provider": k[1], + "version": k[2], + "profile": k[3], + "code": k[4], + "rule_gap": k[5], + "occurrences": v, + } + for k, v in sorted(gap_groups.items(), key=lambda item: str(item[0])) + ], + "production_state_changed": False, + "execution_verified": False, + } + + def main(): parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", action="store_true", help="Audit current manifest UI scope") parser.add_argument("--repo", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument( "--profile", choices=( + ASR_PROFILE, PROFILE, AUX_PROFILE, PRIMITIVE_PROFILE, @@ -290,7 +606,7 @@ def main(): default=PROFILE, ) args = parser.parse_args() - report = audit(args.repo, args.profile) + report = audit_library(args.repo) if args.library else audit(args.repo, args.profile) args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n") print(json.dumps({"reference_only": True, "active_cases": len(report["cases"])})) diff --git a/calliope-backend/src/calliope/comfyui/serialization_reference.py b/calliope-backend/src/calliope/comfyui/serialization_reference.py index f8420926..52c11805 100644 --- a/calliope-backend/src/calliope/comfyui/serialization_reference.py +++ b/calliope-backend/src/calliope/comfyui/serialization_reference.py @@ -12,6 +12,7 @@ from __future__ import annotations from typing import Any +ASR_PROFILE = "comfy-frontend-1.37.11-asr-b037d7be-reference" PROFILE = "comfy-frontend-1.37.11-core-reference" AUX_PROFILE = "comfy-frontend-1.37.11-controlnet-aux-e8b689a-reference" AUX_COMMIT = "e8b689a513c3e6b63edc44066560ca5919c0576e" @@ -81,6 +82,23 @@ def reference_definitions(profile: str = PROFILE) -> dict[str, Any]: "output": outputs, } + if profile == ASR_PROFILE: + definitions = reference_definitions(PREVIEW_PROFILE) + return { + "LoadAudio": definitions["LoadAudio"], + "PreviewAny": definitions["PreviewAny"], + "AILab_Qwen3ASR": spec( + {"audio": "AUDIO"}, + ["STRING"], + { + "model": "COMBO", + "precision": "COMBO", + "language": "COMBO", + "hints": "STRING", + "unload_models": "BOOLEAN", + }, + ), + } if profile not in (PROFILE, AUX_PROFILE, PRIMITIVE_PROFILE, PREVIEW_PROFILE): raise ValueError("未知参考版本") definitions = { @@ -136,6 +154,14 @@ def reference_definitions(profile: str = PROFILE) -> dict[str, Any]: def serialize_reference_widgets(node: dict[str, Any], profile: str = PROFILE) -> dict[str, Any]: """Apply only the pinned identity serializers; reject any extra/missing value.""" + if profile == ASR_PROFILE: + if any(k in node for k in ("widgets", "widgets_values_named", "serializeValue")): + raise ValueError("ASR参考不支持自定义控件/serializer覆盖") + if node.get("type") == "LoadAudio": + return _serialize_subtitle(node) + if node.get("type") == "PreviewAny": + return _serialize_preview(node) + return _serialize_asr(node) if profile not in (PROFILE, AUX_PROFILE, PRIMITIVE_PROFILE, PREVIEW_PROFILE): raise ValueError("未知参考版本") if profile in (PRIMITIVE_PROFILE, PREVIEW_PROFILE) and node.get("type") in ( @@ -904,3 +930,92 @@ def serialize_case04_node(node): ): raise ValueError("autogrow只覆盖连续已连接输入及末尾空槽") return result + + +_ASR_LAYOUT = ( + ("model", str), + ("precision", str), + ("language", str), + ("hints", str), + ("unload_models", bool), +) +_ASR_LANGUAGES = ( + "auto", + "Chinese", + "English", + "Cantonese", + "Arabic", + "German", + "French", + "Spanish", + "Portuguese", + "Indonesian", + "Italian", + "Korean", + "Russian", + "Thai", + "Vietnamese", + "Japanese", + "Turkish", + "Hindi", + "Malay", + "Dutch", + "Swedish", + "Danish", + "Finnish", + "Polish", + "Czech", + "Filipino", + "Persian", + "Greek", + "Hungarian", + "Macedonian", + "Romanian", +) + + +def _serialize_asr(node): + """b037d7be five-widget ASR, explicitly assumed when declaration is absent. + + Not the fourteen-widget subtitle class or newer six-widget normalize_text + schema. Model membership and UE overrides remain unknown; no transcription. + """ + props = node.get("properties") or {} + if ( + node.get("type") != "AILab_Qwen3ASR" + or node.get("mode", 0) != 0 + or props.get("cnr_id") is not None + or props.get("ver") is not None + ): + raise ValueError("ASR参考要求无提供方/版本声明;显式声明未证明或模式不符") + values = node.get("widgets_values") + if not isinstance(values, list) or len(values) != len(_ASR_LAYOUT): + raise ValueError("ASR参考只覆盖5控件,不覆盖新版normalize_text或字幕14控件") + result = {} + for (name, kind), value in zip(_ASR_LAYOUT, values): + if type(value) is not kind: + raise ValueError(f"ASR字段 {name} 类型不符") + result[name] = value + if ( + result["precision"] not in ("bf16", "fp16", "fp32") + or result["language"] not in _ASR_LANGUAGES + ): + raise ValueError("ASR静态枚举不符") + allowed = { + "audio": "AUDIO", + "model": "COMBO", + "precision": "COMBO", + "language": "COMBO", + "hints": "STRING", + "unload_models": "BOOLEAN", + } + sockets = node.get("inputs", []) + if len(sockets) != len(allowed) or {s.get("name") for s in sockets} != set(allowed): + raise ValueError("ASR输入绑定缺失/重复/额外") + for socket in sockets: + name = socket["name"] + if socket.get("type") != allowed[name] or socket.get("widget") != ( + None if name == "audio" else {"name": name} + ): + raise ValueError("ASR输入类型/具名控件绑定不符") + return result diff --git a/calliope-backend/src/calliope/comfyui/ui2api.py b/calliope-backend/src/calliope/comfyui/ui2api.py index b99727d0..e7904526 100644 --- a/calliope-backend/src/calliope/comfyui/ui2api.py +++ b/calliope-backend/src/calliope/comfyui/ui2api.py @@ -14,6 +14,7 @@ from dataclasses import dataclass, field from typing import Any from .serialization_reference import ( + ASR_PROFILE, AUX_PROFILE, CASE04_PROFILE, PREVIEW_PROFILE, @@ -57,6 +58,7 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion: profile not in ( PROFILE, + ASR_PROFILE, AUX_PROFILE, PRIMITIVE_PROFILE, PREVIEW_PROFILE, @@ -116,7 +118,7 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion: result.resolved_boundaries = structure.resolved return result if ( - profile == PREVIEW_PROFILE + profile in (PREVIEW_PROFILE, ASR_PROFILE) and (source.get("extra") or {}).get("frontendVersion") != "1.37.11" ): raise ValueError("PreviewAny 需要显式1.37.11前端声明") @@ -131,6 +133,8 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion: except (ValueError, TypeError, KeyError, AttributeError, IndexError) as exc: return Conversion(None, [{"code": "invalid_reference_contract", "message": str(exc)}], True) result.reference_only = True + if profile == ASR_PROFILE: + result.serialization_stage = "restored_saved_state_before_queue_hooks" return result @@ -254,7 +258,10 @@ def _convert( raise ValueError("源输出槽不符合固定参考契约") names = [s.get("name") for s in node.get("inputs", [])] allowed = set(declared) | ({"upload"} if ct == "LoadImage" else set()) - if reference_profile in (PRIMITIVE_PROFILE, PREVIEW_PROFILE) and ct == "LoadAudio": + if ( + reference_profile in (PRIMITIVE_PROFILE, PREVIEW_PROFILE, ASR_PROFILE) + and ct == "LoadAudio" + ): allowed |= {"upload", "audioUI"} if len(names) != len(set(names)) or set(names) - allowed: raise ValueError("额外或重复输入槽不在固定参考契约内") @@ -312,7 +319,7 @@ def _convert( # Custom unions/wildcards need frontend evidence; do not guess coercions. if expected != actual and not ( reference - and reference_profile in (PREVIEW_PROFILE, CASE04_PROFILE) + and reference_profile in (PREVIEW_PROFILE, CASE04_PROFILE, ASR_PROFILE) and ct == "PreviewAny" and name == "source" and expected == "*" diff --git a/calliope-backend/tests/test_asr_library_reference.py b/calliope-backend/tests/test_asr_library_reference.py new file mode 100644 index 00000000..80d299c4 --- /dev/null +++ b/calliope-backend/tests/test_asr_library_reference.py @@ -0,0 +1,275 @@ +"""Real saved-source checks and explicitly synthetic mutations; no target execution.""" + +from __future__ import annotations + +import ast +import copy +import hashlib +import json +from pathlib import Path + +import pytest +from scripts import audit_reference_conversion as audit + +from calliope.comfyui.serialization_reference import ASR_PROFILE, PREVIEW_PROFILE +from calliope.comfyui.ui2api import Conversion, convert, convert_reference + +REPO = Path(__file__).resolve().parents[2] +SOURCE = "example_ComfyUI_workflows/1-语音生成/Qwen3-ASR-语音转文字.json" + + +def graph(): + return json.loads((REPO / SOURCE).read_bytes()) + + +def test_real_source_matches_fixed_original_contract_independently(): + source = graph() + original = copy.deepcopy(source) + result = convert_reference(source, ASR_PROFILE) + assert result.prompt is not None and result.reference_only + assert result.serialization_stage == "restored_saved_state_before_queue_hooks" + assert source == original and convert(source).prompt is None + # Parse syntax only: never import or execute upstream plugin. + tree = ast.parse((REPO / "docs/hel-892/structure-reference/qwen-b037d7be.py").read_text()) + cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "AILab_Qwen3ASR") + method = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == "INPUT_TYPES") + schema = next(n.value for n in ast.walk(method) if isinstance(n, ast.Return)) + optional = next(v for k, v in zip(schema.keys, schema.values) if k.value == "optional") + fields = [k.value for k in optional.keys] + assert fields == ["model", "precision", "language", "hints", "unload_models"] + assert any( + isinstance(n, ast.Assign) + and any(isinstance(t, ast.Name) and t.id == "RETURN_TYPES" for t in n.targets) + and ast.literal_eval(n.value) == ("STRING",) + for n in cls.body + ) + for node in source["nodes"]: + nid = str(node["id"]) + if node["type"] == "MarkdownNote": + assert nid not in result.prompt + continue + actual = result.prompt[nid] + assert actual["class_type"] == node["type"] + assert actual["_meta"] == {"title": node.get("title") or node["type"]} + if node["type"] == "AILab_Qwen3ASR": + for index, name in enumerate(fields): + assert actual["inputs"][name] == node["widgets_values"][index] + assert type(actual["inputs"][name]) is type(node["widgets_values"][index]) + if node["type"] == "LoadAudio": + assert actual["inputs"] == {"audio": node["widgets_values"][0], "audioUI": ""} + if node["type"] == "PreviewAny": + assert actual["inputs"]["preview"] == "" + assert actual["inputs"]["previewMode"] is None + for _, upstream, slot, target, input_slot, _ in source["links"]: + target_node = next(n for n in source["nodes"] if n["id"] == target) + name = target_node["inputs"][input_slot]["name"] + assert result.prompt[str(target)]["inputs"][name] == [str(upstream), slot] + + +@pytest.mark.parametrize("hints,unload", [("", False), ("第一行\n第二行", True), ("Qwen", False)]) +def test_two_instances_propagate_changed_values_without_cross_talk(hints, unload): + source = graph() + source["nodes"][0]["widgets_values"][3:] = [hints, unload] + source["nodes"][3]["widgets_values"][3:] = ["other\nvalue", not unload] + prompt = convert_reference(source, ASR_PROFILE).prompt + assert prompt["32"]["inputs"]["hints"] == hints + assert prompt["32"]["inputs"]["unload_models"] is unload + assert prompt["34"]["inputs"]["hints"] == "other\nvalue" + assert prompt["34"]["inputs"]["unload_models"] is not unload + assert "normalize_text" not in prompt["32"]["inputs"] + + +@pytest.mark.parametrize( + "mutation", + [ + "extra", + "missing", + "boolean_integer", + "text_null", + "precision", + "language", + "provider", + "version", + "mode", + "widget_binding", + "input_type", + "missing_socket", + "extra_socket", + "output", + "custom", + "frontend", + "missing_frontend", + "bad_link", + "audio_extra", + "preview_extra", + "subtitle", + ], +) +def test_invalid_assumptions_never_emit_partial_prompt(mutation): + source = graph() + node = source["nodes"][0] + if mutation == "extra": + node["widgets_values"].append(True) + elif mutation == "missing": + node["widgets_values"].pop() + elif mutation == "boolean_integer": + node["widgets_values"][4] = 1 + elif mutation == "text_null": + node["widgets_values"][3] = None + elif mutation == "precision": + node["widgets_values"][1] = "unknown" + elif mutation == "language": + node["widgets_values"][2] = "unknown" + elif mutation == "provider": + node["properties"]["cnr_id"] = "other" + elif mutation == "version": + node["properties"]["ver"] = "new" + elif mutation == "mode": + node["mode"] = 2 + elif mutation == "widget_binding": + node["inputs"][4]["widget"] = {"name": "model"} + elif mutation == "input_type": + node["inputs"][4]["type"] = "COMBO" + elif mutation == "missing_socket": + node["inputs"].pop() + elif mutation == "extra_socket": + node["inputs"].append(copy.deepcopy(node["inputs"][1])) + elif mutation == "output": + node["outputs"].append({"type": "STRING", "links": []}) + elif mutation == "custom": + node["serializeValue"] = "unknown" + elif mutation == "frontend": + source["extra"]["frontendVersion"] = "1.53.6" + elif mutation == "missing_frontend": + source["extra"].pop("frontendVersion") + elif mutation == "bad_link": + source["links"][0][2] = 1 + elif mutation == "audio_extra": + source["nodes"][1]["widgets_values"].append("extra") + elif mutation == "preview_extra": + source["nodes"][2]["widgets_values"].append(None) + elif mutation == "subtitle": + node["type"] = "AILab_Qwen3ASRSubtitle" + result = convert_reference(source, ASR_PROFILE) + assert result.prompt is None and result.issues + + +def test_actual_library_partition_delta_and_no_partial_candidates(): + report = audit.audit_library(REPO) + old = audit.audit_library(REPO, tuple(p for p in audit.REFERENCE_PROFILES if p != ASR_PROFILE)) + paths = {r["source_path"] for r in report["cases"]} + assert report["source_total"] == len(paths) + len(report["api_paths"]) + len(report["excluded"]) + assert not paths.intersection(report["excluded"] + report["api_paths"]) + newly_complete = {r["source_path"] for r in report["cases"] if r["complete_profiles"]} - { + r["source_path"] for r in old["cases"] if r["complete_profiles"] + } + assert newly_complete == {SOURCE} + assert len([r for r in report["cases"] if r["cohort"] == "with_companion"]) == 6 + for row in report["cases"]: + assert ( + hashlib.sha256((REPO / row["source_path"]).read_bytes()).hexdigest() + == row["source_sha256"] + ) + assert not row["production_prompt_available"] + if row["cohort"] == "without_companion": + assert row["comparison_status"] == "comparison_unavailable" + assert "comparisons" not in row + for attempt in row["attempts"]: + assert ("candidate_prompt" in attempt) == ( + attempt["status"] == "complete_reference_candidate" + ) + if "candidate_prompt" in attempt: + assert ( + audit.canonical_sha(attempt["candidate_prompt"]) == attempt["candidate_sha256"] + ) + assert all( + r["status"] in ("blocked", "complete_reference_candidate", "candidate_conflict") + for r in report["cases"] + ) + + +def synthetic_repo(tmp_path, monkeypatch): + """Explicitly synthetic tiny manifest, not a real export/history.""" + (tmp_path / "docs/hel-892/offline").mkdir(parents=True) + (tmp_path / "example_ComfyUI_workflows").mkdir() + raw = json.dumps(graph()).encode() + (tmp_path / "example_ComfyUI_workflows/synthetic.json").write_bytes(raw) + (tmp_path / "docs/hel-892/offline/manifest.json").write_text( + json.dumps( + [ + { + "path": "example_ComfyUI_workflows/synthetic.json", + "source_sha": hashlib.sha1(raw).hexdigest(), + }, + ] + ) + ) + monkeypatch.setattr(audit, "load_companions", lambda _: {}) + return tmp_path + + +def test_source_manifest_sha_mismatch_rejected(tmp_path, monkeypatch): + repo = synthetic_repo(tmp_path, monkeypatch) + (repo / "example_ComfyUI_workflows/synthetic.json").write_text("{}") + with pytest.raises(ValueError, match="SHA"): + audit.audit_library(repo) + + +def test_profile_conflicts_are_reported_not_selected(tmp_path, monkeypatch): + repo = synthetic_repo(tmp_path, monkeypatch) + + def conflict(source, profile): + return Conversion({"synthetic": {"class_type": profile, "inputs": {}}}, reference_only=True) + + monkeypatch.setattr(audit, "convert_reference", conflict) + monkeypatch.setattr(audit, "asr_field_evidence", lambda *_: []) + row = audit.audit_library(repo, (ASR_PROFILE, PREVIEW_PROFILE))["cases"][0] + assert row["status"] == "candidate_conflict" + assert len(row["candidate_hashes"]) == 2 + assert len(row["complete_profiles"]) == 2 + + +def test_explicit_frontend_conflict_skips_conversion(): + source = graph() + source["extra"]["frontendVersion"] = "unknown" + result = audit.profile_attempt(source, ASR_PROFILE) + assert result["status"] == "not_applicable" and "candidate_prompt" not in result + + +def test_identical_candidates_keep_both_assumptions(tmp_path, monkeypatch): + repo = synthetic_repo(tmp_path, monkeypatch) + monkeypatch.setattr( + audit, + "convert_reference", + lambda *_: Conversion( + {"synthetic": {"class_type": "same", "inputs": {}}}, reference_only=True + ), + ) + monkeypatch.setattr(audit, "asr_field_evidence", lambda *_: []) + row = audit.audit_library(repo, (ASR_PROFILE, PREVIEW_PROFILE))["cases"][0] + assert row["status"] == "complete_reference_candidate" + assert len(row["complete_profiles"]) == 2 and len(row["candidate_hashes"]) == 1 + + +def test_changed_dynamic_model_string_and_socket_order_follow_fixed_constructor(): + source = graph() + source["nodes"][0]["widgets_values"] = ["unverified/model", "fp32", "Chinese", "", False] + # Keep the connected audio socket first; reorder only named widget sockets. + node = source["nodes"][0] + node["inputs"] = node["inputs"][:1] + list(reversed(node["inputs"][1:])) + result = audit.profile_attempt(source, ASR_PROFILE) + assert result["status"] == "complete_reference_candidate" + values = result["candidate_prompt"]["32"]["inputs"] + assert values["model"] == "unverified/model" + assert values["precision"] == "fp32" and values["language"] == "Chinese" + assert values["unload_models"] is False + assert result["assumptions"]["dynamic_options_and_files_available"] == "unknown" + evidence = result["field_evidence"] + assert len(evidence) == sum(len(n["inputs"]) for n in result["candidate_prompt"].values()) + + +def test_manifest_cannot_hide_new_source_file(tmp_path, monkeypatch): + repo = synthetic_repo(tmp_path, monkeypatch) + (repo / "example_ComfyUI_workflows/unlisted.json").write_text("{}") + with pytest.raises(ValueError, match="集合"): + audit.audit_library(repo)