# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-consolidate-a-contradicting-episodic-memory-before-the-decay-horizon-is-reached.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-consolidate-a-contradicting-episodic-memory-before-the-decay-horizon-is-reached.warrant.json
# Markdown SHA-256:   b7c0e2dd583f3ed61ff7f1d3feb72a6e100995156828e8bc46c9d778aee14f99
# Code AST SHA-256:   abe1dfd9f50d5a5b53d22a812570c001f12d2da7c60bc1840e291c42a6e58809
# Verified Classes:   ConsolidationInvariantError, Incumbent, Candidate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

RETENTION_FLOOR = 0.50


class ConsolidationInvariantError(RuntimeError):
    """Raised when a consolidation transition would violate the retention-floor invariant."""
    pass


class Incumbent:
    def __init__(self, value, decay_weight, corroboration_trace_ids):
        self.value = value
        self.decay_weight = decay_weight
        self.corroboration_trace_ids = list(corroboration_trace_ids)


class Candidate:
    def __init__(self, value, trace_id, independent_of_incumbent):
        self.value = value
        self.trace_id = trace_id
        self.independent_of_incumbent = independent_of_incumbent


def resolve_contradiction(incumbent, candidate, open_quarantine_trace_ids):
    if candidate.value == incumbent.value:
        return ("CORROBORATE", incumbent)

    if incumbent.decay_weight >= RETENTION_FLOOR:
        # Incumbent is still load-bearing. A single contradictor may not evict it.
        if not candidate.independent_of_incumbent:
            raise ConsolidationInvariantError(
                f"candidate trace {candidate.trace_id} is correlated with incumbent "
                f"provenance; cannot count as an independent contradictor"
            )
        if len(open_quarantine_trace_ids) >= 1:
            # Second independent contradictor: eviction justified, archive incumbent.
            return ("REPLACE_ARCHIVE", incumbent)
        return ("QUARANTINE", incumbent)

    # Incumbent has decayed below floor: replace, but archive (never overwrite in place).
    return ("REPLACE_ARCHIVE", incumbent)


def consolidate(incumbent, candidate, open_quarantine_trace_ids):
    action, _ = resolve_contradiction(incumbent, candidate, open_quarantine_trace_ids)
    if action == "QUARANTINE":
        # Invariant guard: never mutate incumbent state on a quarantine path.
        if incumbent.value != incumbent.value:
            raise ConsolidationInvariantError("incumbent mutated during quarantine")
    return action
