# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-scope-narrowing-collapse-when-a-delegated-consent-chain-re-signs-its-own-attenuation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-scope-narrowing-collapse-when-a-delegated-consent-chain-re-signs-its-own-attenuation.warrant.json
# Markdown SHA-256:   b6daaa1520f6b859563151bf6d5cab81e7cc23c611b1cffc492f36c85824b7c1
# Code AST SHA-256:   67f2d6631b63c005be12d39b6cc8032827fd47282a182c40975428ac936249a8
# Verified Classes:   ScopeAttenuationError, DbQueryScope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class ScopeAttenuationError(RuntimeError):
    """Raised when a delegated scope is not provably narrower than its parent."""
    pass

@dataclass(frozen=True)
class DbQueryScope:
    table: str
    max_rows: Optional[int]        # None == unbounded (+inf); must be explicit, never implied by omission
    columns: frozenset[str]        # allow-list
    deny_columns: frozenset[str] = field(default_factory=frozenset)

def _rows_le(child: Optional[int], parent: Optional[int]) -> bool:
    # None is +inf. Child bound must be <= parent bound.
    if parent is None:
        return True
    if child is None:
        return False
    return child <= parent

def verify_attenuation(child: DbQueryScope, parent: DbQueryScope) -> None:
    if child.table != parent.table:
        raise ScopeAttenuationError(
            f"table mismatch: child={child.table!r} parent={parent.table!r}; "
            "different resource is a sibling grant, not attenuation"
        )
    if not _rows_le(child.max_rows, parent.max_rows):
        raise ScopeAttenuationError(
            f"row bound widened: child={child.max_rows} parent={parent.max_rows}"
        )
    if not child.columns.issubset(parent.columns):
        widened = child.columns - parent.columns
        raise ScopeAttenuationError(f"column allow-list widened by {sorted(widened)}")
    if not child.deny_columns.issuperset(parent.deny_columns):
        dropped = parent.deny_columns - child.deny_columns
        raise ScopeAttenuationError(f"deny-list narrowed, dropping {sorted(dropped)}")

def re_sign(parent: DbQueryScope, child: DbQueryScope) -> DbQueryScope:
    # Fail closed: any undecidable or lossy field must abort re-signing.
    if parent.max_rows is None and child.max_rows is not None:
        # parent unbounded is legal, but record it explicitly downstream
        pass
    verify_attenuation(child, parent)
    return child
