ouroboros-consensus
Safe HaskellNone
LanguageHaskell2010

Ouroboros.Consensus.MiniProtocol.LeiosFetch.Decision

Description

What the node's LeiosFetch clients request, decided for all of them at once: the node-wide state of what is outstanding, and the pure decision that assigns the peers' offers to requests.

Synopsis

Requests

data LeiosBlockRequest Source #

A request for an endorser block's body.

Constructors

MkLeiosBlockRequest 

Fields

data LeiosBlockTxsRequest Source #

A request for some of an EB's txs: its point and the LeiosJobs it covers, keyed by job id (so a request can't list a job twice), each with its full commitment. Everything needed to validate the response is carried here, so the reply handler needs no lookup into the (body-less) job pool -- and a redundant response for a job that has since completed still validates. On the wire only the offset bitmap goes to the peer; it is derived from the union of the jobs' offsets (see offsetsToBitmap), not stored.

Offers

data OfferedHalves Source #

Which halves of an endorser block one peer has offered at one point. A peer that offered neither has no offer there.

The two LeiosNotify offers are independent messages: either can arrive first, or alone. A CertRB roll-forward makes both at once.

The body offer carries a size and the closure offer does not, and that asymmetry is not an oversight. We hold nothing to size a body request by, so the peer's claim is both what the request asks for and what it spends against that peer's byte budget. Closure jobs carry their own byte counts, taken from the body we already hold by the time assignClosure runs, so there is nothing there for a peer to claim.

The size the peer offered the body at is its own claim, and the only size that decides anything: no announcement gets a say (see assignBody), and what the endorser block really weighs is settled by hashing the bytes that arrive.

Offering one point twice costs the peer its connection, but one hash at two points does not: those are separate entries, each needing its own announcement, and nothing here arbitrates between the sizes they name.

TODO disconnect a peer that ever offers one EndorserBlockHash at two sizes, whichever messages the two arrived on. That is proof it is lying, and today we keep both and carry on.

Constructors

OfferedBody !BytesSize

The body, at this size

OfferedClosure

The closure

OfferedBodyAndClosure !BytesSize

Both, the body at this size

Instances

Instances details
Semigroup OfferedHalves Source #

What either offered. Of two body sizes, the leftmost wins, which for insertWith is the newer offer's, and a peer that makes that choice matter has already lost our trust.

Instance details

Defined in Ouroboros.Consensus.MiniProtocol.LeiosFetch.Decision

Eq OfferedHalves Source # 
Instance details

Defined in Ouroboros.Consensus.MiniProtocol.LeiosFetch.Decision

Show OfferedHalves Source # 
Instance details

Defined in Ouroboros.Consensus.MiniProtocol.LeiosFetch.Decision

data PeerOffer Source #

What one peer has offered for one endorser block point.

Constructors

MkPeerOffer 

Fields

Instances

Instances details
Semigroup PeerOffer Source #

Each field on its own terms (see OfferedHalves). The bound is not a claim of the peer's but a value we computed, so the two sides agree whenever both have one and either will do.

Instance details

Defined in Ouroboros.Consensus.MiniProtocol.LeiosFetch.Decision

Eq PeerOffer Source # 
Instance details

Defined in Ouroboros.Consensus.MiniProtocol.LeiosFetch.Decision

Methods

(==) ∷ PeerOffer → PeerOffer → Bool #

(/=) ∷ PeerOffer → PeerOffer → Bool #

Show PeerOffer Source # 
Instance details

Defined in Ouroboros.Consensus.MiniProtocol.LeiosFetch.Decision

Methods

showsPrec ∷ Int → PeerOffer → ShowS #

show ∷ PeerOffer → String #

showList ∷ [PeerOffer] → ShowS #

data OfferPrune Source #

What of a peer's offer of a point the decision logic found can no longer help.

The decision logic reads the peers' offers in one transaction and prunes them in a later one, so meanwhile a peer's closure offer may merge into its body offer. Pruning the whole offer would lose that closure offer, so PruneOffer is decided only where no closure offer could help either.

Constructors

PruneOffer

The whole offer.

PruneOfferedBody

Its body half, and the whole offer unless it offers the closure: the body is held, or was requested of this peer, which is asked for it at most once.

Outstanding state

data LeiosOutstanding peer Source #

Main data structure used in the Leios fetching logic.

Tracks both EB-level state (what EBs we have/need) and TX-level state (what TXs we need for each EB), along with request tracking for bandwidth management.

Constructors

MkLeiosOutstanding 

Fields

  • ebState ∷ !(Map LeiosPoint EbState)

    Per-point state for every endorser block point this node is tracking. Four things add an entry: the announcement that takes an election's focus, the node's own forge (holdForgedEb), a verified certificate (trackCertifiedEb), and the start-up seeding (initializeLeiosOutstanding) of the endorser blocks whose closures the LeiosDb already holds (merely to avoid refetching them). An offer never does, and is only ever acted on for a point already here.

    Each point is fetched on its own, even when another point names the same endorser block, so the ledger's bounds an entry is held to never change: they are those of its slot.

  • elFocus ∷ !(Map ElectionId EndorserBlockHash)

    The endorser block each election is fetching.

    Two activities decide it. Processing an announcement focuses an election that has no focus yet, and nothing more (focusElectionIfUnfocused). Processing a certificate overrides whatever is there (focusCertifiedEb) --- the CertRB itself, when its certificate is verified, not its header, which only records an offer. Pruning is the only other writer, and it just drops the elections below the immutable tip.

    A point is focused when an election in its slot is fetching its endorser block (isFocusedPoint). Unless a point is focused, the decision logic asks no peer for anything about it: neither its body nor any of its closure's jobs, since this is what filters a peer's offers before either is considered. A body we already hold stays held and its job pool stays as it is, so an election that focuses it later resumes rather than restarts.

  • outstandingPrunedSlot ∷ !SlotNo

    The slot this whole LeiosOutstanding has most recently been pruned up to: pruneOutstandingToImmTip moves it in the same record it prunes ebState and elFocus in, so it says how far both of them have got.

    Used to robustly prevent re-inserting what has already been pruned out.

  • requestedEbPeers ∷ !(Map LeiosPoint (Set peer))

    Which peers we've requested each point's body from

  • requestedEbsPerPeer ∷ !(Map peer (NESet LeiosPoint))

    The inverse of requestedEbPeers: the points whose body each peer has been requested, so that cancelling a peer's requests touches only those

  • requestedBytesSizePerPeer ∷ !(Map peer BytesSize)

    Running total of bytes requested from each peer. This is the only outstanding-byte limit: there is no global cap (the global bound falls out as this per-peer cap times the peer count).

  • requestedJobsPerPeer ∷ !(Map peer (Map LeiosPoint NEIntSet))

    Per peer, per point, the job ids it currently has in flight -- for decrementing those multiplicities on disconnect

  • leiosFetchPrng ∷ !StdGen

    The LeiosFetch decision loop's own PRNG, threaded through each iteration. Used to shuffle which job is drawn when assigning tx-closure work to a peer (a uniform pick within the least-requested multiplicity bucket), so job ids aren't consumed in a fixed order. Seeded once at start-up.

data EbState Source #

Per-point state tracked in ebState

Constructors

MkEbState 

Fields

  • !(StrictMaybe RelativeTime)

    The wall-clock onset of the point's slot, if known. The acquisition traces subtract it from the arrival time, so they say how long after this point was announced we got it. It is SNothing when nothing supplied an onset, as for a verified certificate or the start-up seeding.

  • !EbFetchState

    The current progress of fetching it

Instances

Instances details
Eq EbState Source # 
Instance details

Defined in Ouroboros.Consensus.MiniProtocol.LeiosFetch.Decision

Methods

(==) ∷ EbState → EbState → Bool #

(/=) ∷ EbState → EbState → Bool #

Show EbState Source # 
Instance details

Defined in Ouroboros.Consensus.MiniProtocol.LeiosFetch.Decision

Methods

showsPrec ∷ Int → EbState → ShowS #

show ∷ EbState → String #

showList ∷ [EbState] → ShowS #

data EbFetchState Source #

Whether we hold an EB's body.

Constructors

NoBody

We've only ever received an announcement.

BodyAcquired !LeiosJobPool

The job pool: the jobs whose txs are not yet durably written.

A body too big for the point's bounds is held with an empty pool too. It is never written, and nothing more is fetched or emitted for it at this point.

The body itself is not retained -- it lives in the LeiosDb, and each job carries a JobCommitment sufficient to validate its response. Retaining up to ~10k bodies (each up to ~600 kB) would cost gigabytes.

TODO the LeiosJobPool could be an 'MVar m LeiosJobPool' for per-EB locking, at the cost of an m parameter on EbFetchState/EbState/LeiosOutstanding and a monadic body-acquire; deferred.

ebStateOnset ∷ EbState → StrictMaybe RelativeTime Source #

The recorded onset of the point's slot, if any (see MkEbState); the arrival handlers use it to report the EB's age on arrival.

emptyLeiosOutstanding ∷ StdGen → SlotNo → LeiosOutstanding peer Source #

The empty outstanding state, given the slot it has already been pruned up to. The caller supplies the immutable-tip slot at startup so that a body at or below it reads as too old from the outset (see outstandingPrunedSlot / pruneOutstandingToImmTip), and the seed for the decision loop's PRNG (see leiosFetchPrng).

initializeLeiosOutstanding ∷ StdGen → [LeiosPoint] → SlotNo → LeiosOutstanding peer Source #

Initialize the outstanding state

Its contents are only BodyAcquired emptyJobPool for the EBs the LeiosDb already holds in full: a complete tx closure whose announcer is no older than the immutable tip. Each is marked BodyAcquired with an empty job pool so we neither re-fetch nor re-process (eg emit AcquiredEb) an EB whose closure we already have at start-up time.

Everything else in the LeiosDb is deliberately ignored here, and it's safe to do so:

  • A merely body-held EB with a partial closure is not seeded: an empty pool would strand its missing txs. Left absent, it is re-derived from a fresh announcement/offer, and the redundant body re-fetch + re-insert is idempotent.
  • Complete closures at or below the immutable tip are already final; they would read as too old anyway, so there is nothing to track.

The announcements on the initially selected chain are likewise not replayed here, though those blocks never roll forward and so are never announced to us this run. Only two things list an endorser block to fetch --- the announcement that takes an election's focus, and focusCertifiedEb on a verified certificate --- and between them they reach every endorser block we could come to need. A CertRB on the initial chain has its endorser block already, since it could not have been selected otherwise; one that is not on the initial chain is re-fetched if some chain we would select needs it, and verifying its certificate then sets the focus and lists it.

The per-peer request-tracking fields must start empty regardless: there are no connections yet and nothing is in flight.

newLeiosJobPool ∷ LeiosFetchStaticEnv → IntMap (TxHash, BytesSize) → LeiosJobPool Source #

A pool of jobs to fetch these missing txs of an EB's closure, given as in mkJobPool.

acquireEbBody ∷ LeiosPoint → LeiosJobPool → LeiosOutstanding peer → LeiosOutstanding peer Source #

The body's LeiosDb write is durable, so record BodyAcquired with the pool of jobs the settled write still leaves to fetch.

There is no intermediate "write in flight" state. During the (brief, async) write window the entry is still NoBody, so a concurrent offer may redundantly re-fetch the body -- cheaper than tracking an in-flight state and reverting it on a lost write, which with the single writer cannot happen without bringing the node down anyway.

holdForgedEb Source #

Arguments

∷ ElectionId 
→ EndorserBlockHash 
→ BytesSize

the size of the body

→ LeiosOutstanding peer 
→ (LeiosOutstanding peer, [LeiosAcquisition]) 

The node's own forge produced the endorser block of this hash in this election, and its body and closure have been written, so hold it with no job left, and focus the election on it unless another endorser block took the focus first. Also returns the acquisitions not yet emitted at its point.

As for acquireEbBody, there is no intermediate state: until the writes land, a peer offering the same point (another leader of the slot built the same endorser block) may be fetched from redundantly.

recordReferencedPoint ∷ LeiosPoint → StrictMaybe RelativeTime → LeiosOutstanding peer → LeiosOutstanding peer Source #

Record that this point is referenced --- announced, or named by a verified certificate --- along with its slot's wall-clock onset if known. A reference that carries no onset (SNothing) never overrides one already recorded.

focusElectionIfUnfocused ∷ ElectionId → EndorserBlockHash → LeiosOutstanding peer → LeiosOutstanding peer Source #

Make this endorser block the one this election is fetching, unless the election is already fetching one.

The first announcement we see for an election wins, which is what an honest electee's single announcement gives; only a certificate (focusCertifiedEb) overrules it.

focusCertifiedEb ∷ ElectionId → EndorserBlockHash → LeiosOutstanding peer → LeiosOutstanding peer Source #

A verified certificate moves its election's focus onto the endorser block it names, and lists that body as one to fetch.

The endorser block this names may never have been listed. The announcement that took the election's focus listed its own; this one's may have lost that race, or may never have reached us --- and nothing lists it in the meantime, because an unverified claim must not be able to make us track an endorser block.

It does nothing for an election older than what has been pruned: its certificate may have been read before the pruning, and focusing it now would track what the pruning dropped.

trackCertifiedEb ∷ LeiosPoint → LeiosOutstanding peer → LeiosOutstanding peer Source #

Start tracking a certified endorser block, unless it is too old.

An ebState entry is what makes a body fetchable at all: the decision logic skips any offer of an endorser block it has no entry for. The announcement this certificate names may have no entry, in two ways. Its announcing block may have been on our selection since start-up, so its header never rolled forward and nothing announced it to us. Or it may have been a second announcement for an election already focused elsewhere, which is deliberately not tracked.

Already holding the body is not a special case: recordReferencedPoint leaves the fetch state alone, so nothing is re-fetched.

focusElection ∷ ElectionId → EndorserBlockHash → LeiosOutstanding peer → LeiosOutstanding peer Source #

Make this endorser block the one this election is fetching, whatever it was fetching before.

Whatever it was fetching stops being asked for, unless another election is also fetching it. Nothing else about that endorser block is disturbed: we keep the body if we acquired it, and we still take whatever was already requested for it, since those bytes are paid for either way.

NOTE One election, one certified endorser block --- which holds only while enough of the committee's weight is honest, since two valid certificates for one election means the committee equivocated. Should that ever happen, this is last-claim-wins: each certificate moves the focus, so it ends on whichever LeiosFetch learns of last, and the node can be left fetching the endorser block of one fork while the chain it would select needs the other, and it stays stuck there. The recourse is to restart the node and hope the certificates arrive in the other order, since this state is in memory only and the order they come back in is the network's to decide. We deliberately do not spend complexity on that case here, since it requires catastrophically buggy nodes and/or an amount of adversarial stake the protocol itself is not designed to resist.

isFocusedPoint ∷ LeiosPoint → LeiosOutstanding peer → Bool Source #

Whether some election is currently fetching this point: one in the point's slot that focuses its endorser block. ElectionId orders slot-first, so the elections of a slot are a range of elFocus. A slot has at most one election per leader of that slot, and rarely has more than one leader, so the range is short.

pruneOutstandingToImmTip ∷ SlotNo → LeiosOutstanding peer → LeiosOutstanding peer Source #

Prune LeiosOutstanding to the immutable tip.

LeiosPoint and ElectionId both order slot-first, so what is below the tip is a prefix of each map, dropped with dropWhileAntitone.

TODO still more it could prune (e.g. abandoned in-flight EB requests).

Settled requests

removePeerFromOutstanding ∷ Ord peer ⇒ peer → LeiosOutstanding peer → LeiosOutstanding peer Source #

Cancel all of a peer's outstanding fetch requests in bulk, e.g. when it disconnects: refund its share of the request budget, drop it from the per-EB body request set (requestedEbPeers), and -- via the per-peer requestedEbsPerPeer and requestedJobsPerPeer indices -- decrement the multiplicity of every job it had in flight, so those bodies and jobs become re-requestable from other peers.

refundEbRequest ∷ Ord peer ⇒ peer → LeiosPoint → BytesSize → LeiosOutstanding peer → LeiosOutstanding peer Source #

Reverse this peer's per-request accounting for a received EB body, but only if the peer is still tracked.

If the peer has already been cancelled in bulk (e.g. it disconnected and its requests were refunded en masse via its requestedBytesSizePerPeer total), that entry is gone; re-applying the per-request refund here would double-subtract requestedBytesSizePerPeer and underflow. So we gate on the peer still being present. The membership check, the refund, and the bulk cancellation all run within the same critical section, so whichever happens first refunds and the other does nothing.

refundTxRequest ∷ Ord peer ⇒ peer → BytesSize → LeiosOutstanding peer → LeiosOutstanding peer Source #

Like refundEbRequest, but for a received batch of EB txs: refunds the bytes, gated on the peer still being tracked (see refundEbRequest). The job bookkeeping (jobPool + this peer's in-flight set) is handled by completeTxRequest.

completeTxRequest ∷ Ord peer ⇒ peer → LeiosBlockTxsRequest → LeiosOutstanding peer → LeiosOutstanding peer Source #

On a received tx batch, remove its now-fetched jobs: delete them from the EB's jobPool (they are done for every peer) and from this peer's in-flight set, so neither this peer nor any other is asked for them again. Complements refundTxRequest, which handles only the per-peer byte accounting.

Deciding

data LeiosFetchStaticEnv Source #

The limits the decision logic holds its requests to.

The per-peer caps are hard: a request is made only if it fits in what remains of its peer's cap (peerBudget). A request larger than a whole cap is never made to that peer, so each cap must be at least the largest body the node fetches (maxEndorserBlockBytesSize) and the largest job (the larger of maxJobBytesSize and the ledger's maxTxSize).

maxJobBytesSize and maxRequestBytesSize are technically soft, but effectively hard because of the current protocol parameters. A transaction larger than maxJobBytesSize forms a job by itself, and a job larger than maxRequestBytesSize forms a request by itself. Neither happens while the ledger's maxTxSize is at most maxJobBytesSize and that is at most maxRequestBytesSize: the current constitution's guardrails cap maxTxSize at 32,768 bytes (MTS-01), in Dijkstra as in Conway, and the defaults here are 64 KiB and 500 kB. maxJobTxCount is hard.

Constructors

MkLeiosFetchStaticEnv 

Fields

leiosFetchLogicIteration Source #

Arguments

∷ Ord peer 
⇒ LeiosFetchStaticEnv 
→ (SlotNo → Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))

The ledger's bounds on an EB, forecast from the immutable tip to a slot. The slot can be older than the immutable tip, for a point not pruned yet.

Only an offer that brought no bound of its own needs this, and for those it cannot fail: the announcement backing such an offer was accepted by forecasting to that same slot from an immutable tip no newer than this one. See poEbBounds.

→ Maybe (SlotNo, Word64)

The current slot, and how many slots before it a point is still worth voting on, as of the ledger there (see fetchPriorityTiers); or Nothing when either is not yet known (i.e. we are syncing), in which case we fetch freshest-last instead of freshest-first.

→ Map peer (Map LeiosPoint PeerOffer) 
→ Map peer IsBigLedgerPeer

Which peers are big-ledger peers (a peer absent from this map is treated as IsNotBigLedgerPeer).

→ LeiosOutstanding peer 
→ (LeiosOutstanding peer, Map peer (NESeq LeiosFetchRequest), Map peer (NEMap LeiosPoint OfferPrune))

The new outstanding state, the requests to send, and what of the offers to prune (pruneOffers)

Decide what to request from each peer right now

A big-ledger peer is fetched from aggressively: it has a larger per-peer byte budget, enough that a closure it offers is requested in full (the whole remaining job pool) at once.

NOTE that which txs a point still lacks was settled when its body's write landed, so a job is requested even if the node has come to hold its txs elsewhere since. (TODO the LeiosFetch client could check again just before it sends the request? That would need the txs' hashes, retained in memory or read from disk.)

fetchPriorityTiers ∷ Maybe (SlotNo, Word64) → [(SlotNo, v)] → ([v], [v]) Source #

Prioritize a peer's Leios offers, each given with its point's slot

The offers are categorized into two tiers. The high-priority tier is the points still worth voting on: those no older than L = 3*L_hdr + L_vote + L_diff, in slots, as of the ledger at the current slot (ie whose slot is >= currentSlot - L). It prioritizes staler points. The low-priority tier is the rest, and it prioritizes fresher points.

assignPeer processes the high-priority tier first and then it carries over the resulting accumulator in order to process the low-priority tier.

When the node's ledger state is too old to know the current slot or L there, all points are categorized as the high-priority tier, and the low-priority tier is empty.

TODO rank first the points a verified certificate certifies (see focusCertifiedEb): ChainSel cannot select the block certifying one until the node holds its closure.

peerBudget ∷ Ord peer ⇒ LeiosFetchStaticEnv → IsBigLedgerPeer → LeiosOutstanding peer → peer → Int Source #

A peer's remaining outstanding-byte budget. The only "global limit" falls out as this per-peer cap multiplied by the peer count. That's good so that an adversarial peer can't occupy "too much" of some fixed global budget, thereby starving honest peers.

Big-ledger peers get a larger cap (so they can be asked for a whole EB closure at once), but still a bounded one -- even a stake-based peer might be adversarial.