Canonical: https://nitride.xyz/docs/receiver/gap-detection

# Detecting gaps and duplicates

A receiver sees shreds in whatever order UDP delivers them. This page shows how to key them, which gaps you can see at receive time, why a gap there does not prove a loss, and what to count.

Start by giving every shred a key: its slot, its index and whether it is a data or a coding shred. Every duplicate check and gap count on this page builds on that key. The offsets come from [parsing the shred header](https://nitride.xyz/docs/shreds/parse-header), and this page is part of the [Nitride.xyz docs](https://nitride.xyz/docs).

## How do I key each shred?
Read three fields from the common header and one bit pattern from the variant byte:

- slot: bytes 65 to 72, u64 little-endian;
- index: bytes 73 to 76, u32;
- FEC set index: bytes 79 to 82, u32;
- type: the high nibble of byte 64, `0x6` or `0x7` for coding and `0x9` or `0xB` for data. Legacy and unchained variants fall into the tracker's `unknown` count; [parsing the shred header](https://nitride.xyz/docs/shreds/parse-header) explains why current Agave rejects them.

Data and coding shreds count their index separately, and both counters restart at zero in each slot. Data shred 40 and coding shred 40 of the same slot are two different shreds, so the type belongs in the key. Agave's own `ShredId` is the same triple.

## What counts as a duplicate?
A duplicate is a second shred with a key you already hold. Keep a short hash of the payload next to each key, then sort repeats into two counters:

- **identical**: the bytes match. This is normal on a network and costs you nothing but a lookup.
- **conflicting**: same key, different bytes. That can mean a corrupted packet, or a leader that produced two versions of the slot. Count it and log the slot.

One exception: resigned shreds, from the last erasure batch of a slot, end with a 64-byte retransmitter signature that each forwarding node writes again. Two honest copies can differ there. Agave's duplicate check skips those 64 bytes, and yours should too.

## Which gaps can a receiver see?
Only data shred gaps are worth tracking, and only within a slot:

- **Within the slot.** Data indices run from 0 with no holes. Once you hold the shred flagged `LAST_SHRED_IN_SLOT` (flags byte 85, `flags & 0xC0 == 0xC0`), you know the slot's last index, and every index below it that you lack is missing.
- **Within an FEC set.** Each erasure batch is 32 data and 32 coding shreds in the current Agave source, and the FEC set index is the first data index of the batch. A batch can be rebuilt once any 32 of its 64 shreds are present.

Two gaps stay invisible. If the last shred of a slot is lost, you cannot tell how many came after the highest one you hold. If a whole batch is lost, data and coding together, nothing in hand names it. Count slots that close without a `LAST_SHRED_IN_SLOT` shred as their own metric. If you record the stream for later study, run the same counts over the capture; [backtesting with captured shreds](https://nitride.xyz/blog/backtesting-with-captured-shreds) shows how to record it.

## Why is a gap not proof of loss?
A missing index at receive time is a question, not an answer:

- **Coding shreds can rebuild it.** If the batch has 32 shreds of any kind, Reed-Solomon recovery restores the missing data shreds. See [recovering and decoding](https://nitride.xyz/docs/shreds/recover-and-decode).
- **It may arrive late.** UDP does not order packets. A shred can land after you first looked, so judge a slot only when you close it.
- **The slot may be skipped.** A leader can produce a partial slot, or none, and the cluster moves on. Missing shreds of a skipped slot were never part of the chain.

Validators fill real holes with the [repair protocol](https://nitride.xyz/learn/repair-protocol). A raw UDP feed has no retransmission, so your receiver's options are recovery from coding shreds and waiting.

## How do I keep memory bounded?
Hold state per slot and close slots that fall too far behind the highest slot seen. When a slot closes, count its gaps and drop its state. Shreds that arrive for a closed slot go to a `late` counter and are dropped. The window is your choice: wider catches more late shreds, narrower uses less memory. With a fixed window, memory is bounded by the window times the shreds per slot.

## A tracker in Python
```python file="gaps.py"
import hashlib, struct
from collections import Counter

KEEP_SLOTS = 32   # slots kept behind the highest slot seen

class SlotState:
    def __init__(self):
        self.seen = {}            # (kind, index) -> payload digest
        self.data = set()         # data indices received
        self.fec = Counter()      # fec_set_index -> data + coding shreds received
        self.fec_need = {}        # fec_set_index -> num_data_shreds (from a coding header)
        self.last_index = None    # index of the LAST_IN_SLOT data shred

class GapTracker:
    def __init__(self):
        self.slots, self.top = {}, 0
        self.stats = Counter()

    def add(self, pkt):
        variant = pkt[64] & 0xF0
        if variant not in (0x60, 0x70, 0x90, 0xB0):
            self.stats["unknown"] += 1
            return
        kind = "data" if variant >= 0x90 else "code"
        slot, index, _, fec = struct.unpack_from("<QIHI", pkt, 65)
        if slot + KEEP_SLOTS < self.top:
            self.stats["late_after_evict"] += 1
            return
        st = self.slots.setdefault(slot, SlotState())
        # ignore the retransmitter signature, which differs from hop to hop
        body = pkt[:-64] if variant in (0x70, 0xB0) else pkt
        digest = hashlib.blake2b(body, digest_size=16).digest()
        key = (kind, index)
        if key in st.seen:
            same = st.seen[key] == digest
            self.stats["duplicate" if same else "conflicting"] += 1
            return
        st.seen[key] = digest
        st.fec[fec] += 1
        self.stats[kind] += 1
        if kind == "data":
            st.data.add(index)
            if pkt[85] & 0xC0 == 0xC0:
                st.last_index = index
        else:
            st.fec_need[fec] = struct.unpack_from("<H", pkt, 83)[0]
        if slot > self.top:
            self.top = slot
            for old in [s for s in self.slots if s + KEEP_SLOTS < slot]:
                self.close(old)

    def close(self, slot):
        st = self.slots.pop(slot)
        if st.last_index is None:
            self.stats["slot_no_last"] += 1
            end = max(st.data, default=-1)
        else:
            end = st.last_index
        missing = [i for i in range(end + 1) if i not in st.data]
        self.stats["data_missing"] += len(missing)
        for fec in {i - i % 32 for i in missing}:  # fixed 32-shred sets; see note
            if st.fec[fec] < st.fec_need.get(fec, 32):
                self.stats["fec_unrecoverable"] += 1
        return missing

    def flush(self):
        for slot in sorted(self.slots):
            self.close(slot)
```

Call `add` with each datagram that passed your header checks, and read `stats` on a timer. The line marked "see note" maps a missing index to its batch by rounding down to a multiple of 32, which holds while every batch has 32 data shreds. If that rule changes, take the batch from the FEC set index of the shreds around the hole instead.

We ran it on 127.0.0.1 with 40 crafted slots of 64 data and 64 coding shreds each, sent in a locally shuffled order through a UDP socket. One slot lost 6 data shreds, another lost its whole second batch, and we added an exact repeat, a same-key packet with one changed byte, and a resigned shred sent twice with different last 64 bytes. The output:

```text
5054 datagrams {'data': 2523, 'code': 2528, 'duplicate': 2, 'conflicting': 1, 'data_missing': 6, 'slot_no_last': 1}
```

The 6 missing shreds were recoverable, so `fec_unrecoverable` stayed at zero. The lost batch shows up only as `slot_no_last`, as described above.

## What should I count and alert on?
Count everything, alert on little:

- `data` and `code` per second: alert when either drops to zero for longer than a few slots.
- `fec_unrecoverable` per slot: the number that means data you cannot rebuild. Alert on a sustained rate, not a single slot.
- `slot_no_last`: watch its trend next to `fec_unrecoverable`.
- `conflicting`: rare; log the slot for a look.
- `late_after_evict`: if it climbs, widen the window.
- Kernel drops: `UdpRcvbufErrors` counts datagrams the kernel discarded before your program saw them. Read it with `nstat` and fix it with a bigger receive buffer, as shown in [Linux sockets and buffers](https://nitride.xyz/docs/receiver/linux-sockets).

Raw `data_missing` is a poor alert on its own, because most of it is recovered or explained by skipped slots.
