Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 32 additions & 9 deletions core/services/ocr3_1/plugins/queue/blobs.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,31 @@ import (
"github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types"

"github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb"
"github.com/smartcontractkit/chainlink/v2/core/services/ocr3_1/plugins/queue/queuelimits"
)

// defaultBlobOpTimeout bounds each blob fetch or broadcast, so a stalled blob store or peer cannot block a plugin
// method indefinitely. It mirrors the vault plugin's blobBroadcastTimeout.
const defaultBlobOpTimeout = 2 * time.Second

// blobCache is a short-lived cache for coordinating concurrent fetches of event blobs, and of splitting them up.
type blobCache struct {
fetcher ocr3_1types.BlobFetcher
// timeout bounds each fetch. Zero means defaultBlobOpTimeout.
timeout time.Duration

mu sync.RWMutex
cache map[string]func() ([]byte, error) // blob handle -> blob
elements map[string]func() ([][]byte, error) // blob handle -> its events, split up
}

func (c *blobCache) opTimeout() time.Duration {
if c.timeout > 0 {
return c.timeout
}
return defaultBlobOpTimeout
}

// isCancellation reports whether an error is a context ending.
func isCancellation(err error) bool {
return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded)
Expand All @@ -50,6 +64,8 @@ func uncancelled[T any](ctx context.Context, get func() (T, error), evict func()
// fetchBlob fetches the blob once however many callers want it, and shares the result, whether a blob or an error. Not
// an error that is a context ending: see uncancelled.
func (c *blobCache) fetchBlob(ctx context.Context, handle []byte) ([]byte, error) {
ctx, cancel := context.WithTimeout(ctx, c.opTimeout())
defer cancel()
return uncancelled(ctx, func() ([]byte, error) { return c.fetchBlobCached(ctx, handle) }, func() {
c.mu.Lock()
defer c.mu.Unlock()
Expand Down Expand Up @@ -90,6 +106,8 @@ func (c *blobCache) fetchBlobCached(ctx context.Context, handle []byte) ([]byte,
// event by scanning from the start of a blob each time is quadratic in its events, which a peer could exploit by padding
// a blob with empty events.
func (c *blobCache) fetchElements(ctx context.Context, handle []byte) ([][]byte, error) {
ctx, cancel := context.WithTimeout(ctx, c.opTimeout())
defer cancel()
return uncancelled(ctx, func() ([][]byte, error) { return c.fetchElementsCached(ctx, handle) }, func() {
c.mu.Lock()
defer c.mu.Unlock()
Expand Down Expand Up @@ -135,11 +153,10 @@ func fetchCoordinatedEventFromBlob(ctx context.Context, fetcher *blobCache, hand
return &event, elements[idx], nil
}

const coordinatedEventsFieldNumber = 1 // pb.CoordinatedEventList.Events
const coordinatedEventsFieldNumber = queuelimits.CoordinatedEventsFieldNumber // pb.CoordinatedEventList.Events

// maxEventFramingOverhead is the most framing (field tag + length prefix) an event adds as an element of a blob.
// The length prefix is at most as long as the varint of the blob payload limit, which is capped by MaxMaxBlobPayloadBytes.
var maxEventFramingOverhead = protowire.SizeTag(coordinatedEventsFieldNumber) + protowire.SizeVarint(uint64(ocr3_1types.MaxMaxBlobPayloadBytes))
var maxEventFramingOverhead = queuelimits.MaxEventFramingOverhead(coordinatedEventsFieldNumber)

// maxEventBytes returns the largest encoded event (without timestamps) guaranteed to fit alone in a blob.
// It is conservative by at most a few bytes.
Expand Down Expand Up @@ -194,7 +211,7 @@ func splitEvents(b []byte, limit int) ([][]byte, error) {
const (
// minBlobLifetime is the least time a blob is kept past the events in it expiring. Peers reap expired blobs
// asynchronously, and nodes that are behind, or that never received the blob, need time to fetch it.
minBlobLifetime = 30 * time.Second
minBlobLifetime = queuelimits.MinBlobLifetime
// minBlobLifetimeRounds is the fewest rounds a blob is kept, however the round interval compares to minBlobLifetime.
// The events in it are executed in Committed for its round and in the Observation of the next, which both fetch it.
minBlobLifetimeRounds = 3
Expand Down Expand Up @@ -226,15 +243,21 @@ func (c *consensusQueuePlugin) blobPrefix(events []*pb.CoordinatedEvent) int {
})
}

// broadcastBlob broadcasts a blob with all of the events, which must fit, and returns its marshaled handle.
func (c *consensusQueuePlugin) broadcastBlob(ctx context.Context, broadcaster ocr3_1types.BlobBroadcaster, events []*pb.CoordinatedEvent, seqNr uint64) ([]byte, error) {
var maxDeadline time.Time
// latestDeadline returns the latest deadline among the events, or the zero time if none has one.
func latestDeadline(events []*pb.ConsensusQueueEvent) time.Time {
var latest time.Time
for _, event := range events {
if t := event.Deadline.AsTime(); t.After(maxDeadline) {
maxDeadline = t
if t := event.GetDeadline().AsTime(); t.After(latest) {
latest = t
}
}
return latest
}

// broadcastBlob broadcasts a blob with all of the events, which must fit, and returns its marshaled handle.
// maxDeadline is the latest deadline of the events, which the caller must take from the observation: the events
// themselves carry no timestamps, as they are stripped for consistent hashing and left out of the blob.
func (c *consensusQueuePlugin) broadcastBlob(ctx context.Context, broadcaster ocr3_1types.BlobBroadcaster, events []*pb.CoordinatedEvent, maxDeadline time.Time, seqNr uint64) ([]byte, error) {
// An event is kept until its deadline plus the grace period, so its blob must be too.
grace, err := c.expirationDur(ctx)
if err != nil {
Expand Down
9 changes: 8 additions & 1 deletion core/services/ocr3_1/plugins/queue/blobs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -622,7 +622,14 @@ func (c *consensusQueuePlugin) broadcastAsBlob(ctx context.Context, broadcaster
return nil, 0, errors.New("failed to package any events in blob")
}

blobHandle, err = c.broadcastBlob(ctx, broadcaster, events[:n], seqNr)
var maxDeadline time.Time
for _, event := range events[:n] {
if t := event.GetDeadline().AsTime(); t.After(maxDeadline) {
maxDeadline = t
}
}

blobHandle, err = c.broadcastBlob(ctx, broadcaster, events[:n], maxDeadline, seqNr)
if err != nil {
return nil, -1, err
}
Expand Down
12 changes: 12 additions & 0 deletions core/services/ocr3_1/plugins/queue/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (

"github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb"
"github.com/smartcontractkit/chainlink-common/pkg/settings/cresettings"
"github.com/smartcontractkit/chainlink/v2/core/services/ocr3_1/plugins/queue/queuelimits"
)

// The tests below calibrate the constants in queue.go (and the libocr limits they must fit within) by measuring real
Expand Down Expand Up @@ -233,5 +234,16 @@ func TestCalibration_BlobLifetime(t *testing.T) {
roundDur, rounds, time.Duration(rounds)*roundDur, perRoundBlobs*int(rounds), //nolint:gosec // G115: a small number of rounds
float64(perRoundBlobs)*float64(rounds)*float64(ocr3_1types.MaxMaxBlobPayloadBytes)/(1<<30))
assert.GreaterOrEqual(t, time.Duration(rounds)*roundDur, timeout+grace, "blobs must outlive their events") //nolint:gosec // G115: a small number of rounds

// The per-oracle quota a deployment must allow for a node's broadcasts to survive the event lifetime. Size it
// for a reference 1 MiB of payload per round: the config field is a uint32, so the worst case (10 full blobs
// every round) cannot be expressed at fast round intervals.
const referencePayloadPerRound = 1 << 20
quotaCount, quotaPayload := queuelimits.BlobQuota(roundDur, timeout, grace, referencePayloadPerRound)
t.Logf("DeltaRound %-6s: quota %6d blobs, %5.1f GiB for 1 MiB per round", roundDur, quotaCount, float64(quotaPayload)/(1<<30))
assert.GreaterOrEqual(t, int(quotaCount), perRoundBlobs*int(rounds), //nolint:gosec // G115: a small number of rounds
"the quota must hold a full observation's blobs for the event lifetime")
assert.GreaterOrEqual(t, int64(quotaPayload), int64(referencePayloadPerRound)*int64(rounds), //nolint:gosec // G115: a small number of rounds
"the quota must hold the reference payload for the event lifetime")
}
}
11 changes: 6 additions & 5 deletions core/services/ocr3_1/plugins/queue/kvstate.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,23 @@ import (
"github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types"

"github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb"
"github.com/smartcontractkit/chainlink/v2/core/services/ocr3_1/plugins/queue/queuelimits"
)

// numKVKeys is the number of KV keys written each round.
const numKVKeys = 4
const numKVKeys = queuelimits.NumKVKeys

// KV store keys
const (
// observed events waiting for consensus (F+1 <= observers <2F+1). Each event's Blobs are aligned with its NodeIds: the
// blob of each vote.
observedEventsKey = "observed_events::index" // pb.ConsensusQueueObservedEvents { map[string]*pb.ConsensusQueueObservedEvent; [][]byte }
observedEventsKey = queuelimits.ObservedEventsKey // pb.ConsensusQueueObservedEvents { map[string]*pb.ConsensusQueueObservedEvent; [][]byte }
// priority queue of events waiting for capacity
queuedEventsKey = "queued_events::index" // pb.ConsensusQueueEventList { []*pb.ConsensusQueueEvent }
queuedEventsKey = queuelimits.QueuedEventsKey // pb.ConsensusQueueEventList { []*pb.ConsensusQueueEvent }
// events the plugin committed to sending to nodes
consensusEventsKey = "consensus_events::index" // pb.ConsensusQueueEventList { []*pb.ConsensusQueueEvent }
consensusEventsKey = queuelimits.ConsensusEventsKey // pb.ConsensusQueueEventList { []*pb.ConsensusQueueEvent }
// blob handles referenced from events in the PQ and consensus set
blobHandlesKey = "blob_handles::index" // pb.ConsensusQueueBlobHandleList{ [][]byte }
blobHandlesKey = queuelimits.BlobHandlesKey // pb.ConsensusQueueBlobHandleList{ [][]byte }
)

type stateWriter struct {
Expand Down
33 changes: 27 additions & 6 deletions core/services/ocr3_1/plugins/queue/queue.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,15 @@ import (
"github.com/smartcontractkit/chainlink-common/pkg/settings/cresettings"
"github.com/smartcontractkit/chainlink-common/pkg/settings/limits"
"github.com/smartcontractkit/chainlink-common/pkg/workflows"
"github.com/smartcontractkit/chainlink/v2/core/services/ocr3_1/plugins/queue/queuelimits"
"github.com/smartcontractkit/chainlink/v2/core/services/ocr3_1/plugins/queue/queuepb"
"github.com/smartcontractkit/chainlink/v2/core/services/workflows/types"
"github.com/smartcontractkit/chainlink/v2/core/services/workflows/v2/triggers"
)

const (
maxObservedBlobHandles = 10 // sanity check on blobs in an observation
maxObservedEvents = 1000 // sanity check events in an observation
maxObservedBlobHandles = queuelimits.MaxBlobHandlesPerObservation // sanity check on blobs in an observation
maxObservedEvents = queuelimits.MaxObservedEvents // sanity check events in an observation
maxKeyValueValueBytes = ocr3_1types.MaxMaxKeyValueValueBytes
)

Expand Down Expand Up @@ -130,6 +131,9 @@ func (c *consensusQueuePluginFactory) NewReportingPlugin(ctx context.Context, co
if err != nil {
return nil, ocr3_1types.ReportingPluginInfo1{}, err
}
if err = queuepb.ValidateForDon(pluginLimits, config.N, config.F); err != nil {
return nil, ocr3_1types.ReportingPluginInfo1{}, fmt.Errorf("invalid consensus-queue limits: %w", err)
}
c.lggr.Infow("Creating consensus-queue reporting plugin", "configDigest", config.ConfigDigest.String(), "limits", pluginLimits)

metrics, err := newPluginMetrics(c.meter, config.ConfigDigest.String())
Expand Down Expand Up @@ -158,12 +162,21 @@ type consensusQueuePlugin struct {
triggerCoordinator triggers.Coordinator
triggerQueue triggers.Queue
blobBroadcastFetcher ocr3_1types.BlobBroadcastFetcher
expirationDur func(context.Context) (time.Duration, error)
// blobTimeout bounds each blob fetch or broadcast. Zero means defaultBlobOpTimeout.
blobTimeout time.Duration
expirationDur func(context.Context) (time.Duration, error)
// kvDrain reports whether the KV drain recovery mode is on at a time. Nil means it never is.
kvDrain func(ctx context.Context, at time.Time) (bool, error)
metrics *pluginMetrics
}

func (c *consensusQueuePlugin) blobOpTimeout() time.Duration {
if c.blobTimeout > 0 {
return c.blobTimeout
}
return defaultBlobOpTimeout
}

// draining reports whether the KV drain recovery mode is on at a time. A failure to read the setting counts as off, and
// is logged, as the mode is for recovering and normal operation is the safe default.
//
Expand Down Expand Up @@ -199,6 +212,7 @@ func newConsensusQueuePlugin(
triggerCoordinator: triggerCoordinator,
triggerQueue: triggerQueue,
blobBroadcastFetcher: blobs,
blobTimeout: defaultBlobOpTimeout,
expirationDur: expirationGraceDur,
metrics: metrics,
}
Expand Down Expand Up @@ -451,9 +465,16 @@ func (c *consensusQueuePlugin) broadcastObservationBlobs(
var eg errgroup.Group
for i, start := 0, 0; i < len(ends); i++ {
batch := events[start:ends[i]]
// The events have no timestamps (they are stripped before hashing and broadcasting), so take the blob's
// deadline from the observation, which retains it, for the expiration hint.
maxDeadline := latestDeadline(obs.Events[start:ends[i]])
start = ends[i]
eg.Go(func() error {
handles[i], errs[i] = c.broadcastBlob(ctx, blobBroadcaster, batch, seqNr)
// Bound each broadcast, so a stalled blob store or peer cannot hold this Observation. A timeout is a failed
// broadcast: its events are omitted below, which must not fail Observation.
bcastCtx, cancel := context.WithTimeout(ctx, c.blobOpTimeout())
defer cancel()
handles[i], errs[i] = c.broadcastBlob(bcastCtx, blobBroadcaster, batch, maxDeadline, seqNr)
return nil
})
}
Expand Down Expand Up @@ -545,7 +566,7 @@ func (c *consensusQueuePlugin) ValidateObservation(
}

var eg errgroup.Group
fetcher := blobCache{fetcher: blobFetcher, cache: make(map[string]func() ([]byte, error))}
fetcher := blobCache{fetcher: blobFetcher, timeout: c.blobOpTimeout(), cache: make(map[string]func() ([]byte, error))}
for i, event := range obs.Events {
eg.Go(func() error {
if verr := validateObservedEvent(ctx, &fetcher, event, obs.BlobHandles); verr != nil {
Expand Down Expand Up @@ -892,7 +913,7 @@ func (c *consensusQueuePlugin) commitState(ctx context.Context, kvReader ocr3_1t
// It is idempotent, thus safe to call from Observation and Committed.
func (c *consensusQueuePlugin) tryStartExecutions(ctx context.Context, done chan struct{}, consensusEvents []*pb.ConsensusQueueEvent, blobHandles [][]byte) {
defer close(done)
fetcher := blobCache{fetcher: c.blobBroadcastFetcher, cache: make(map[string]func() ([]byte, error))}
fetcher := blobCache{fetcher: c.blobBroadcastFetcher, timeout: c.blobOpTimeout(), cache: make(map[string]func() ([]byte, error))}
var wg sync.WaitGroup
for _, consensusEvent := range consensusEvents {
wg.Add(1)
Expand Down
Loading
Loading