diff --git a/core/services/ocr3_1/plugins/queue/blobs.go b/core/services/ocr3_1/plugins/queue/blobs.go index 1e3da60304a..689f2a65bca 100644 --- a/core/services/ocr3_1/plugins/queue/blobs.go +++ b/core/services/ocr3_1/plugins/queue/blobs.go @@ -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) @@ -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() @@ -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() @@ -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. @@ -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 @@ -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 { diff --git a/core/services/ocr3_1/plugins/queue/blobs_test.go b/core/services/ocr3_1/plugins/queue/blobs_test.go index 9a04450f914..16768ed13af 100644 --- a/core/services/ocr3_1/plugins/queue/blobs_test.go +++ b/core/services/ocr3_1/plugins/queue/blobs_test.go @@ -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 } diff --git a/core/services/ocr3_1/plugins/queue/config_test.go b/core/services/ocr3_1/plugins/queue/config_test.go index f8dbbb733a8..fece74e4835 100644 --- a/core/services/ocr3_1/plugins/queue/config_test.go +++ b/core/services/ocr3_1/plugins/queue/config_test.go @@ -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 @@ -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") } } diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index 70c6bac2005..4740df75576 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -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 { diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index a48d2a9f449..cb705493812 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -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 ) @@ -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()) @@ -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. // @@ -199,6 +212,7 @@ func newConsensusQueuePlugin( triggerCoordinator: triggerCoordinator, triggerQueue: triggerQueue, blobBroadcastFetcher: blobs, + blobTimeout: defaultBlobOpTimeout, expirationDur: expirationGraceDur, metrics: metrics, } @@ -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 }) } @@ -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 { @@ -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) diff --git a/core/services/ocr3_1/plugins/queue/queue_test.go b/core/services/ocr3_1/plugins/queue/queue_test.go index e3f4df9a909..445ca23dcea 100644 --- a/core/services/ocr3_1/plugins/queue/queue_test.go +++ b/core/services/ocr3_1/plugins/queue/queue_test.go @@ -49,9 +49,12 @@ func TestConsensusQueuePluginFactory_NewReportingPlugin(t *testing.T) { validCfg, err := proto.Marshal(&queuepb.ReportingPluginConfig{ Limits: &queuepb.ReportingPluginLimits{ - MaxObservationBytes: 1024, - MaxKeyValueModifiedKeys: 10, - MaxKeyValueModifiedKeysPlusValuesBytes: 2048, + MaxObservationBytes: 512 * 1024, + MaxKeyValueModifiedKeys: 10, + MaxKeyValueModifiedKeysPlusValuesBytes: 2048, + MaxBlobPayloadBytes: 5 * 1024 * 1024, + MaxPerOracleUnexpiredBlobCumulativePayloadBytes: 100 * 1024 * 1024, + MaxPerOracleUnexpiredBlobCount: 1000, }, }) require.NoError(t, err) @@ -70,13 +73,37 @@ func TestConsensusQueuePluginFactory_NewReportingPlugin(t *testing.T) { require.True(t, ok, "unexpected ReportingPluginInfo type %T", info) require.Equal(t, "ConsensusQueueReportingPlugin", info1.Name) want := ocr3_1types.ReportingPluginLimits{ - MaxObservationBytes: 1024, - MaxKeyValueModifiedKeys: 10, - MaxKeyValueModifiedKeysPlusValuesBytes: 2048, + MaxObservationBytes: 512 * 1024, + MaxKeyValueModifiedKeys: 10, + MaxKeyValueModifiedKeysPlusValuesBytes: 2048, + MaxBlobPayloadBytes: 5 * 1024 * 1024, + MaxPerOracleUnexpiredBlobCumulativePayloadBytes: 100 * 1024 * 1024, + MaxPerOracleUnexpiredBlobCount: 1000, } require.Equal(t, want, info1.Limits) }) + t.Run("observation too small for the DON is rejected", func(t *testing.T) { + t.Parallel() + small, err := proto.Marshal(&queuepb.ReportingPluginConfig{ + Limits: &queuepb.ReportingPluginLimits{ + MaxObservationBytes: 1024, + MaxKeyValueModifiedKeys: 4, + MaxKeyValueModifiedKeysPlusValuesBytes: 10 * 1024 * 1024, + MaxBlobPayloadBytes: 5 * 1024 * 1024, + MaxPerOracleUnexpiredBlobCumulativePayloadBytes: 100 * 1024 * 1024, + MaxPerOracleUnexpiredBlobCount: 1000, + }, + }) + require.NoError(t, err) + + factory, err := NewConsensusQueuePluginFactory(logger.Test(t), limits.Factory{}, noopCoordinator{}, noopQueue{}, noop.NewMeterProvider().Meter("test")) + require.NoError(t, err) + plugin, _, err := factory.NewReportingPlugin(t.Context(), ocr3types.ReportingPluginConfig{N: 4, F: 1, OffchainConfig: small}, nil) + require.ErrorContains(t, err, "MaxObservationBytes") + require.Nil(t, plugin) + }) + tests := []struct { name string got []byte @@ -686,6 +713,75 @@ func TestValidateObservation(t *testing.T) { }) } +// blockingBlobs waits for its context to end, so tests can prove blob fetches and broadcasts are bounded. +type blockingBlobs struct{} + +func (blockingBlobs) FetchBlob(ctx context.Context, _ ocr3_1types.BlobHandle) ([]byte, error) { + <-ctx.Done() + return nil, ctx.Err() +} + +func (blockingBlobs) BroadcastBlob(ctx context.Context, _ []byte, _ ocr3_1types.BlobExpirationHint) (ocr3_1types.BlobHandle, error) { + <-ctx.Done() + return ocr3_1types.BlobHandle{}, ctx.Err() +} + +// A stalled blob store or peer must not hold a plugin method open. Each blob operation is bounded, and a timeout is +// treated as a failed blob: Observation still returns, ValidateObservation rejects the observation, and Committed +// gives up on the event. +func TestBlobOperations_AreBounded(t *testing.T) { + t.Parallel() + + const blobTimeout = 20 * time.Millisecond + newEvents := func(t *testing.T) []hashedEvent { + return mkEvents(t, 1, time.Now().Add(time.Hour).Unix()) + } + + t.Run("Observation bounds a stalled broadcast", func(t *testing.T) { + t.Parallel() + c := testPlugin(t, sliceQueue{events: newEvents(t)}, &memBlobs{}, ocr3_1types.MaxMaxObservationBytes) + c.blobTimeout = blobTimeout + + start := time.Now() + raw, err := c.Observation(t.Context(), 1, ocrtypes.AttributedQuery{}, memKV{}, blockingBlobs{}) + elapsed := time.Since(start) + require.NoError(t, err, "a failed broadcast must not fail Observation") + assert.Less(t, elapsed, 2*time.Second) + + var obs pb.ConsensusQueueObservation + require.NoError(t, proto.Unmarshal(raw, &obs)) + assert.Empty(t, obs.Events, "the events of a timed-out blob are omitted") + assert.Empty(t, obs.BlobHandles) + }) + + t.Run("ValidateObservation bounds a stalled fetch", func(t *testing.T) { + t.Parallel() + blobs := &memBlobs{} + c := testPlugin(t, sliceQueue{events: newEvents(t)}, blobs, ocr3_1types.MaxMaxObservationBytes) + raw, err := c.Observation(t.Context(), 1, ocrtypes.AttributedQuery{}, memKV{}, blobs) + require.NoError(t, err) + c.blobTimeout = blobTimeout + + start := time.Now() + err = c.ValidateObservation(t.Context(), 1, ocrtypes.AttributedQuery{}, + ocrtypes.AttributedObservation{Observer: 1, Observation: raw}, memKV{}, blockingBlobs{}) + assert.Less(t, time.Since(start), 2*time.Second) + require.ErrorContains(t, err, "failed to fetch") + }) + + t.Run("Committed bounds a stalled fetch", func(t *testing.T) { + t.Parallel() + blobs, kv := &memBlobs{}, memKV{} + seedKV(t, kv, blobs, []string{"a"}, nil) + c := newCommitPlugin(t, &recCoordinator{}, &recQueue{}, blockingBlobs{}) + c.blobTimeout = blobTimeout + + start := time.Now() + require.NoError(t, c.Committed(t.Context(), 1, kv)) + assert.Less(t, time.Since(start), 2*time.Second) + }) +} + func TestObservationQuorum(t *testing.T) { t.Parallel() @@ -1566,6 +1662,28 @@ func TestObservation_BlobBatching(t *testing.T) { }) } +func TestObservation_BlobExpiryHintCoversEventDeadline(t *testing.T) { + t.Parallel() + + // testPlugin uses a one minute grace and a one second estimated round interval. + const grace = time.Minute + blobs := &hintBlobs{} + c := testPlugin(t, sliceQueue{events: mkEvents(t, 1, time.Now().Add(time.Hour).Unix())}, blobs, ocr3_1types.MaxMaxObservationBytes) + + obs, err := observe(t, c, memKV{}, blobs) + require.NoError(t, err) + require.Len(t, obs.Events, 1) + require.Len(t, blobs.hints, 1, "one event is one blob") + + hint, ok := blobs.hints[0].(ocr3_1types.BlobExpirationHintSequenceNumber) + require.True(t, ok, "unexpected hint type %T", blobs.hints[0]) + + // The blob must live until its event's deadline plus the grace period, plus the minimum lifetime. The hint is + // computed from the deadline retained in the observation, not from the event, whose timestamps are stripped. + want := blobExpirySeqNr(1, time.Until(obs.Events[0].Deadline.AsTime().Add(grace)), c.onchainCfg.EstimatedRoundInterval) + assert.InDelta(t, int(want), int(hint.SeqNr), 2) //nolint:gosec // G115: small test values +} + // Known issues (SHOULD FIX): libocr says a BlobBroadcast failure should not make Observation fail, and one event that // can never be broadcast must not wedge this node's observations forever. These fail until handled. func TestObservation_BlobFailuresAreNotFatal(t *testing.T) { diff --git a/core/services/ocr3_1/plugins/queue/queuelimits/queuelimits.go b/core/services/ocr3_1/plugins/queue/queuelimits/queuelimits.go new file mode 100644 index 00000000000..b34cf214166 --- /dev/null +++ b/core/services/ocr3_1/plugins/queue/queuelimits/queuelimits.go @@ -0,0 +1,88 @@ +// Package queuelimits holds the consensus-queue plugin's runtime sizing constants and the formula for its blob quotas. +// It is shared by the plugin, config validation and deployment tooling. Configuration validation itself lives in +// queuepb, next to the config it validates. +package queuelimits + +import ( + "math" + "time" + + "google.golang.org/protobuf/encoding/protowire" + + "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types" +) + +// Plugin sizing constants. +const ( + // MaxBlobHandlesPerObservation is the most blobs a node broadcasts in one Observation. + MaxBlobHandlesPerObservation = 10 + // MaxObservedEvents is the most events a node reports in one Observation. + MaxObservedEvents = 1000 + // MinBlobLifetime is the least time a blob is kept past the events in it expiring. + MinBlobLifetime = 30 * time.Second + // BlobReapingSlack is the extra time a blob may remain after it expires before it is reaped. libocr reaps + // asynchronously, and asks for a margin of tens of seconds when sizing the per-oracle blob quotas. + BlobReapingSlack = time.Minute +) + +// The KV keys StateTransition writes every round. +const ( + ObservedEventsKey = "observed_events::index" + QueuedEventsKey = "queued_events::index" + ConsensusEventsKey = "consensus_events::index" + BlobHandlesKey = "blob_handles::index" + + // NumKVKeys is the number of KV keys StateTransition writes every round. + NumKVKeys = 4 +) + +// Blob framing constants. +const ( + // CoordinatedEventsFieldNumber is the protobuf field number of CoordinatedEventList.Events. + CoordinatedEventsFieldNumber = 1 +) + +// MaxEventFramingOverhead returns the most framing an event adds as an element of a blob: its field tag and the +// length prefix, whose varint is at most as long as the blob payload limit. +func MaxEventFramingOverhead(fieldNumber protowire.Number) int { + return protowire.SizeTag(fieldNumber) + protowire.SizeVarint(uint64(ocr3_1types.MaxMaxBlobPayloadBytes)) +} + +// BlobQuota returns the per-oracle unexpired blob quota, in blobs and cumulative payload bytes, needed to hold a +// node's broadcasts for the lifetime of their events plus a margin for asynchronous reaping. +// +// A blob is kept until its event's deadline plus the grace period, and at least MinBlobLifetime. A node broadcasts at +// most MaxBlobHandlesPerObservation blobs per round. eventTimeout and grace are the workflow's trigger event timeout +// and the consensus-queue expiration grace; roundDur is the DON's DeltaRound. +// +// payloadBytesPerRound is the sustained blob payload per round the quota should cover. Pass the reference the +// deployment targets, not necessarily MaxBlobPayloadBytes: the config field is a uint32, and covering the worst case +// (MaxBlobHandlesPerObservation full blobs every round) would need far more than it can express. +// +// Both results saturate at math.MaxUint32, the widest value the config proto can carry. +func BlobQuota(roundDur, eventTimeout, grace time.Duration, payloadBytesPerRound int) (count, payloadBytes uint32) { + if roundDur <= 0 { + roundDur = time.Second + } + lifetime := max(0, eventTimeout) + max(0, grace) + MinBlobLifetime + rounds := (lifetime + roundDur - 1) / roundDur // round up: every partial round is a full one + rounds = max(rounds, 3) // blobs are kept for at least three rounds + reapingRounds := (BlobReapingSlack + roundDur - 1) / roundDur + // Both are non-negative: roundDur is positive (defaulted above), and each is a positive duration divided by it. + totalRounds := uint64(rounds + reapingRounds) //nolint:gosec // G115: non-negative rounds, see above + + count = saturatingMul(uint64(MaxBlobHandlesPerObservation), totalRounds) + payloadBytes = saturatingMul(uint64(max(0, payloadBytesPerRound)), totalRounds) + return +} + +// saturatingMul multiplies without overflowing, saturating at math.MaxUint32. +func saturatingMul(a, b uint64) uint32 { + if a == 0 || b == 0 { + return 0 + } + if a > math.MaxUint32/b { + return math.MaxUint32 + } + return uint32(a * b) //nolint:gosec // G115 the guard above bounds the product by math.MaxUint32 +} diff --git a/core/services/ocr3_1/plugins/queue/queuelimits/queuelimits_test.go b/core/services/ocr3_1/plugins/queue/queuelimits/queuelimits_test.go new file mode 100644 index 00000000000..5f29f5cefb3 --- /dev/null +++ b/core/services/ocr3_1/plugins/queue/queuelimits/queuelimits_test.go @@ -0,0 +1,65 @@ +package queuelimits + +import ( + "math" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestBlobQuota(t *testing.T) { + t.Parallel() + + const ( + timeout = 10 * time.Minute + grace = time.Minute + perRound = 1 << 20 + ) + + t.Run("covers the event lifetime plus reaping slack", func(t *testing.T) { + t.Parallel() + count, payload := BlobQuota(time.Second, timeout, grace, perRound) + // 690 rounds of event lifetime (10m + 1m + 30s minimum) plus 60 rounds of reaping slack. + assert.Equal(t, uint32(7_500), count) + assert.Equal(t, uint32(786_432_000), payload) + }) + + t.Run("faster rounds keep proportionally more blobs", func(t *testing.T) { + t.Parallel() + count, payload := BlobQuota(200*time.Millisecond, timeout, grace, perRound) + // 3450 rounds of event lifetime plus 300 rounds of reaping slack. + assert.Equal(t, uint32(37_500), count) + assert.Equal(t, uint32(3_932_160_000), payload) + }) + + t.Run("keeps blobs for at least three rounds", func(t *testing.T) { + t.Parallel() + count, _ := BlobQuota(time.Hour, 0, 0, 0) + // The lifetime is MinBlobLifetime, which rounds to zero at a one hour round interval, so the minimum of + // three applies, plus one reaping round. + assert.Equal(t, uint32(4*MaxBlobHandlesPerObservation), count) + }) + + t.Run("non-positive round interval means one second", func(t *testing.T) { + t.Parallel() + count, payload := BlobQuota(0, timeout, grace, perRound) + wantCount, wantPayload := BlobQuota(time.Second, timeout, grace, perRound) + assert.Equal(t, wantCount, count) + assert.Equal(t, wantPayload, payload) + }) + + t.Run("saturates at the config's uint32 maximum", func(t *testing.T) { + t.Parallel() + count, payload := BlobQuota(time.Nanosecond, timeout, grace, math.MaxInt32) + assert.Equal(t, uint32(math.MaxUint32), count) + assert.Equal(t, uint32(math.MaxUint32), payload) + }) + + t.Run("negative lifetimes are clamped", func(t *testing.T) { + t.Parallel() + count, _ := BlobQuota(time.Second, -time.Hour, -time.Hour, 0) + // Only MinBlobLifetime remains: 30 rounds at a one second interval, plus 60 rounds of reaping slack. + assert.Equal(t, uint32(10*(30+60)), count) + }) +} diff --git a/core/services/ocr3_1/plugins/queue/queuepb/limits.go b/core/services/ocr3_1/plugins/queue/queuepb/limits.go index 74c624ab497..90e50c6bd3e 100644 --- a/core/services/ocr3_1/plugins/queue/queuepb/limits.go +++ b/core/services/ocr3_1/plugins/queue/queuepb/limits.go @@ -7,6 +7,23 @@ import ( "google.golang.org/protobuf/proto" "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types" + + "github.com/smartcontractkit/chainlink/v2/core/services/ocr3_1/plugins/queue/queuelimits" +) + +// Config floors. A value below one of these does not merely degrade the plugin: it cannot observe events or commit a +// state transition, permanently and DON-wide. +const ( + // MinEventPayloadBytes is a conservative floor for one encoded trigger event: a 64-character workflow ID plus the + // trigger response. No event can be observed or broadcast below it. + MinEventPayloadBytes = 256 + // MinObservationBytes is the least observation budget beyond the blob handle reservation: one event's metadata, + // the expiration and capacity fields, and the workflow capacities map. + MinObservationBytes = 1024 + // MinKeyValueModifiedKeysPlusValuesBytes is the least budget that can hold every KV key with an empty value. A + // smaller budget makes libocr reject every state transition, so no round ever commits. + MinKeyValueModifiedKeysPlusValuesBytes = len(queuelimits.ObservedEventsKey) + len(queuelimits.QueuedEventsKey) + + len(queuelimits.ConsensusEventsKey) + len(queuelimits.BlobHandlesKey) ) // Decode parses the consensus-queue plugin config from the OCR offchain config bytes. @@ -32,8 +49,8 @@ func Decode(b []byte) (*ReportingPluginConfig, error) { // OCRLimits converts the config's limits to libocr's ReportingPluginLimits. // There are no defaults. Every value comes from the config so all oracles agree on it. // -// Returns an error if the limits are missing, if MaxObservationBytes, MaxKeyValueModifiedKeys or -// MaxKeyValueModifiedKeysPlusValuesBytes is zero, or if any limit exceeds libocr's maximum. +// Returns an error if the limits are missing, if they cannot support the plugin's writes and observations (see +// ValidateConfig), or if any limit exceeds libocr's maximum. func (c *ReportingPluginConfig) OCRLimits() (ocr3_1types.ReportingPluginLimits, error) { l := c.GetLimits() if l == nil { @@ -53,18 +70,55 @@ func (c *ReportingPluginConfig) OCRLimits() (ocr3_1types.ReportingPluginLimits, MaxPerOracleUnexpiredBlobCount: int(l.GetMaxPerOracleUnexpiredBlobCount()), } + if err := errors.Join(ValidateConfig(out), out.Validate()); err != nil { + return ocr3_1types.ReportingPluginLimits{}, fmt.Errorf("invalid consensus-queue limits: %w", err) + } + return out, nil +} + +// ValidateConfig checks the configuration-only floors the plugin relies on. A value below one of these does not +// merely degrade: the plugin cannot observe events or commit a state transition, permanently and DON-wide. +func ValidateConfig(l ocr3_1types.ReportingPluginLimits) error { var err error - if out.MaxObservationBytes == 0 { - err = errors.Join(err, errors.New("MaxObservationBytes must be at least 1")) + if l.MaxObservationBytes < MinObservationBytes { + err = errors.Join(err, fmt.Errorf( + "MaxObservationBytes must be at least %d to carry one event, but got %d", MinObservationBytes, l.MaxObservationBytes)) } - if out.MaxKeyValueModifiedKeys == 0 { - err = errors.Join(err, errors.New("MaxKeyValueModifiedKeys must be at least 1")) + if l.MaxKeyValueModifiedKeys < queuelimits.NumKVKeys { + err = errors.Join(err, fmt.Errorf( + "MaxKeyValueModifiedKeys must be at least %d, the keys written every round, but got %d", queuelimits.NumKVKeys, l.MaxKeyValueModifiedKeys)) } - if out.MaxKeyValueModifiedKeysPlusValuesBytes == 0 { - err = errors.Join(err, errors.New("MaxKeyValueModifiedKeysPlusValuesBytes must be at least 1")) + if l.MaxKeyValueModifiedKeysPlusValuesBytes < MinKeyValueModifiedKeysPlusValuesBytes { + err = errors.Join(err, fmt.Errorf( + "MaxKeyValueModifiedKeysPlusValuesBytes must be at least %d, the keys written every round, but got %d", + MinKeyValueModifiedKeysPlusValuesBytes, l.MaxKeyValueModifiedKeysPlusValuesBytes)) } - if err = errors.Join(err, out.Validate()); err != nil { - return ocr3_1types.ReportingPluginLimits{}, fmt.Errorf("invalid consensus-queue limits: %w", err) + minBlob := queuelimits.MaxEventFramingOverhead(queuelimits.CoordinatedEventsFieldNumber) + MinEventPayloadBytes + if l.MaxBlobPayloadBytes < minBlob { + err = errors.Join(err, fmt.Errorf( + "MaxBlobPayloadBytes must be at least %d to carry one event, but got %d", minBlob, l.MaxBlobPayloadBytes)) } - return out, nil + if l.MaxPerOracleUnexpiredBlobCount <= 0 { + err = errors.Join(err, fmt.Errorf( + "MaxPerOracleUnexpiredBlobCount must be positive, but got %d", l.MaxPerOracleUnexpiredBlobCount)) + } + if l.MaxPerOracleUnexpiredBlobCumulativePayloadBytes <= 0 { + err = errors.Join(err, fmt.Errorf( + "MaxPerOracleUnexpiredBlobCumulativePayloadBytes must be positive, but got %d", l.MaxPerOracleUnexpiredBlobCumulativePayloadBytes)) + } + return err +} + +// ValidateForDon checks the limits that depend on the DON's size. Observation reserves space for +// queuelimits.MaxBlobHandlesPerObservation blob handles up front, and their wire size grows with N and F, so a config +// that is valid in general can still be too small for a particular DON. +func ValidateForDon(l ocr3_1types.ReportingPluginLimits, n, f int) error { + handleBytes := ocr3_1types.BlobHandleMarshalledBytesUpperBound(n, f) + minBytes := queuelimits.MaxBlobHandlesPerObservation*handleBytes + MinObservationBytes + if l.MaxObservationBytes < minBytes { + return fmt.Errorf( + "MaxObservationBytes must be at least %d for N=%d F=%d, which reserves space for %d blob handles, but got %d", + minBytes, n, f, queuelimits.MaxBlobHandlesPerObservation, l.MaxObservationBytes) + } + return nil } diff --git a/core/services/ocr3_1/plugins/queue/queuepb/limits_test.go b/core/services/ocr3_1/plugins/queue/queuepb/limits_test.go index b0582e27296..aa61211d364 100644 --- a/core/services/ocr3_1/plugins/queue/queuepb/limits_test.go +++ b/core/services/ocr3_1/plugins/queue/queuepb/limits_test.go @@ -12,15 +12,15 @@ import ( func validLimits() *ReportingPluginLimits { return &ReportingPluginLimits{ MaxQueryBytes: 1, - MaxObservationBytes: 2, + MaxObservationBytes: 512 * 1024, MaxReportsPlusPrecursorBytes: 3, MaxReportBytes: 4, MaxReportCount: 5, - MaxKeyValueModifiedKeys: 6, - MaxKeyValueModifiedKeysPlusValuesBytes: 7, - MaxBlobPayloadBytes: 8, - MaxPerOracleUnexpiredBlobCumulativePayloadBytes: 9, - MaxPerOracleUnexpiredBlobCount: 10, + MaxKeyValueModifiedKeys: 4, + MaxKeyValueModifiedKeysPlusValuesBytes: 10 * 1024 * 1024, + MaxBlobPayloadBytes: 5 * 1024 * 1024, + MaxPerOracleUnexpiredBlobCumulativePayloadBytes: 100 * 1024 * 1024, + MaxPerOracleUnexpiredBlobCount: 1000, } } @@ -71,6 +71,31 @@ func TestDecode(t *testing.T) { got: withLimits(func(l *ReportingPluginLimits) { l.MaxObservationBytes = ocr3_1types.MaxMaxObservationBytes + 1 }), wantErr: "MaxObservationBytes", }, + { + name: "too few modified keys for the four writes", + got: withLimits(func(l *ReportingPluginLimits) { l.MaxKeyValueModifiedKeys = 3 }), + wantErr: "MaxKeyValueModifiedKeys", + }, + { + name: "too few key bytes for the four writes", + got: withLimits(func(l *ReportingPluginLimits) { l.MaxKeyValueModifiedKeysPlusValuesBytes = 1 }), + wantErr: "MaxKeyValueModifiedKeysPlusValuesBytes", + }, + { + name: "blob payload too small for one event", + got: withLimits(func(l *ReportingPluginLimits) { l.MaxBlobPayloadBytes = 1 }), + wantErr: "MaxBlobPayloadBytes", + }, + { + name: "no unexpired blobs allowed", + got: withLimits(func(l *ReportingPluginLimits) { l.MaxPerOracleUnexpiredBlobCount = 0 }), + wantErr: "MaxPerOracleUnexpiredBlobCount", + }, + { + name: "no unexpired blob payload allowed", + got: withLimits(func(l *ReportingPluginLimits) { l.MaxPerOracleUnexpiredBlobCumulativePayloadBytes = 0 }), + wantErr: "MaxPerOracleUnexpiredBlobCumulativePayloadBytes", + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -90,15 +115,15 @@ func TestDecode(t *testing.T) { require.NoError(t, err) want := ocr3_1types.ReportingPluginLimits{ MaxQueryBytes: 1, - MaxObservationBytes: 2, + MaxObservationBytes: 512 * 1024, MaxReportsPlusPrecursorBytes: 3, MaxReportBytes: 4, MaxReportCount: 5, - MaxKeyValueModifiedKeys: 6, - MaxKeyValueModifiedKeysPlusValuesBytes: 7, - MaxBlobPayloadBytes: 8, - MaxPerOracleUnexpiredBlobCumulativePayloadBytes: 9, - MaxPerOracleUnexpiredBlobCount: 10, + MaxKeyValueModifiedKeys: 4, + MaxKeyValueModifiedKeysPlusValuesBytes: 10 * 1024 * 1024, + MaxBlobPayloadBytes: 5 * 1024 * 1024, + MaxPerOracleUnexpiredBlobCumulativePayloadBytes: 100 * 1024 * 1024, + MaxPerOracleUnexpiredBlobCount: 1000, } require.Equal(t, want, got) }) diff --git a/core/services/ocr3_1/plugins/queue/queuepb/validate_test.go b/core/services/ocr3_1/plugins/queue/queuepb/validate_test.go new file mode 100644 index 00000000000..ea9e9522b74 --- /dev/null +++ b/core/services/ocr3_1/plugins/queue/queuepb/validate_test.go @@ -0,0 +1,112 @@ +package queuepb + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types" + + "github.com/smartcontractkit/chainlink/v2/core/services/ocr3_1/plugins/queue/queuelimits" +) + +func validOCRLimits() ocr3_1types.ReportingPluginLimits { + return ocr3_1types.ReportingPluginLimits{ + MaxObservationBytes: 512 * 1024, + MaxKeyValueModifiedKeys: queuelimits.NumKVKeys, + MaxKeyValueModifiedKeysPlusValuesBytes: 10 * 1024 * 1024, + MaxBlobPayloadBytes: 5 * 1024 * 1024, + MaxPerOracleUnexpiredBlobCount: 1000, + MaxPerOracleUnexpiredBlobCumulativePayloadBytes: 100 * 1024 * 1024, + } +} + +func TestValidateConfig(t *testing.T) { + t.Parallel() + + t.Run("valid", func(t *testing.T) { + t.Parallel() + require.NoError(t, ValidateConfig(validOCRLimits())) + }) + + minBlob := queuelimits.MaxEventFramingOverhead(queuelimits.CoordinatedEventsFieldNumber) + MinEventPayloadBytes + tests := []struct { + name string + mutate func(*ocr3_1types.ReportingPluginLimits) + wantErr string + }{ + { + name: "observation below one event", + mutate: func(l *ocr3_1types.ReportingPluginLimits) { + l.MaxObservationBytes = MinObservationBytes - 1 + }, + wantErr: "MaxObservationBytes", + }, + { + name: "fewer keys than written", + mutate: func(l *ocr3_1types.ReportingPluginLimits) { + l.MaxKeyValueModifiedKeys = queuelimits.NumKVKeys - 1 + }, + wantErr: "MaxKeyValueModifiedKeys", + }, + { + name: "kv bytes below the keys", + mutate: func(l *ocr3_1types.ReportingPluginLimits) { + l.MaxKeyValueModifiedKeysPlusValuesBytes = MinKeyValueModifiedKeysPlusValuesBytes - 1 + }, + wantErr: "MaxKeyValueModifiedKeysPlusValuesBytes", + }, + { + name: "blob payload below one event", + mutate: func(l *ocr3_1types.ReportingPluginLimits) { l.MaxBlobPayloadBytes = minBlob - 1 }, + wantErr: "MaxBlobPayloadBytes", + }, + { + name: "no unexpired blobs allowed", + mutate: func(l *ocr3_1types.ReportingPluginLimits) { l.MaxPerOracleUnexpiredBlobCount = 0 }, + wantErr: "MaxPerOracleUnexpiredBlobCount", + }, + { + name: "no unexpired blob payload allowed", + mutate: func(l *ocr3_1types.ReportingPluginLimits) { l.MaxPerOracleUnexpiredBlobCumulativePayloadBytes = 0 }, + wantErr: "MaxPerOracleUnexpiredBlobCumulativePayloadBytes", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + l := validOCRLimits() + tt.mutate(&l) + require.ErrorContains(t, ValidateConfig(l), tt.wantErr) + }) + } + + t.Run("boundaries are inclusive", func(t *testing.T) { + t.Parallel() + l := validOCRLimits() + l.MaxObservationBytes = MinObservationBytes + l.MaxKeyValueModifiedKeys = queuelimits.NumKVKeys + l.MaxKeyValueModifiedKeysPlusValuesBytes = MinKeyValueModifiedKeysPlusValuesBytes + l.MaxBlobPayloadBytes = minBlob + require.NoError(t, ValidateConfig(l)) + }) +} + +func TestValidateForDon(t *testing.T) { + t.Parallel() + + for _, don := range []struct{ n, f int }{{4, 1}, {7, 2}, {31, 10}} { + t.Run("observation must hold the blob handle reservation", func(t *testing.T) { + t.Parallel() + handleBytes := ocr3_1types.BlobHandleMarshalledBytesUpperBound(don.n, don.f) + minBytes := queuelimits.MaxBlobHandlesPerObservation*handleBytes + MinObservationBytes + + l := validOCRLimits() + l.MaxObservationBytes = minBytes + require.NoError(t, ValidateForDon(l, don.n, don.f), "exactly enough") + + l.MaxObservationBytes = minBytes - 1 + require.ErrorContains(t, ValidateForDon(l, don.n, don.f), "MaxObservationBytes") + }) + } +} diff --git a/deployment/cre/ocr3/ocr3_1/config.go b/deployment/cre/ocr3/ocr3_1/config.go index f616685333f..bf7024d42a3 100644 --- a/deployment/cre/ocr3/ocr3_1/config.go +++ b/deployment/cre/ocr3/ocr3_1/config.go @@ -11,6 +11,7 @@ import ( focr "github.com/smartcontractkit/chainlink-deployments-framework/offchain/ocr" "github.com/smartcontractkit/chainlink/deployment/cre/ocr3" + "github.com/smartcontractkit/chainlink/v2/core/services/ocr3_1/plugins/queue/queuepb" evm "github.com/smartcontractkit/chainlink-evm/pkg/relay" "github.com/smartcontractkit/chainlink/deployment" @@ -71,12 +72,14 @@ func genOCR3_1Config(cfg V3_1OracleConfig, identities []confighelper.OracleIdent return ocr3.OCR2OracleConfig{}, errors.New("OCRSecrets is required") } + var consensusQueue bool if cfgBytes == nil { pc, err := getPluginConfig(cfg) if err != nil { return ocr3.OCR2OracleConfig{}, err } if pc != nil { + _, consensusQueue = pc.(*ConsensusQueueOffchainConfig) cfgBytes, err = pc.Marshal() if err != nil { return ocr3.OCR2OracleConfig{}, fmt.Errorf("failed to marshal plugin config: %w", err) @@ -86,6 +89,21 @@ func genOCR3_1Config(cfg V3_1OracleConfig, identities []confighelper.OracleIdent if cfgBytes == nil { return ocr3.OCR2OracleConfig{}, errors.New("failed to get offchain config: one of reportingPluginConfigOverride, DKGOffchainConfig, VaultOffchainConfig or ConsensusQueueOffchainConfig is required") } + if consensusQueue { + // The node also checks this when it creates the plugin. Check it here so tooling cannot write a config the + // node will reject: the observation must hold the blob handles its DON needs. + decoded, err := queuepb.Decode(cfgBytes) + if err != nil { + return ocr3.OCR2OracleConfig{}, err + } + limits, err := decoded.OCRLimits() + if err != nil { + return ocr3.OCR2OracleConfig{}, err + } + if err := queuepb.ValidateForDon(limits, len(identities), cfg.MaxFaultyOracles); err != nil { + return ocr3.OCR2OracleConfig{}, fmt.Errorf("invalid consensus-queue limits: %w", err) + } + } prevConfigDigest, prevHistoryDigest, err := VerifyAndExtractOCR3_1Fields(cfg.PrevConfigDigest, cfg.PrevSeqNr, cfg.PrevHistoryDigest) if err != nil { diff --git a/deployment/cre/ocr3/ocr3_1/config_test.go b/deployment/cre/ocr3/ocr3_1/config_test.go index 2454a7d00f8..a3b4af4f1fa 100644 --- a/deployment/cre/ocr3/ocr3_1/config_test.go +++ b/deployment/cre/ocr3/ocr3_1/config_test.go @@ -7,6 +7,7 @@ import ( "sort" "strings" "testing" + "time" "github.com/ethereum/go-ethereum/common" "github.com/google/go-cmp/cmp" @@ -452,15 +453,15 @@ func Test_GenerateOCR3_1Config_ConsensusQueueOffchainConfig(t *testing.T) { cfg.ConsensusQueueOffchainConfig = &ConsensusQueueOffchainConfig{ Limits: ConsensusQueueLimits{ MaxQueryBytes: 1, - MaxObservationBytes: 2, + MaxObservationBytes: 512 * 1024, MaxReportsPlusPrecursorBytes: 3, MaxReportBytes: 4, MaxReportCount: 5, - MaxKeyValueModifiedKeys: 6, - MaxKeyValueModifiedKeysPlusValuesBytes: 7, - MaxBlobPayloadBytes: 8, - MaxPerOracleUnexpiredBlobCumulativePayloadBytes: 9, - MaxPerOracleUnexpiredBlobCount: 10, + MaxKeyValueModifiedKeys: 4, + MaxKeyValueModifiedKeysPlusValuesBytes: 10 * 1024 * 1024, + MaxBlobPayloadBytes: 5 * 1024 * 1024, + MaxPerOracleUnexpiredBlobCumulativePayloadBytes: 100 * 1024 * 1024, + MaxPerOracleUnexpiredBlobCount: 1000, }, } @@ -474,15 +475,15 @@ func Test_GenerateOCR3_1Config_ConsensusQueueOffchainConfig(t *testing.T) { require.NoError(t, err) wantLimits := ocr3_1types.ReportingPluginLimits{ MaxQueryBytes: 1, - MaxObservationBytes: 2, + MaxObservationBytes: 512 * 1024, MaxReportsPlusPrecursorBytes: 3, MaxReportBytes: 4, MaxReportCount: 5, - MaxKeyValueModifiedKeys: 6, - MaxKeyValueModifiedKeysPlusValuesBytes: 7, - MaxBlobPayloadBytes: 8, - MaxPerOracleUnexpiredBlobCumulativePayloadBytes: 9, - MaxPerOracleUnexpiredBlobCount: 10, + MaxKeyValueModifiedKeys: 4, + MaxKeyValueModifiedKeysPlusValuesBytes: 10 * 1024 * 1024, + MaxBlobPayloadBytes: 5 * 1024 * 1024, + MaxPerOracleUnexpiredBlobCumulativePayloadBytes: 100 * 1024 * 1024, + MaxPerOracleUnexpiredBlobCount: 1000, } if diff := cmp.Diff(wantLimits, gotLimits); diff != "" { t.Errorf("encoded limits mismatch (-want +got):\n%s", diff) @@ -497,19 +498,34 @@ func Test_GenerateOCR3_1Config_ConsensusQueueOffchainConfig(t *testing.T) { got, err := decoded.OCRLimits() require.NoError(t, err) + // Sized for a one second round: event lifetime (10m timeout + 1m grace + 30s minimum) is 690 rounds, + // plus 60 rounds of reaping slack. Ten blobs per round, and 1 MiB of payload per round. want := ocr3_1types.ReportingPluginLimits{ MaxObservationBytes: 512 * 1024, MaxKeyValueModifiedKeys: 4, MaxKeyValueModifiedKeysPlusValuesBytes: 10 * 1024 * 1024, MaxBlobPayloadBytes: 5 * 1024 * 1024, - MaxPerOracleUnexpiredBlobCumulativePayloadBytes: 100 * 1024 * 1024, - MaxPerOracleUnexpiredBlobCount: 100, + MaxPerOracleUnexpiredBlobCumulativePayloadBytes: 786_432_000, + MaxPerOracleUnexpiredBlobCount: 7_500, } if diff := cmp.Diff(want, got); diff != "" { t.Errorf("default limits mismatch (-want +got):\n%s", diff) } }) + t.Run("blob quotas scale with the round interval", func(t *testing.T) { + // Faster rounds keep proportionally more blobs unexpired for the same event lifetime. + fast := DefaultConsensusQueueOffchainConfigForRoundInterval(200 * time.Millisecond) + slow := DefaultConsensusQueueOffchainConfigForRoundInterval(time.Second) + require.Greater(t, fast.Limits.MaxPerOracleUnexpiredBlobCount, slow.Limits.MaxPerOracleUnexpiredBlobCount) + require.Greater(t, fast.Limits.MaxPerOracleUnexpiredBlobCumulativePayloadBytes, + slow.Limits.MaxPerOracleUnexpiredBlobCumulativePayloadBytes) + + // 690s lifetime is 3450 rounds at 200ms, plus 300 rounds of reaping slack. + require.Equal(t, uint32(37_500), fast.Limits.MaxPerOracleUnexpiredBlobCount) + require.Equal(t, uint32(3_932_160_000), fast.Limits.MaxPerOracleUnexpiredBlobCumulativePayloadBytes) + }) + t.Run("invalid limits fail to marshal", func(t *testing.T) { cfg2 := cfg cfg2.ConsensusQueueOffchainConfig = DefaultConsensusQueueOffchainConfig() @@ -518,6 +534,15 @@ func Test_GenerateOCR3_1Config_ConsensusQueueOffchainConfig(t *testing.T) { require.ErrorContains(t, err, "MaxKeyValueModifiedKeys") }) + t.Run("observation too small for the DON is rejected", func(t *testing.T) { + cfg2 := cfg + cfg2.ConsensusQueueOffchainConfig = DefaultConsensusQueueOffchainConfig() + // This passes the config-only floors but cannot hold the blob handles the DON's N and F require. + cfg2.ConsensusQueueOffchainConfig.Limits.MaxObservationBytes = 1024 + _, err := GenerateOCR3_1ConfigFromNodes(cfg2, nodes, chain_selectors.ETHEREUM_TESTNET_SEPOLIA.Selector, ocr.XXXGenerateTestOCRSecrets(), nil, nil) + require.ErrorContains(t, err, "MaxObservationBytes") + }) + t.Run("both ConsensusQueueOffchainConfig and VaultOffchainConfig returns error", func(t *testing.T) { cfg2 := cfg cfg2.VaultOffchainConfig = &VaultOffchainConfig{} diff --git a/deployment/cre/ocr3/ocr3_1/oracle_config.go b/deployment/cre/ocr3/ocr3_1/oracle_config.go index b082f0cb7ce..047a005e171 100644 --- a/deployment/cre/ocr3/ocr3_1/oracle_config.go +++ b/deployment/cre/ocr3/ocr3_1/oracle_config.go @@ -4,12 +4,15 @@ import ( "encoding/hex" "errors" "fmt" + "time" "github.com/smartcontractkit/smdkg/dkgocr/dkgocrtypes" "google.golang.org/protobuf/proto" "github.com/smartcontractkit/chainlink-common/pkg/capabilities/actions/vault" + "github.com/smartcontractkit/chainlink-common/pkg/settings/cresettings" + "github.com/smartcontractkit/chainlink/v2/core/services/ocr3_1/plugins/queue/queuelimits" "github.com/smartcontractkit/chainlink/v2/core/services/ocr3_1/plugins/queue/queuepb" ) @@ -129,24 +132,50 @@ type ConsensusQueueLimits struct { MaxPerOracleUnexpiredBlobCount uint32 `yaml:"maxPerOracleUnexpiredBlobCount" json:"maxPerOracleUnexpiredBlobCount"` } -// DefaultConsensusQueueOffchainConfig returns starting limits for a consensus-queue DON. -// The plugin broadcasts trigger events as blobs, so the blob quotas hold every blob in a full observation, -// and it writes a fixed handful of KV keys per round. -// The plugin has no queries or reports, so those limits are zero. +// consensusQueueReferenceBlobPayloadPerRound is the sustained blob payload the default per-oracle quota is sized +// for: a full observation of the calibration's ~1 KiB (EVM log) events each round. The config field is a uint32, so +// the plugin's worst case (MaxBlobHandlesPerObservation full blobs every round for the whole event lifetime) cannot +// be expressed. DONs that sustain larger trigger payloads must raise MaxPerOracleUnexpiredBlobCumulativePayloadBytes. +const consensusQueueReferenceBlobPayloadPerRound = 1 << 20 + +// DefaultConsensusQueueOffchainConfigForRoundInterval returns starting limits for a consensus-queue DON whose OCR +// DeltaRound is roundDur. +// +// The plugin broadcasts trigger events as blobs and keeps them until their events expire, which is the workflow's +// TriggerEventQueueTimeout plus the consensus-queue expiration grace. The blob quotas must therefore cover every blob +// a node can broadcast over that lifetime: a fixed default is wrong for a DON whose rounds are faster or slower than +// the one it was sized for. The plugin has no queries or reports, so those limits are zero, and it writes a fixed +// handful of KV keys per round. +// +// The sizes use the default TriggerEventQueueTimeout and ConsensusQueueExpirationGraceInterval. A node or workflow +// that raises either keeps blobs longer, so a DON using larger values needs a proportionally larger quota. +// // The node never applies defaults itself. Different node versions would otherwise disagree under the same digest. -func DefaultConsensusQueueOffchainConfig() *ConsensusQueueOffchainConfig { +func DefaultConsensusQueueOffchainConfigForRoundInterval(roundDur time.Duration) *ConsensusQueueOffchainConfig { + blobCount, blobPayloadBytes := queuelimits.BlobQuota( + roundDur, + cresettings.Default.PerWorkflow.TriggerEventQueueTimeout.DefaultValue, + cresettings.Default.ConsensusQueueExpirationGraceInterval.DefaultValue, + consensusQueueReferenceBlobPayloadPerRound, + ) return &ConsensusQueueOffchainConfig{ Limits: ConsensusQueueLimits{ MaxObservationBytes: 512 * 1024, MaxKeyValueModifiedKeys: 4, MaxKeyValueModifiedKeysPlusValuesBytes: 10 * 1024 * 1024, MaxBlobPayloadBytes: 5 * 1024 * 1024, - MaxPerOracleUnexpiredBlobCumulativePayloadBytes: 100 * 1024 * 1024, - MaxPerOracleUnexpiredBlobCount: 100, + MaxPerOracleUnexpiredBlobCumulativePayloadBytes: blobPayloadBytes, + MaxPerOracleUnexpiredBlobCount: blobCount, }, } } +// DefaultConsensusQueueOffchainConfig returns the starting limits for a one second DeltaRound, a common default. +// Use DefaultConsensusQueueOffchainConfigForRoundInterval when the DON's DeltaRound is known to be different. +func DefaultConsensusQueueOffchainConfig() *ConsensusQueueOffchainConfig { + return DefaultConsensusQueueOffchainConfigForRoundInterval(time.Second) +} + // Marshal encodes the config as a queuepb.ReportingPluginConfig. // Returns an error if the limits would be rejected by the node (see queuepb.Decode). func (c *ConsensusQueueOffchainConfig) Marshal() ([]byte, error) { diff --git a/system-tests/lib/cre/features/queue/queue.go b/system-tests/lib/cre/features/queue/queue.go index 8bf24c0d76e..3ae7f48f17a 100644 --- a/system-tests/lib/cre/features/queue/queue.go +++ b/system-tests/lib/cre/features/queue/queue.go @@ -3,6 +3,7 @@ package queue import ( "context" "fmt" + "time" "github.com/rs/zerolog" @@ -39,7 +40,8 @@ func (o *ConsensusQueue) PreEnvStartup( // The plugin reads its OCR limits only from the plugin config inside the registry's OCR config. ocrConfig := contracts.DefaultOCR3_1Config(len(workers)) - ocrConfig.ConsensusQueueOffchainConfig = ocr3_1.DefaultConsensusQueueOffchainConfig() + ocrConfig.ConsensusQueueOffchainConfig = ocr3_1.DefaultConsensusQueueOffchainConfigForRoundInterval( + time.Duration(ocrConfig.DeltaRoundMillis) * time.Millisecond) return &cre.PreEnvStartupOutput{ DONCapabilityWithConfig: []keystone_changeset.DONCapabilityWithConfig{{