# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-treat-a-forget-as-idempotent-when-retention-scopes-overlap-across-tenant-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-treat-a-forget-as-idempotent-when-retention-scopes-overlap-across-tenant-boundaries.warrant.json
# Markdown SHA-256:   e358140d12bd3b917d2f43406477f85b55d27d2401d43eefdbbb4e04d0a6926c
# Code AST SHA-256:   00da7c71b0007a4358b62a5d219de68894e77a3a6aa210bd3d427e8c9ef71ab8
# Verified Classes:   IncompleteForgetError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class IncompleteForgetError(RuntimeError):
    """Raised when a forget request short-circuits on a visibility-only
    tombstone while co-scoped records still retain the subject's payload."""
    pass


def forget_subject(store, subject_id, *, acknowledge_visibility_only=False):
    tombstone = store.get_tombstone(subject_id)

    if tombstone is not None:
        # Idempotence is only valid if existence was actually erased.
        if tombstone.existence_erased:
            return {"status": "already_forgotten", "subject": subject_id}

        residual = store.co_scoped_records(subject_id)  # records with scope \ {subject}
        if residual and not acknowledge_visibility_only:
            raise IncompleteForgetError(
                f"forget({subject_id}) short-circuited on a visibility-only "
                f"tombstone, but {len(residual)} co-scoped record(s) still "
                f"retain the subject's payload under residual scopes "
                f"{sorted({s for r in residual for s in r.retention_scope if s != subject_id})}. "
                f"Complete excision or pass acknowledge_visibility_only=True."
            )
        if residual:
            # Caller explicitly accepted a visibility-only forget; record the exception.
            store.mark_residual_scopes(subject_id, [r.retention_scope for r in residual])
            return {"status": "visibility_only_forget", "residual": len(residual)}

    # First forget (or re-entry): perform real excision.
    excised = 0
    for record in store.co_scoped_records(subject_id):
        store.excise_and_rewrite(record, remove_subject=subject_id)
        excised += 1
    store.write_tombstone(subject_id, existence_erased=True)
    return {"status": "existence_erased", "excised": excised}
