"""Normalize workflow material binding payloads for generation nodes.""" from __future__ import annotations from copy import deepcopy from typing import Any from backend.dto.common import ApiError, ErrorCode from backend.dto.workflow_dto import WorkflowNode from engines.character_flow import canonical_gradual_node_key from core.text_utils import optional_text as _optional_text MATERIAL_BINDING_SCHEMA_VERSION = "2026-07-09.material-binding-schema.v1" # Only versions listed here may take the "already normalized" path. An # unrecognized version must fail closed rather than fall through, otherwise a # future/forged marker is an easy way to smuggle an unchecked payload past the # normalizer. KNOWN_MATERIAL_BINDING_SCHEMA_VERSIONS: frozenset[str] = frozenset({MATERIAL_BINDING_SCHEMA_VERSION}) NODE_MATERIAL_BINDING_SCHEMA_VERSION = "2026-07-15.node-material-bindings.v1" NODE_MATERIAL_BINDING_METADATA_KEY = "node_material_bindings" REFERENCE_POLICY = { "mode": "explicit_only", "default_use_reference": False, "empty_material_means": "do_not_use_reference", } STAGE_NODE_KEYS: dict[str, tuple[str, ...]] = { "profile-prep": ("profile_brief", "prompt_plan", "material_bind"), "portrait-draft": ("headshot", "fast_candidates"), "halfbody-draft": ("upper_body", "lower_body"), "body-sheet": ("full_body", "turnaround", "design_sheet"), "review-archive": ("style_lock", "profile_card", "fast_final"), } STRENGTHS: dict[str, tuple[str, float]] = { "强": ("strong", 0.85), "strong": ("strong", 0.85), "high": ("strong", 0.85), "中": ("medium", 0.55), "medium": ("medium", 0.55), "mid": ("medium", 0.55), "弱": ("weak", 0.3), "weak": ("weak", 0.3), "low": ("weak", 0.3), } def normalize_material_bindings( payload: Any, workflow_nodes: list[WorkflowNode] | None = None, ) -> dict[str, Any]: """Return one canonical material-binding document for ``payload``. A payload carrying a ``schema_version`` claims to be normalized already and must not go through the raw rewrite: ``_normalize_rule`` reads the *raw* rule shape (``material_id``) rather than the normalized one (``material.material_id``), so re-running it on a normalized rule silently empties every binding. That second path used to be granted on the version marker alone, which turned the marker itself into the bypass -- any client could staple the current version string onto arbitrary content and have it stored, then replayed verbatim, including a forged ``by_node_id`` view that feeds straight into generation prompts. Reads take the same path, so a single such write poisoned the ``material_bind`` node permanently. The claim is now verified instead of trusted, an unrecognized version fails closed, and every derived index is recomputed from the rules rather than carried over from the caller. """ declared_version = _optional_text(payload.get("schema_version")) if isinstance(payload, dict) else None if declared_version is not None: if declared_version not in KNOWN_MATERIAL_BINDING_SCHEMA_VERSIONS: raise ApiError( ErrorCode.VALIDATION_FAILED, "素材绑定数据的 schema_version 无法识别,请使用当前版本重新提交", { "field": "material_bindings.schema_version", "actual": declared_version, "supported_versions": sorted(KNOWN_MATERIAL_BINDING_SCHEMA_VERSIONS), }, ) raw_rules = payload.get("rules") if not isinstance(raw_rules, list): raise ApiError( ErrorCode.VALIDATION_FAILED, "素材绑定数据缺少合法的 rules 列表", { "field": "material_bindings.rules", "actual_type": type(raw_rules).__name__, }, ) rules = [_validated_normalized_rule(rule, index + 1) for index, rule in enumerate(raw_rules)] return _assemble_bindings(rules, payload, workflow_nodes) source = _extract_source_payload(payload) rules = [ _normalize_rule(rule, index + 1) for index, rule in enumerate(source.get("rules", []) if isinstance(source.get("rules"), list) else []) if isinstance(rule, dict) ] return _assemble_bindings(rules, source, workflow_nodes) def _assemble_bindings( rules: list[dict[str, Any]], source: dict[str, Any], workflow_nodes: list[WorkflowNode] | None, ) -> dict[str, Any]: active_rules = [rule for rule in rules if rule["use_reference"]] by_stage = _index_by_stage(active_rules) by_node_key = _index_by_node_key(active_rules) by_node_id = _index_by_node_id(active_rules, workflow_nodes or []) selected_material_ids = _string_list(source.get("selected_material_ids")) if not selected_material_ids: selected_material_ids = [rule["material"]["material_id"] for rule in active_rules] return { "schema_version": MATERIAL_BINDING_SCHEMA_VERSION, "reference_policy": deepcopy(REFERENCE_POLICY), "profile_id": _optional_text(source.get("profile_id")), "profile_name": _optional_text(source.get("profile_name")), "selected_material_ids": _unique_texts(selected_material_ids), "rules": rules, "active_rules": active_rules, "by_stage": by_stage, "by_node_key": by_node_key, "by_node_id": by_node_id, "node_parameters": by_node_id, "prompt_context": _prompt_context(active_rules), "summary": { "rule_count": len(rules), "active_rule_count": len(active_rules), "has_references": bool(active_rules), "disabled_categories": [rule["category"] for rule in rules if not rule["use_reference"]], "target_stage_ids": sorted(by_stage), "target_node_keys": sorted(by_node_key), }, } def material_bindings_for_node( workflow_metadata: dict[str, Any], node: WorkflowNode, workflow_nodes: list[WorkflowNode] | None = None, ) -> dict[str, Any]: normalized = normalize_material_bindings(workflow_metadata.get("material_bindings"), workflow_nodes) inherited = node_material_binding_view(normalized, node) state = ( node.metadata.get(NODE_MATERIAL_BINDING_METADATA_KEY) if isinstance(node.metadata, dict) else None ) if not isinstance(state, dict): return inherited return node_material_binding_override_view(state, node, inherited=inherited) def node_material_binding_view(normalized: dict[str, Any], node: WorkflowNode) -> dict[str, Any]: by_node_id = normalized.get("by_node_id") if isinstance(normalized.get("by_node_id"), dict) else {} by_node_key = normalized.get("by_node_key") if isinstance(normalized.get("by_node_key"), dict) else {} node_view = by_node_id.get(node.node_id) if not isinstance(node_view, dict): node_view = _node_view( active_rules=by_node_key.get(canonical_gradual_node_key(node.node_key), []), node_id=node.node_id, node_key=node.node_key, title=node.title, ) result = { "schema_version": normalized.get("schema_version", MATERIAL_BINDING_SCHEMA_VERSION), "reference_policy": normalized.get("reference_policy", deepcopy(REFERENCE_POLICY)), "summary": normalized.get("summary", {}), "target_node_id": node.node_id, "target_node_key": node.node_key, "target_node_title": node.title, **node_view, } generation_params = result.get("generation_params") selected_material_ids = ( generation_params.get("reference_material_ids") if isinstance(generation_params, dict) and isinstance(generation_params.get("reference_material_ids"), list) else [] ) result["selected_material_ids"] = _unique_texts(selected_material_ids) result.setdefault("temporary_references", []) result.setdefault("navigation_context", {}) result["binding_source"] = "workflow_material_bind" return result def node_material_binding_override_view( state: dict[str, Any], node: WorkflowNode, *, inherited: dict[str, Any] | None = None, ) -> dict[str, Any]: """Return one node-scoped binding view over the workflow-level defaults. The node state stores the full effective selection deliberately. That makes refresh/restart recovery deterministic and lets a user explicitly remove a material that was selected during the earlier planning stage. The material records themselves remain in the material library; only IDs and lightweight binding options are persisted on the workflow node. """ base = inherited if isinstance(inherited, dict) else {} active_bindings = [ deepcopy(item) for item in state.get("active_bindings", []) if isinstance(item, dict) ] selected_material_ids = _unique_texts( state.get("selected_material_ids") if isinstance(state.get("selected_material_ids"), list) else [ ( item.get("material", {}).get("material_id") if isinstance(item.get("material"), dict) else item.get("material_id") ) for item in active_bindings ] ) material_prompts = _unique_texts( ( item.get("material", {}).get("prompt") if isinstance(item.get("material"), dict) else item.get("prompt") ) for item in active_bindings ) reference_strengths = [ deepcopy(item.get("reference_strength")) for item in active_bindings if isinstance(item.get("reference_strength"), dict) ] temporary_references = [ deepcopy(item) for item in state.get("temporary_references", []) if isinstance(item, dict) ] return { **base, "schema_version": state.get("schema_version", NODE_MATERIAL_BINDING_SCHEMA_VERSION), "base_schema_version": base.get("schema_version", MATERIAL_BINDING_SCHEMA_VERSION), "reference_policy": deepcopy(REFERENCE_POLICY), "binding_source": "node_override", "target_node_id": node.node_id, "target_node_key": node.node_key, "target_node_title": node.title, "selected_material_ids": selected_material_ids, "has_references": bool(active_bindings or temporary_references), "active_bindings": active_bindings, "material_prompts": material_prompts, "prompt_context": ", ".join(material_prompts), "generation_params": { "reference_material_ids": selected_material_ids, "reference_prompts": material_prompts, "reference_strengths": reference_strengths, }, "temporary_references": temporary_references, "navigation_context": deepcopy(state.get("navigation_context")) if isinstance(state.get("navigation_context"), dict) else {}, "updated_at": state.get("updated_at"), "updated_by": state.get("updated_by"), "summary": { "rule_count": len(active_bindings), "active_rule_count": len(active_bindings), "has_references": bool(active_bindings or temporary_references), "temporary_reference_count": len(temporary_references), "target_node_keys": [canonical_gradual_node_key(node.node_key)], }, } def _extract_source_payload(payload: Any) -> dict[str, Any]: if not isinstance(payload, dict): return {} material_bindings = payload.get("material_bindings") if isinstance(material_bindings, dict) and isinstance(material_bindings.get("rules"), list): return material_bindings if isinstance(payload.get("rules"), list): return payload return {} def _normalize_rule(rule: dict[str, Any], ordinal: int) -> dict[str, Any]: material_id = _optional_text(rule.get("material_id")) material_prompt = _optional_text(rule.get("material_prompt")) category = _optional_text(rule.get("category")) or "other" target_stages = _target_stages(rule.get("bind_to_stages")) target_node_keys = _unique_texts( node_key for stage in target_stages for node_key in STAGE_NODE_KEYS.get(stage["stage_id"], ()) ) strength_label = _optional_text(rule.get("reference_strength")) or "medium" strength_key, strength_weight = STRENGTHS.get(strength_label.lower(), STRENGTHS.get(strength_label, ("medium", 0.55))) use_reference = bool(material_id or material_prompt) return { "id": _optional_text(rule.get("id")) or f"material_binding_{ordinal:02d}", "category": category, "use_reference": use_reference, "required": bool(rule.get("required")), "status": _optional_text(rule.get("status")) or ("ready" if use_reference else "pending"), "conflict": _optional_text(rule.get("conflict")), "material": { "material_id": material_id, "label": _optional_text(rule.get("material_label")), "group": _optional_text(rule.get("material_group")), "prompt": material_prompt, "colors": _string_list(rule.get("material_colors")), }, "target_stages": target_stages, "target_node_keys": target_node_keys, "inheritance_rule": _optional_text(rule.get("inheritance_rule")) or "", "reference_strength": { "label": strength_label, "key": strength_key, "weight": strength_weight, }, "generation_params": { "reference_policy": "explicit_only" if use_reference else "do_not_use_reference", "reference_strength": strength_key if use_reference else "none", "reference_weight": strength_weight if use_reference else 0, }, "expand_to_nodes_later": True, } def _validated_normalized_rule(rule: Any, ordinal: int) -> dict[str, Any]: """Check one rule that claims to be normalized already, and re-canonicalize it. A missing field is tolerated and defaulted: stored documents predate some of the keys below, and a read must not break on them. A field that is *present with the wrong shape* is rejected instead, because the normalizer can never produce that -- it only appears when the payload was hand-crafted against the version marker. """ field = f"material_bindings.rules[{ordinal - 1}]" if not isinstance(rule, dict): raise _binding_error(field, "素材绑定规则必须是对象", {"actual_type": type(rule).__name__}) material = rule.get("material") if material is None: material = {} if not isinstance(material, dict): raise _binding_error( f"{field}.material", "素材绑定规则的 material 必须是对象", {"actual_type": type(material).__name__}, ) material_id = _checked_text(material.get("material_id"), f"{field}.material.material_id") material_prompt = _checked_text(material.get("prompt"), f"{field}.material.prompt") use_reference = rule.get("use_reference") if use_reference is None: use_reference = bool(material_id or material_prompt) elif not isinstance(use_reference, bool): raise _binding_error( f"{field}.use_reference", "素材绑定规则的 use_reference 必须是布尔值", {"actual_type": type(use_reference).__name__}, ) elif use_reference and not (material_id or material_prompt): # ``explicit_only`` means a reference exists only when a material or a # prompt backs it; a bare flag would enable an empty reference. raise _binding_error( f"{field}.use_reference", "启用参考的素材绑定规则必须提供素材或提示词", {"material_id": material_id, "prompt": material_prompt}, ) generation_params = rule.get("generation_params") if generation_params is not None and not isinstance(generation_params, dict): raise _binding_error( f"{field}.generation_params", "素材绑定规则的 generation_params 必须是对象", {"actual_type": type(generation_params).__name__}, ) strength = _checked_reference_strength(rule.get("reference_strength"), f"{field}.reference_strength") target_stages = _checked_target_stages(rule.get("target_stages"), f"{field}.target_stages") target_node_keys = _checked_text_list(rule.get("target_node_keys"), f"{field}.target_node_keys") if not target_node_keys: target_node_keys = _unique_texts( node_key for stage in target_stages for node_key in STAGE_NODE_KEYS.get(stage["stage_id"], ()) ) return { **deepcopy(rule), "id": _checked_text(rule.get("id"), f"{field}.id") or f"material_binding_{ordinal:02d}", "category": _checked_text(rule.get("category"), f"{field}.category") or "other", "use_reference": use_reference, "required": bool(rule.get("required")), "status": _checked_text(rule.get("status"), f"{field}.status") or ("ready" if use_reference else "pending"), "conflict": _checked_text(rule.get("conflict"), f"{field}.conflict"), "material": { **deepcopy(material), "material_id": material_id, "label": _checked_text(material.get("label"), f"{field}.material.label"), "group": _checked_text(material.get("group"), f"{field}.material.group"), "prompt": material_prompt, "colors": _checked_text_list(material.get("colors"), f"{field}.material.colors"), }, "target_stages": target_stages, "target_node_keys": target_node_keys, "inheritance_rule": _checked_text(rule.get("inheritance_rule"), f"{field}.inheritance_rule") or "", "reference_strength": strength, "generation_params": { "reference_policy": "explicit_only" if use_reference else "do_not_use_reference", "reference_strength": strength["key"] if use_reference else "none", "reference_weight": strength["weight"] if use_reference else 0, }, "expand_to_nodes_later": True, } def _checked_text(value: Any, field: str) -> str | None: if value is None: return None if not isinstance(value, str): raise _binding_error(field, "素材绑定字段必须是文本", {"actual_type": type(value).__name__}) return value.strip() or None def _checked_text_list(value: Any, field: str) -> list[str]: if value is None: return [] if not isinstance(value, list) or any(not isinstance(item, str) for item in value): raise _binding_error(field, "素材绑定字段必须是文本列表", {"actual_type": type(value).__name__}) return _unique_texts(value) def _checked_target_stages(value: Any, field: str) -> list[dict[str, str]]: if value is None: return [] if not isinstance(value, list): raise _binding_error(field, "素材绑定字段必须是阶段列表", {"actual_type": type(value).__name__}) stages: list[dict[str, str]] = [] for index, item in enumerate(value): if not isinstance(item, dict): raise _binding_error( f"{field}[{index}]", "素材绑定阶段必须是对象", {"actual_type": type(item).__name__}, ) stage_id = _checked_text(item.get("stage_id"), f"{field}[{index}].stage_id") if not stage_id: raise _binding_error(f"{field}[{index}].stage_id", "素材绑定阶段缺少 stage_id", {}) stage = { "stage_id": stage_id, "stage_title": _checked_text(item.get("stage_title"), f"{field}[{index}].stage_title") or stage_id, } if stage not in stages: stages.append(stage) return stages def _checked_reference_strength(value: Any, field: str) -> dict[str, Any]: if value is None: return {"label": "medium", "key": "medium", "weight": 0.55} if not isinstance(value, dict): raise _binding_error(field, "素材绑定强度必须是对象", {"actual_type": type(value).__name__}) label = _checked_text(value.get("label"), f"{field}.label") or "medium" key_text = _checked_text(value.get("key"), f"{field}.key") or label strength_key, default_weight = STRENGTHS.get(key_text.lower(), STRENGTHS.get(key_text, ("medium", 0.55))) weight = value.get("weight", default_weight) if isinstance(weight, bool) or not isinstance(weight, (int, float)): raise _binding_error(f"{field}.weight", "素材绑定强度权重必须是数值", {"actual_type": type(weight).__name__}) return {"label": label, "key": strength_key, "weight": min(max(float(weight), 0.0), 1.0)} def _binding_error(field: str, message: str, details: dict[str, Any]) -> ApiError: return ApiError(ErrorCode.VALIDATION_FAILED, message, {"field": field, **details}) def _target_stages(value: Any) -> list[dict[str, str]]: if not isinstance(value, list): return [] stages: list[dict[str, str]] = [] for item in value: if not isinstance(item, dict): continue stage_id = _optional_text(item.get("stage_id") or item.get("id")) if not stage_id: continue stage = { "stage_id": stage_id, "stage_title": _optional_text(item.get("stage_title") or item.get("title")) or stage_id, } if stage not in stages: stages.append(stage) return stages def _index_by_stage(rules: list[dict[str, Any]]) -> dict[str, dict[str, Any]]: result: dict[str, dict[str, Any]] = {} for rule in rules: for stage in rule["target_stages"]: stage_id = stage["stage_id"] bucket = result.setdefault( stage_id, { "stage_id": stage_id, "stage_title": stage["stage_title"], "active_bindings": [], "material_prompts": [], }, ) bucket["active_bindings"].append(rule) if rule["material"]["prompt"]: bucket["material_prompts"].append(rule["material"]["prompt"]) return result def _index_by_node_key(rules: list[dict[str, Any]]) -> dict[str, list[dict[str, Any]]]: result: dict[str, list[dict[str, Any]]] = {} for rule in rules: for node_key in rule["target_node_keys"]: result.setdefault(canonical_gradual_node_key(node_key), []).append(rule) return result def _index_by_node_id( rules: list[dict[str, Any]], workflow_nodes: list[WorkflowNode], ) -> dict[str, dict[str, Any]]: by_node_key = _index_by_node_key(rules) result: dict[str, dict[str, Any]] = {} for node in workflow_nodes: canonical_key = canonical_gradual_node_key(node.node_key) active_rules = by_node_key.get(canonical_key) if active_rules: result[node.node_id] = _node_view(active_rules, node.node_id, canonical_key, node.title) return result def _node_view( active_rules: list[dict[str, Any]], node_id: str | None, node_key: str, title: str, ) -> dict[str, Any]: prompts = [rule["material"]["prompt"] for rule in active_rules if rule["material"]["prompt"]] return { "target_node_id": node_id, "target_node_key": node_key, "target_node_title": title, "reference_policy": deepcopy(REFERENCE_POLICY), "has_references": bool(active_rules), "active_bindings": deepcopy(active_rules), "material_prompts": prompts, "prompt_context": ", ".join(prompts), "generation_params": { "reference_material_ids": [ rule["material"]["material_id"] for rule in active_rules if rule["material"]["material_id"] ], "reference_prompts": prompts, "reference_strengths": [rule["reference_strength"] for rule in active_rules], }, } def _prompt_context(rules: list[dict[str, Any]]) -> list[dict[str, str]]: return [ { "category": rule["category"], "material_id": rule["material"]["material_id"] or "", "prompt": rule["material"]["prompt"] or "", "target_node_keys": ", ".join(rule["target_node_keys"]), } for rule in rules if rule["material"]["prompt"] ] def _string_list(value: Any) -> list[str]: if isinstance(value, str): return [value] if value.strip() else [] if not isinstance(value, list): return [] return _unique_texts(str(item).strip() for item in value if str(item or "").strip()) def _unique_texts(values: Any) -> list[str]: result: list[str] = [] for value in values: text = str(value or "").strip() if text and text not in result: result.append(text) return result