# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-acknowledge-a-committed-task-it-never-durably-recorded-quorum-signed-commitments-vs-episodic-memory-divergence-in-byzantine-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-acknowledge-a-committed-task-it-never-durably-recorded-quorum-signed-commitments-vs-episodic-memory-divergence-in-byzantine-agent.warrant.json
# Markdown SHA-256:   ba09fd177dd843c8027a719c0a6e146e25446b2999762f6848bfe8986b97f069
# Code AST SHA-256:   d66ca62d3d2602a0a569884d4a09af8d70feb08044d6c95ee61d20d627bff03c
# Verified Classes:   CommitmentAcknowledgmentSplit
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CommitmentAcknowledgmentSplit(RuntimeError):
    """Raised when a quorum-committed task's execution intent is not
    durably attested, or when a coordinator attempts to override a
    committed record using a single-replica self-report."""
    pass


QUORUM = 5  # ⌈2n/3⌉+1 for n=6, f=1


def reconcile_shard_status(ledger_record: dict, self_report: dict,
                           read_quorum_attestations: list[dict]) -> str:
    """Resolve a shard's execution status at the coordinator boundary.

    ledger_record: quorum-committed task record (authoritative for commitment).
    self_report:   the executing agent's own claim about its intent/status.
    read_quorum_attestations: fresh signatures from >= QUORUM replicas
                   attesting to the shard's execution-status record.
    """
    if ledger_record.get("status") != "COMMITTED":
        raise CommitmentAcknowledgmentSplit(
            "reconcile called on non-committed task; upstream bug"
        )

    # Invariant 1: intent must be durably attested before vote finality.
    if not ledger_record.get("execution_intent_attested"):
        raise CommitmentAcknowledgmentSplit(
            f"task {ledger_record['id']} committed without durable "
            "execution-intent attestation; commitment-acknowledgment "
            "split is possible on any replica restart"
        )

    # Invariant 2: self-report is a single-replica read; never trust it
    # to override the ledger without a read-quorum.
    if self_report.get("status") == "NOT_STARTED" and \
            ledger_record.get("assigned_shard") == self_report.get("shard"):
        valid = [a for a in read_quorum_attestations if a.get("valid")]
        if len(valid) < QUORUM:
            raise CommitmentAcknowledgmentSplit(
                f"cannot override committed assignment of "
                f"{self_report['shard']} using single-replica self-report; "
                f"read-quorum has {len(valid)}/{QUORUM} valid attestations — "
                "re-dispatch here would risk double-execution"
            )
        # Read-quorum confirms unexecuted: safe to re-dispatch.
        return "REDISPATCH_SAFE"

    return "IN_FLIGHT"
