# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-derive-taint-when-a-provenance-label-survives-a-tool-call-but-the-payload-underneath-it-is-re-serialized.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-derive-taint-when-a-provenance-label-survives-a-tool-call-but-the-payload-underneath-it-is-re-serialized.warrant.json
# Markdown SHA-256:   437e97a494d7933b60524d6ae62505017c0443081ebee69de60a296e1935bf72
# Code AST SHA-256:   a283936d08fed7d5bb79ca8aef797ce822feb59ac32a5dcbc70c583006c8d6eb
# Verified Classes:   TaintRenderParityError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintRenderParityError(RuntimeError):
    """Raised when a provenance label's coverage does not match the bytes a gate authorized."""
    pass


def assert_render_parity(displayed: bytes, model_input: bytes, label_coverage: set[str]) -> None:
    # The gate authorized `displayed`; the model will consume `model_input`.
    # A label is valid only if it covers every field that reaches the model.
    if not model_input.startswith(displayed):
        raise TaintRenderParityError(
            f"gate displayed {len(displayed)}B but model reads {len(model_input)}B; "
            "reviewer authorized a projection, not the consumed object"
        )
    unlabeled_tail = model_input[len(displayed):]
    if unlabeled_tail and not label_coverage:
        raise TaintRenderParityError(
            f"{len(unlabeled_tail)}B of model input lie outside any labeled span; "
            "re-serialization synthesized unlabeled bytes"
        )


def rederive_label_on_transform(span_id: str, emitted_fields: dict[str, bytes],
                                source_taint: set[str]) -> dict[str, set[str]]:
    # Labels are a function of emitted bytes, not of span lineage.
    labels: dict[str, set[str]] = {}
    for field, payload in emitted_fields.items():
        if not payload:
            continue
        # Every emitted field derived from tainted input inherits the taint;
        # no field may inherit a label by span_id alone.
        labels[field] = set(source_taint)
    if not labels:
        raise TaintRenderParityError(
            f"transform on {span_id} emitted no labeled fields; "
            "empty envelope cannot carry provenance and must not be trusted"
        )
    return labels
