# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-scope-leakage-when-a-planner-reuses-a-privileged-subplan-across-a-provenance-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-scope-leakage-when-a-planner-reuses-a-privileged-subplan-across-a-provenance-boundary.warrant.json
# Markdown SHA-256:   48edfaa65548b4d3e5b0ba72dcf355e6e7f13adfc1cbaacc7aaa789ccf876f56
# Code AST SHA-256:   ef306adf94c1406f0f4a18d23fa27b6f41548f06d7be1a0c04aa81142220f87e
# Verified Classes:   Taint, Leaf, Subplan, TaintScopeLeakError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

@dataclass(frozen=True)
class Taint:
    labels: FrozenSet[str]
    def __le__(self, other: "Taint") -> bool:
        return self.labels <= other.labels

@dataclass(frozen=True)
class Leaf:
    tool: str
    scope: FrozenSet[str]

@dataclass(frozen=True)
class Subplan:
    signature: str
    leaves: tuple
    minted_under: Taint

class TaintScopeLeakError(RuntimeError):
    """Raised when a spliced subplan's leaf scopes exceed the tainted parent's grant."""

def authorized_scopes(taint: Taint) -> FrozenSet[str]:
    # Untrusted contexts are read-only; clean contexts inherit full grant.
    if "external:untrusted" in taint.labels:
        return frozenset({"finance:read"})
    return frozenset({"finance:read", "finance:write"})

def splice_subplan(parent_taint: Taint, subplan: Subplan) -> tuple:
    """Splice a cached subplan under a parent frame, enforcing downward scope narrowing.

    Invariant: authorization_scope(leaf) subset-of authorized_scopes(parent_taint)
    for every leaf. The taint-ordering check (parent >= child) is necessary but
    NOT sufficient and is deliberately not used as the gate here.
    """
    grant = authorized_scopes(parent_taint)
    for leaf in subplan.leaves:
        if not leaf.scope <= grant:
            raise TaintScopeLeakError(
                f"subplan {subplan.signature!r} leaf {leaf.tool!r} "
                f"requires scope {sorted(leaf.scope)} but tainted parent "
                f"{sorted(parent_taint.labels)} grants only {sorted(grant)}; "
                f"re-derive under current taint context"
            )
    return subplan.leaves

# Reproduction of the observed seam.
clean = Taint(frozenset())
untrusted = Taint(frozenset({"external:untrusted"}))
cached = Subplan(
    signature="reconcile:*:ledger",
    leaves=(Leaf("read_ledger", frozenset({"finance:read"})),
            Leaf("write_reconciliation", frozenset({"finance:write"}))),
    minted_under=clean,
)

# Clean parent: splice is legal.
splice_subplan(clean, cached)

# Tainted parent selecting the same cached subplan: must fail closed.
try:
    splice_subplan(untrusted, cached)
except TaintScopeLeakError:
    pass  # expected: privilege escalation via cache is blocked at the seam
