diff --git a/core/cmd/shell.go b/core/cmd/shell.go
index cc5c7bf3974..698cf90f738 100644
--- a/core/cmd/shell.go
+++ b/core/cmd/shell.go
@@ -62,6 +62,7 @@ import (
"github.com/smartcontractkit/chainlink/v2/core/services/llo"
ocr3beholderwrapper "github.com/smartcontractkit/chainlink/v2/core/services/ocr3/beholderwrapper"
ocr3_1beholderwrapper "github.com/smartcontractkit/chainlink/v2/core/services/ocr3_1/beholderwrapper"
+ consensusqueue "github.com/smartcontractkit/chainlink/v2/core/services/ocr3_1/plugins/queue"
"github.com/smartcontractkit/chainlink/v2/core/services/periodicbackup"
"github.com/smartcontractkit/chainlink/v2/core/services/pg"
"github.com/smartcontractkit/chainlink/v2/core/services/versioning"
@@ -85,6 +86,7 @@ func metricViews() []sdkmetric.View {
ccvcommon.MetricViews(),
ocr3beholderwrapper.MetricViews(),
ocr3_1beholderwrapper.MetricViews(),
+ consensusqueue.MetricViews(),
gatewaynetwork.HTTPClientMetricViews(),
gatewaynetwork.WSConnectionMetricViews(),
gatewaymonitoring.MetricViews(),
diff --git a/core/scripts/go.mod b/core/scripts/go.mod
index 900f1894445..702a28e53dc 100644
--- a/core/scripts/go.mod
+++ b/core/scripts/go.mod
@@ -29,7 +29,7 @@ require (
github.com/shopspring/decimal v1.4.0
github.com/smartcontractkit/chain-selectors v1.0.112
github.com/smartcontractkit/chainlink-ccip/chains/evm v0.0.0-20261001213322-a2d686f610ca
- github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123132302-3db945c721d8
+ github.com/smartcontractkit/chainlink-common v0.11.2-0.20261124133622-53ca4463ec7d
github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb
github.com/smartcontractkit/chainlink-deployments-framework v0.126.0
github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261118192309-cfc3cc2381a2
diff --git a/core/scripts/go.sum b/core/scripts/go.sum
index 0a364521caf..442fb24b012 100644
--- a/core/scripts/go.sum
+++ b/core/scripts/go.sum
@@ -1696,8 +1696,8 @@ github.com/smartcontractkit/chainlink-ccip/deployment v0.0.0-20261001213322-a2d6
github.com/smartcontractkit/chainlink-ccip/deployment v0.0.0-20261001213322-a2d686f610ca/go.mod h1:Dm/Abz0vr7F2v9TygUX947q8HIwJEJikDfSdanX1Cic=
github.com/smartcontractkit/chainlink-ccv v0.16.0 h1:WhDQEEI2Kb5A4C0PNAa+nyGLDvG0H+uT6h4y1NwmkYg=
github.com/smartcontractkit/chainlink-ccv v0.16.0/go.mod h1:oaSLVHiJVbJ9aCcUQnoRuVONACWzA/DWVqvUnLAe9bE=
-github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123132302-3db945c721d8 h1:/Ha7GrK/2S2L6sXECIX4oreW8OlNDzNQ0SEOLhddftA=
-github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123132302-3db945c721d8/go.mod h1:Gv+qglZ5Kxtf4pvpYIx/FBbntZDuvxVH0a6zFNuG+e8=
+github.com/smartcontractkit/chainlink-common v0.11.2-0.20261124133622-53ca4463ec7d h1:hG4yKbTSx2vKuWz8Poy1R9FIGLSVbeND22NGEmYQ+HM=
+github.com/smartcontractkit/chainlink-common v0.11.2-0.20261124133622-53ca4463ec7d/go.mod h1:Gv+qglZ5Kxtf4pvpYIx/FBbntZDuvxVH0a6zFNuG+e8=
github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb h1:9rVrSeVOAwZsVe2pOpeVRp9XjhtMyjndgeROFglvOhg=
github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb/go.mod h1:WcOKzF6HkTDrkQ96aBHhcJ2IIYE7iK7M2tdt58ea2qc=
github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261119075727-f272852ab605 h1:8NbHKcKLqMf6EgVJz8Tejf/qbLFtlIopnEdKnrR2U2s=
diff --git a/core/services/chainlink/application.go b/core/services/chainlink/application.go
index e8f67d3d1ae..b664dd51bd1 100644
--- a/core/services/chainlink/application.go
+++ b/core/services/chainlink/application.go
@@ -845,6 +845,9 @@ func NewApplication(ctx context.Context, opts ApplicationOpts) (Application, err
OrgResolver: creServices.OrgResolver,
LimitsFactory: limitsFactory,
OCRConfigService: creServices.OCRConfigService,
+ TriggerCoordinator: creServices.TriggerCoordinator,
+ TriggerQueue: creServices.TriggerQueue,
+ Meter: meter,
DefaultBootstrappers: safeDefaultBootstrappers(cfg),
CapRegistryAddress: safeExternalRegistryAddress(cfg),
CapRegistryChainID: safeExternalRegistryChainID(cfg),
diff --git a/core/services/cre/cre.go b/core/services/cre/cre.go
index 6546697af81..7542560d755 100644
--- a/core/services/cre/cre.go
+++ b/core/services/cre/cre.go
@@ -76,6 +76,10 @@ import (
"github.com/smartcontractkit/chainlink/v2/core/static"
)
+// completedExecutionRetentionMargin is added to the longest event lifetime to decide how long to remember completed
+// executions. It allows for clock skew between nodes, as an event's agreed deadline is a median of theirs.
+const completedExecutionRetentionMargin = time.Minute
+
// Keystore is the minimal interface needed from keystore for CRE
type Keystore interface {
CSA() keystore.CSA
@@ -135,6 +139,10 @@ type Services struct {
WorkflowRegistrySyncer syncerV2.WorkflowRegistrySyncer
+ TriggerCoordinator triggers.Coordinator
+
+ TriggerQueue triggers.Queue
+
OrgResolver orgresolver.OrgResolver
OCRConfigService capregconfig.OCRConfigService
@@ -297,7 +305,7 @@ func (s *Services) newSubservices(
wfSyncerLggr.Infof("failed to create billing client: %s", err)
}
- wfSyncer, wfSyncerSrvcs, err := newWorkflowRegistrySyncerV2(
+ wfSyncer, triggerCoordinator, triggerQueue, wfSyncerSrvcs, err := newWorkflowRegistrySyncerV2(
cfg,
relayerChainInterops,
billingClient,
@@ -320,6 +328,8 @@ func (s *Services) newSubservices(
}
s.BillingClient = billingClient
s.WorkflowRegistrySyncer = wfSyncer
+ s.TriggerCoordinator = triggerCoordinator
+ s.TriggerQueue = triggerQueue
srvs = append(srvs, wfSyncerSrvcs...)
return srvs, nil
@@ -800,14 +810,14 @@ func newWorkflowRegistrySyncerV2(
meterIdentity resourcemanager.ResourceIdentity,
dispatcher remotetypes.Dispatcher,
shardIndexMapper *shardownership.ShardIndexMapper,
-) (syncerV2.WorkflowRegistrySyncer, []commonsrv.Service, error) {
+) (syncerV2.WorkflowRegistrySyncer, triggers.Coordinator, triggers.Queue, []commonsrv.Service, error) {
capCfg := cfg.Capabilities()
wfReg := capCfg.WorkflowRegistry()
key := opts.WorkflowKey
fetcherFunc, retrieverFunc, srvcs, err := newFetcherServiceV2(opts, capCfg, lggr, gatewayConnectorWrapper)
if err != nil {
- return nil, nil, err
+ return nil, nil, nil, nil, err
}
artifactsStore, err := artifactsV2.NewStore(
@@ -824,29 +834,29 @@ func newWorkflowRegistrySyncerV2(
}),
)
if err != nil {
- return nil, nil, fmt.Errorf("unable to create artifact store: %w", err)
+ return nil, nil, nil, nil, fmt.Errorf("unable to create artifact store: %w", err)
}
engineRegistry := syncerV2.NewEngineRegistry()
engineLimiters, err := v2.NewLimiters(lf, nil)
if err != nil {
- return nil, nil, fmt.Errorf("could not instantiate engine limiters: %w", err)
+ return nil, nil, nil, nil, fmt.Errorf("could not instantiate engine limiters: %w", err)
}
featureFlags, err := v2.NewFeatureFlags(lf, nil)
if err != nil {
- return nil, nil, fmt.Errorf("could not instantiate engine feature flags: %w", err)
+ return nil, nil, nil, nil, fmt.Errorf("could not instantiate engine feature flags: %w", err)
}
selector, err := chainSelector(wfReg.ChainID(), wfReg.NetworkID())
if err != nil {
- return nil, nil, err
+ return nil, nil, nil, nil, err
}
crFactory, err := newContractReaderFactory(capCfg, relayerChainInterops)
if err != nil {
- return nil, nil, fmt.Errorf("failed to instantiate contract reader factory: %w", err)
+ return nil, nil, nil, nil, fmt.Errorf("failed to instantiate contract reader factory: %w", err)
}
var shardOrchestratorClient shardorchestrator.ClientInterface
@@ -855,7 +865,7 @@ func newWorkflowRegistrySyncerV2(
} else {
c, clientErr := newShardOrchestratorClient(cfg, lggr)
if clientErr != nil {
- return nil, nil, clientErr
+ return nil, nil, nil, nil, clientErr
}
if c != nil {
shardOrchestratorClient = c
@@ -902,24 +912,27 @@ func newWorkflowRegistrySyncerV2(
coordinatorMetrics, err := wfmonitoring.InitMonitoringResources()
if err != nil {
- return nil, nil, fmt.Errorf("unable to init trigger coordinator metrics: %w", err)
+ return nil, nil, nil, nil, fmt.Errorf("unable to init trigger coordinator metrics: %w", err)
}
centralQueueMetrics, err := wfmonitoring.InitCentralTriggerQueueMetrics()
if err != nil {
- return nil, nil, fmt.Errorf("unable to init central trigger queue metrics: %w", err)
+ return nil, nil, nil, nil, fmt.Errorf("unable to init central trigger queue metrics: %w", err)
}
drainerMetrics, err := wfmonitoring.InitTriggerDrainerMetrics()
if err != nil {
- return nil, nil, fmt.Errorf("unable to init central trigger queue drainer metrics: %w", err)
+ return nil, nil, nil, nil, fmt.Errorf("unable to init central trigger queue drainer metrics: %w", err)
}
coordinatorClock := clockwork.NewRealClock()
// Shadow mode copies coordinated trigger events to the central queue while
// FeatureShadowTriggerModeActivePeriod is open. The copies are for observation only.
- // The drainer logs and discards them, and each event still executes on its workflow's own queue.
+ // The drainer logs and discards them, and each event still executes on its workflow's own queue. The coordinator
+ // also logs instead of starting an event in that window when consensus on the queue chooses it. While the consensus
+ // queue plugin is reading the queue, the drainer leaves the events to it and only drops those that have expired.
+ eventLifetime := triggers.NewEventLifetime(triggers.ConsensusQueueExpirationGrace(lf))
centralQueue := triggers.NewQueue(engineLimiters.CentralTriggerEventQueue,
wfmonitoring.NewCentralTriggerQueueMetricLabeler(commonmetrics.NewLabeler(), centralQueueMetrics), lggr)
- centralQueueDrainer := triggers.NewCentralQueueDrainer(centralQueue, engineLimiters.CentralTriggerQueueDrainInterval,
+ centralQueueDrainer := triggers.NewCentralQueueDrainer(centralQueue, triggers.ConsensusQueueExpirationGrace(lf), engineLimiters.CentralTriggerQueueDrainInterval,
wfmonitoring.NewTriggerDrainerMetricLabeler(commonmetrics.NewLabeler(), drainerMetrics), coordinatorClock, lggr)
triggerCoordinator := triggers.NewCoordinator(
triggers.RegisterDeps{
@@ -935,6 +948,8 @@ func newWorkflowRegistrySyncerV2(
coordinatorClock,
triggers.WithShadowMode(centralQueue, engineLimiters.ShadowTriggerMode),
triggers.WithDrainer(centralQueueDrainer),
+ triggers.WithExpirationGrace(triggers.ConsensusQueueExpirationGrace(lf)),
+ triggers.WithEventLifetime(eventLifetime),
)
handlerOpts := []syncerV2.EventHandlerOption{
@@ -971,7 +986,7 @@ func newWorkflowRegistrySyncerV2(
})
specMeter, smErr := syncerV2.NewSpecMeter(lggr, rm, meterIdentity, artifactsStore, orgResolver)
if smErr != nil {
- return nil, nil, fmt.Errorf("unable to create workflow spec meter: %w", smErr)
+ return nil, nil, nil, nil, fmt.Errorf("unable to create workflow spec meter: %w", smErr)
}
handlerOpts = append(handlerOpts, syncerV2.WithSpecMeter(specMeter))
}
@@ -992,7 +1007,7 @@ func newWorkflowRegistrySyncerV2(
if diskMonitorEnabled {
fileStore, fsErr := artifactsV2.NewFileModuleStore(mc.CacheDir(), cacheEnabled)
if fsErr != nil {
- return nil, nil, fmt.Errorf("unable to create file module store: %w", fsErr)
+ return nil, nil, nil, nil, fmt.Errorf("unable to create file module store: %w", fsErr)
}
dm, dmErr := syncerV2.NewWorkflowModuleCacheDiskMonitor(
@@ -1001,7 +1016,7 @@ func newWorkflowRegistrySyncerV2(
syncerV2.WorkflowModuleCacheDiskMonitorTickInterval,
)
if dmErr != nil {
- return nil, nil, fmt.Errorf("unable to create module cache disk monitor: %w", dmErr)
+ return nil, nil, nil, nil, fmt.Errorf("unable to create module cache disk monitor: %w", dmErr)
}
srvcs = append(srvcs, dm)
@@ -1010,7 +1025,7 @@ func newWorkflowRegistrySyncerV2(
if cacheEnabled {
cm, cmErr := syncerV2.NewCacheMetrics()
if cmErr != nil {
- return nil, nil, fmt.Errorf("unable to create module cache metrics: %w", cmErr)
+ return nil, nil, nil, nil, fmt.Errorf("unable to create module cache metrics: %w", cmErr)
}
var idleTimeout time.Duration
@@ -1041,9 +1056,15 @@ func newWorkflowRegistrySyncerV2(
}
}
+ // An event can be queued again (by nodes that were late to see it) until it expires, and the store is what tells the
+ // engine that such an event already ran. So it must remember executions for at least that long.
+ workflowStore := workflowstore.NewInMemoryStore(lggr, clockwork.NewRealClock())
+ workflowStore.SetMinimumCompletedRetention(func() time.Duration {
+ return eventLifetime.Longest(context.Background()) + completedExecutionRetentionMargin
+ })
eventHandler, err := syncerV2.NewEventHandler(
lggr,
- workflowstore.NewInMemoryStore(lggr, clockwork.NewRealClock()),
+ workflowStore,
dontimeStore,
opts.UseLocalTimeProvider,
opts.CapabilitiesRegistry,
@@ -1060,7 +1081,7 @@ func newWorkflowRegistrySyncerV2(
handlerOpts...,
)
if err != nil {
- return nil, nil, fmt.Errorf("unable to create workflow registry event handler: %w", err)
+ return nil, nil, nil, nil, fmt.Errorf("unable to create workflow registry event handler: %w", err)
}
addSources := wfReg.AdditionalSources()
@@ -1113,12 +1134,12 @@ func newWorkflowRegistrySyncerV2(
registryOpts...,
)
if err != nil {
- return nil, nil, fmt.Errorf("unable to create workflow registry syncer: %w", err)
+ return nil, nil, nil, nil, fmt.Errorf("unable to create workflow registry syncer: %w", err)
}
srvcs = append(srvcs, workflowRegistrySyncerV2)
lggr.Debugw("Created WorkflowRegistrySyncer V2")
- return workflowRegistrySyncerV2, srvcs, nil
+ return workflowRegistrySyncerV2, triggerCoordinator, centralQueue, srvcs, nil
}
// NewServices creates and initializes all CRE services
diff --git a/core/services/ocr2/delegate.go b/core/services/ocr2/delegate.go
index 67c69ed5e83..c63698d9020 100644
--- a/core/services/ocr2/delegate.go
+++ b/core/services/ocr2/delegate.go
@@ -17,6 +17,7 @@ import (
"github.com/jonboulle/clockwork"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
+ "go.opentelemetry.io/otel/metric"
"google.golang.org/grpc"
"gopkg.in/guregu/null.v4"
@@ -83,6 +84,7 @@ import (
"github.com/smartcontractkit/chainlink/v2/core/services/synchronization"
"github.com/smartcontractkit/chainlink/v2/core/services/telemetry"
syncerV2 "github.com/smartcontractkit/chainlink/v2/core/services/workflows/syncer/v2"
+ "github.com/smartcontractkit/chainlink/v2/core/services/workflows/v2/triggers"
"github.com/smartcontractkit/chainlink/v2/core/utils"
"github.com/smartcontractkit/chainlink/v2/plugins"
)
@@ -156,6 +158,9 @@ type Delegate struct {
OrgResolver orgresolver.OrgResolver
limitsFactory limits.Factory
ocrConfigService capregconfig.OCRConfigService
+ triggerCoordinator triggers.Coordinator
+ triggerQueue triggers.Queue
+ meter metric.Meter
// Registry-driven launch support: when the delegate is used via
// LocalCapabilityManager (no job spec), these fields provide the
@@ -309,6 +314,10 @@ type DelegateOpts struct {
OrgResolver orgresolver.OrgResolver
LimitsFactory limits.Factory
OCRConfigService capregconfig.OCRConfigService
+ TriggerCoordinator triggers.Coordinator
+ TriggerQueue triggers.Queue
+ // Meter creates the plugins' metrics.
+ Meter metric.Meter
// Registry-driven launch support: defaults for capabilities launched
// via LocalCapabilityManager (no job spec).
@@ -358,6 +367,9 @@ func NewDelegate(
OrgResolver: opts.OrgResolver,
limitsFactory: opts.LimitsFactory,
ocrConfigService: opts.OCRConfigService,
+ triggerCoordinator: opts.TriggerCoordinator,
+ triggerQueue: opts.TriggerQueue,
+ meter: opts.Meter,
defaultBootstrappers: opts.DefaultBootstrappers,
capRegistryAddress: opts.CapRegistryAddress,
capRegistryChainID: opts.CapRegistryChainID,
@@ -904,7 +916,7 @@ func (d *Delegate) newServicesConsensusQueue(
BinaryNetworkEndpointFactory: d.peerWrapper.Peer3_1,
V2Bootstrappers: bootstrapPeers,
ContractConfigTracker: configTracker,
- ContractTransmitter: queue.NewTransmitter(lggr, ocrtypes.Account(spec.TransmitterID.String)),
+ ContractTransmitter: queue.NewTransmitter(ocrtypes.Account(spec.TransmitterID.String)),
Database: ocrDB,
KeyValueDatabaseFactory: kvFactory,
LocalConfig: lc,
@@ -916,12 +928,12 @@ func (d *Delegate) newServicesConsensusQueue(
MetricsRegisterer: prometheus.WrapRegistererWith(map[string]string{"job_name": jb.Name.ValueOrZero()}, prometheus.DefaultRegisterer),
}
- rpf, err := queue.NewConsensusQueuePluginFactory(lggr, d.limitsFactory)
+ rpf, err := queue.NewConsensusQueuePluginFactory(lggr, d.limitsFactory, d.triggerCoordinator, d.triggerQueue, d.meter)
if err != nil {
return nil, err
}
- wrappedRpf := beholderwrapper.NewReportingPluginFactory(rpf, lggr, string(types.ConsensusQueue))
+ wrappedRpf := beholderwrapper.NewReportingPluginFactory(rpf, lggr, string(types.ConsensusQueue), d.meter)
oracleArgs.ReportingPluginFactory = wrappedRpf
oracle, err := libocr2.NewOracle(oracleArgs)
@@ -1124,6 +1136,7 @@ func (d *Delegate) newServicesVaultPlugin(
rpf,
lggr,
"vault",
+ d.meter,
)
oracleArgs.ReportingPluginFactory = wrappedRpf
diff --git a/core/services/ocr3_1/beholderwrapper/factory.go b/core/services/ocr3_1/beholderwrapper/factory.go
index e8708fb4583..ff8f1e8c0ba 100644
--- a/core/services/ocr3_1/beholderwrapper/factory.go
+++ b/core/services/ocr3_1/beholderwrapper/factory.go
@@ -4,6 +4,8 @@ import (
"context"
"fmt"
+ "go.opentelemetry.io/otel/metric"
+
"github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types"
"github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types"
@@ -16,17 +18,20 @@ type ReportingPluginFactory[RI any] struct {
wrapped ocr3_1types.ReportingPluginFactory[RI]
lggr logger.Logger
plugin string
+ meter metric.Meter
}
func NewReportingPluginFactory[RI any](
wrapped ocr3_1types.ReportingPluginFactory[RI],
lggr logger.Logger,
plugin string,
+ meter metric.Meter,
) *ReportingPluginFactory[RI] {
return &ReportingPluginFactory[RI]{
wrapped: wrapped,
lggr: lggr,
plugin: plugin,
+ meter: meter,
}
}
@@ -35,7 +40,7 @@ func (r ReportingPluginFactory[RI]) NewReportingPlugin(ctx context.Context, conf
if err != nil {
return nil, nil, err
}
- return wrapPlugin(r.lggr, r.plugin, config, plugin, info)
+ return wrapPlugin(r.lggr, r.meter, r.plugin, config, plugin, info)
}
var _ ocr3_1types.ReportingPluginFactory2[any] = &ReportingPluginFactory2[any]{}
@@ -45,17 +50,20 @@ type ReportingPluginFactory2[RI any] struct {
wrapped ocr3_1types.ReportingPluginFactory2[RI]
lggr logger.Logger
plugin string
+ meter metric.Meter
}
func NewReportingPluginFactory2[RI any](
wrapped ocr3_1types.ReportingPluginFactory2[RI],
lggr logger.Logger,
plugin string,
+ meter metric.Meter,
) *ReportingPluginFactory2[RI] {
return &ReportingPluginFactory2[RI]{
wrapped: wrapped,
lggr: lggr,
plugin: plugin,
+ meter: meter,
}
}
@@ -64,11 +72,11 @@ func (r ReportingPluginFactory2[RI]) NewReportingPlugin(ctx context.Context, con
if err != nil {
return nil, nil, err
}
- return wrapPlugin(r.lggr, r.plugin, config, plugin, info)
+ return wrapPlugin(r.lggr, r.meter, r.plugin, config, plugin, info)
}
-func wrapPlugin[RI any](lggr logger.Logger, name string, config ocr3types.ReportingPluginConfig, plugin ocr3_1types.ReportingPlugin[RI], info ocr3_1types.ReportingPluginInfo) (ocr3_1types.ReportingPlugin[RI], ocr3_1types.ReportingPluginInfo, error) {
- metrics, err := newPluginMetrics(name, config.ConfigDigest.String())
+func wrapPlugin[RI any](lggr logger.Logger, meter metric.Meter, name string, config ocr3types.ReportingPluginConfig, plugin ocr3_1types.ReportingPlugin[RI], info ocr3_1types.ReportingPluginInfo) (ocr3_1types.ReportingPlugin[RI], ocr3_1types.ReportingPluginInfo, error) {
+ metrics, err := newPluginMetrics(meter, name, config.ConfigDigest.String())
if err != nil {
return nil, nil, fmt.Errorf("failed to create plugin metrics: %w", err)
}
diff --git a/core/services/ocr3_1/beholderwrapper/factory_test.go b/core/services/ocr3_1/beholderwrapper/factory_test.go
index 50831e7ec3c..a799b2bfdce 100644
--- a/core/services/ocr3_1/beholderwrapper/factory_test.go
+++ b/core/services/ocr3_1/beholderwrapper/factory_test.go
@@ -6,6 +6,7 @@ import (
"testing"
"github.com/stretchr/testify/require"
+ "go.opentelemetry.io/otel/metric/noop"
"github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types"
"github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types"
@@ -19,11 +20,13 @@ func Test_WrapperFactory(t *testing.T) {
&fakeFactory[uint]{},
logger.TestLogger(t),
"plugin",
+ noop.NewMeterProvider().Meter("test"),
)
failingFactory := NewReportingPluginFactory(
&fakeFactory[uint]{err: errors.New("error")},
logger.TestLogger(t),
"plugin",
+ noop.NewMeterProvider().Meter("test"),
)
plugin, _, err := validFactory.NewReportingPlugin(t.Context(), ocr3types.ReportingPluginConfig{}, nil)
@@ -52,8 +55,8 @@ func Test_WrapperFactory2(t *testing.T) {
kv := fakeReadOnlyKV{}
inner := &fakeFactory2[uint]{}
- validFactory := NewReportingPluginFactory2(inner, logger.TestLogger(t), "plugin")
- failingFactory := NewReportingPluginFactory2(&fakeFactory2[uint]{err: errors.New("error")}, logger.TestLogger(t), "plugin")
+ validFactory := NewReportingPluginFactory2(inner, logger.TestLogger(t), "plugin", noop.NewMeterProvider().Meter("test"))
+ failingFactory := NewReportingPluginFactory2(&fakeFactory2[uint]{err: errors.New("error")}, logger.TestLogger(t), "plugin", noop.NewMeterProvider().Meter("test"))
plugin, _, err := validFactory.NewReportingPlugin(t.Context(), ocr3types.ReportingPluginConfig{}, nil, kv)
require.NoError(t, err)
diff --git a/core/services/ocr3_1/beholderwrapper/plugin.go b/core/services/ocr3_1/beholderwrapper/plugin.go
index 85babf2d75b..3076fb2d024 100644
--- a/core/services/ocr3_1/beholderwrapper/plugin.go
+++ b/core/services/ocr3_1/beholderwrapper/plugin.go
@@ -112,6 +112,8 @@ func (p *reportingPlugin[RI]) Committed(ctx context.Context, seqNr uint64, keyVa
err := p.ReportingPlugin.Committed(ctx, seqNr, p.wrapReader(ctx, keyValueReader))
return nil, err
})
+ // The round is committed whether or not the plugin was able to act on it.
+ p.metrics.recordCommittedSeqNr(ctx, seqNr)
return err
}
diff --git a/core/services/ocr3_1/beholderwrapper/plugin_test.go b/core/services/ocr3_1/beholderwrapper/plugin_test.go
index 845a8edc3fd..99f804205c4 100644
--- a/core/services/ocr3_1/beholderwrapper/plugin_test.go
+++ b/core/services/ocr3_1/beholderwrapper/plugin_test.go
@@ -6,6 +6,9 @@ import (
"testing"
"github.com/stretchr/testify/require"
+ "go.opentelemetry.io/otel/metric/noop"
+ sdkmetric "go.opentelemetry.io/otel/sdk/metric"
+ "go.opentelemetry.io/otel/sdk/metric/metricdata"
"github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types"
"github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types"
@@ -13,7 +16,7 @@ import (
)
func Test_ReportingPlugin_WrapsAllMethods(t *testing.T) {
- metrics, err := newPluginMetrics("test", "abc")
+ metrics, err := newPluginMetrics(noop.NewMeterProvider().Meter("test"), "test", "abc")
require.NoError(t, err)
plugin := newReportingPlugin(
@@ -69,7 +72,7 @@ func Test_ReportingPlugin_WrapsAllMethods(t *testing.T) {
}
func Test_ReportingPlugin_PropagatesErrors(t *testing.T) {
- metrics, err := newPluginMetrics("test", "abc")
+ metrics, err := newPluginMetrics(noop.NewMeterProvider().Meter("test"), "test", "abc")
require.NoError(t, err)
expectedErr := errors.New("test error")
@@ -110,7 +113,7 @@ func Test_ReportingPlugin_PropagatesErrors(t *testing.T) {
}
func Test_InstrumentedBlobBroadcastFetcher(t *testing.T) {
- metrics, err := newPluginMetrics("test", "abc")
+ metrics, err := newPluginMetrics(noop.NewMeterProvider().Meter("test"), "test", "abc")
require.NoError(t, err)
inner := &fakeBlobBroadcastFetcher{
@@ -140,7 +143,7 @@ func Test_InstrumentedBlobBroadcastFetcher(t *testing.T) {
}
func Test_InstrumentedBlobBroadcastFetcher_PropagatesErrors(t *testing.T) {
- metrics, err := newPluginMetrics("test", "abc")
+ metrics, err := newPluginMetrics(noop.NewMeterProvider().Meter("test"), "test", "abc")
require.NoError(t, err)
expectedErr := errors.New("blob error")
@@ -162,7 +165,7 @@ func Test_InstrumentedBlobBroadcastFetcher_PropagatesErrors(t *testing.T) {
}
func Test_InstrumentedBlobFetcher(t *testing.T) {
- metrics, err := newPluginMetrics("test", "abc")
+ metrics, err := newPluginMetrics(noop.NewMeterProvider().Meter("test"), "test", "abc")
require.NoError(t, err)
inner := &fakeBlobFetcher{fetchPayload: []byte("fetched-data")}
@@ -175,7 +178,7 @@ func Test_InstrumentedBlobFetcher(t *testing.T) {
}
func Test_InstrumentedBlobFetcher_PropagatesErrors(t *testing.T) {
- metrics, err := newPluginMetrics("test", "abc")
+ metrics, err := newPluginMetrics(noop.NewMeterProvider().Meter("test"), "test", "abc")
require.NoError(t, err)
expectedErr := errors.New("fetch error")
@@ -187,7 +190,7 @@ func Test_InstrumentedBlobFetcher_PropagatesErrors(t *testing.T) {
}
func Test_ReportingPlugin_WrapsBlobs(t *testing.T) {
- metrics, err := newPluginMetrics("test", "abc")
+ metrics, err := newPluginMetrics(noop.NewMeterProvider().Meter("test"), "test", "abc")
require.NoError(t, err)
innerBlob := &fakeBlobBroadcastFetcher{
@@ -228,7 +231,7 @@ func Test_ReportingPlugin_WrapsBlobs(t *testing.T) {
}
func Test_InstrumentedKVStateReader(t *testing.T) {
- metrics, err := newPluginMetrics("test", "abc")
+ metrics, err := newPluginMetrics(noop.NewMeterProvider().Meter("test"), "test", "abc")
require.NoError(t, err)
inner := &fakeKVStateReader{data: map[string][]byte{"key1": []byte("value1")}}
@@ -247,7 +250,7 @@ func Test_InstrumentedKVStateReader(t *testing.T) {
}
func Test_InstrumentedKVStateReader_PropagatesErrors(t *testing.T) {
- metrics, err := newPluginMetrics("test", "abc")
+ metrics, err := newPluginMetrics(noop.NewMeterProvider().Meter("test"), "test", "abc")
require.NoError(t, err)
expectedErr := errors.New("read error")
@@ -259,7 +262,7 @@ func Test_InstrumentedKVStateReader_PropagatesErrors(t *testing.T) {
}
func Test_InstrumentedKVStateReadWriter(t *testing.T) {
- metrics, err := newPluginMetrics("test", "abc")
+ metrics, err := newPluginMetrics(noop.NewMeterProvider().Meter("test"), "test", "abc")
require.NoError(t, err)
inner := &fakeKVStateReadWriter{fakeKVStateReader: fakeKVStateReader{data: map[string][]byte{}}}
@@ -290,7 +293,7 @@ func Test_InstrumentedKVStateReadWriter(t *testing.T) {
}
func Test_InstrumentedKVStateReadWriter_PropagatesErrors(t *testing.T) {
- metrics, err := newPluginMetrics("test", "abc")
+ metrics, err := newPluginMetrics(noop.NewMeterProvider().Meter("test"), "test", "abc")
require.NoError(t, err)
expectedErr := errors.New("write error")
@@ -311,7 +314,7 @@ func Test_InstrumentedKVStateReadWriter_PropagatesErrors(t *testing.T) {
}
func Test_ReportingPlugin_WrapsKV(t *testing.T) {
- metrics, err := newPluginMetrics("test", "abc")
+ metrics, err := newPluginMetrics(noop.NewMeterProvider().Meter("test"), "test", "abc")
require.NoError(t, err)
innerReader := &fakeKVStateReader{data: map[string][]byte{}}
@@ -595,3 +598,52 @@ func (f *fakePlugin[RI]) ShouldTransmitAcceptedReport(context.Context, uint64, o
func (f *fakePlugin[RI]) Close() error {
return f.err
}
+
+// The sequence number of the latest committed round is the round progress.
+func Test_ReportingPlugin_RecordsCommittedSeqNr(t *testing.T) {
+ t.Parallel()
+ reader := sdkmetric.NewManualReader()
+ mp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))
+ t.Cleanup(func() { _ = mp.Shutdown(context.Background()) })
+
+ metrics, err := newPluginMetrics(mp.Meter("test"), "test", "abc")
+ require.NoError(t, err)
+ plugin := newReportingPlugin(&fakePlugin[uint]{}, metrics)
+
+ committed := func() (value int64, found bool) {
+ var rm metricdata.ResourceMetrics
+ require.NoError(t, reader.Collect(t.Context(), &rm))
+ for _, sm := range rm.ScopeMetrics {
+ for _, m := range sm.Metrics {
+ if m.Name != MetricPrefix+"_committed_seq_nr" {
+ continue
+ }
+ g, ok := m.Data.(metricdata.Gauge[int64])
+ require.True(t, ok)
+ require.Len(t, g.DataPoints, 1)
+ p, _ := g.DataPoints[0].Attributes.Value("plugin")
+ d, _ := g.DataPoints[0].Attributes.Value("configDigest")
+ require.Equal(t, "test", p.AsString())
+ require.Equal(t, "abc", d.AsString())
+ return g.DataPoints[0].Value, true
+ }
+ }
+ return 0, false
+ }
+
+ _, found := committed()
+ require.False(t, found, "nothing committed yet")
+
+ for _, seqNr := range []uint64{7, 8, 12} {
+ require.NoError(t, plugin.Committed(t.Context(), seqNr, nil))
+ got, found := committed()
+ require.True(t, found)
+ require.Equal(t, int64(seqNr), got, "the latest committed round") //nolint:gosec // G115: small test values
+ }
+
+ // a plugin that fails to act on a round does not stop the round from having been committed
+ failing := newReportingPlugin(&fakePlugin[uint]{err: errors.New("boom")}, metrics)
+ require.Error(t, failing.Committed(t.Context(), 13, nil))
+ got, _ := committed()
+ require.Equal(t, int64(13), got)
+}
diff --git a/core/services/ocr3_1/beholderwrapper/types.go b/core/services/ocr3_1/beholderwrapper/types.go
index cc40d80cdc0..fd9b47cb95e 100644
--- a/core/services/ocr3_1/beholderwrapper/types.go
+++ b/core/services/ocr3_1/beholderwrapper/types.go
@@ -11,7 +11,6 @@ import (
"go.opentelemetry.io/otel/metric"
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
- "github.com/smartcontractkit/chainlink-common/pkg/beholder"
"github.com/smartcontractkit/chainlink/v2/core/services/ocr3/beholderwrapper/metrics"
)
@@ -28,9 +27,15 @@ type pluginMetrics struct {
// OCR3.1 specific metrics for blob and KV operations
blobDurations metric.Int64Histogram
kvDurations metric.Int64Histogram
+
+ // committedSeqNr is the sequence number of the latest round that was committed, which is the round progress
+ // of the protocol: it only goes up, and its rate is the rounds per second.
+ committedSeqNr metric.Int64Gauge
}
-func newPluginMetrics(plugin, configDigest string) (*pluginMetrics, error) {
+// newPluginMetrics creates the OCR3.1 instruments on meter. (The base metrics shared with OCR3 are still created
+// by that package, on the global beholder meter.)
+func newPluginMetrics(meter metric.Meter, plugin, configDigest string) (*pluginMetrics, error) {
// Create base metrics using shared package
base, err := metrics.NewPluginMetrics(MetricPrefix, plugin, configDigest)
if err != nil {
@@ -38,25 +43,39 @@ func newPluginMetrics(plugin, configDigest string) (*pluginMetrics, error) {
}
// Create OCR3.1-specific metrics
- blobDurations, err := beholder.GetMeter().Int64Histogram(MetricPrefix+"_blob_duration_ms", metric.WithUnit("ms"))
+ blobDurations, err := meter.Int64Histogram(MetricPrefix+"_blob_duration_ms", metric.WithUnit("ms"))
if err != nil {
return nil, fmt.Errorf("failed to create blob duration histogram: %w", err)
}
- kvDurations, err := beholder.GetMeter().Int64Histogram(MetricPrefix+"_kv_duration_ms", metric.WithUnit("ms"))
+ kvDurations, err := meter.Int64Histogram(MetricPrefix+"_kv_duration_ms", metric.WithUnit("ms"))
if err != nil {
return nil, fmt.Errorf("failed to create kv duration histogram: %w", err)
}
+ committedSeqNr, err := meter.Int64Gauge(MetricPrefix+"_committed_seq_nr",
+ metric.WithDescription("Sequence number of the latest committed round"))
+ if err != nil {
+ return nil, fmt.Errorf("failed to create committed sequence number gauge: %w", err)
+ }
+
return &pluginMetrics{
- PluginMetrics: base,
- plugin: plugin,
- configDigest: configDigest,
- blobDurations: blobDurations,
- kvDurations: kvDurations,
+ PluginMetrics: base,
+ plugin: plugin,
+ configDigest: configDigest,
+ blobDurations: blobDurations,
+ kvDurations: kvDurations,
+ committedSeqNr: committedSeqNr,
}, nil
}
+func (m *pluginMetrics) recordCommittedSeqNr(ctx context.Context, seqNr uint64) {
+ m.committedSeqNr.Record(ctx, int64(seqNr), metric.WithAttributes( //nolint:gosec // G115: a sequence number never nears MaxInt64
+ attribute.String("plugin", m.plugin),
+ attribute.String("configDigest", m.configDigest),
+ ))
+}
+
func (m *pluginMetrics) recordKVDuration(ctx context.Context, method string, d time.Duration, success bool) {
m.kvDurations.Record(ctx, d.Milliseconds(), metric.WithAttributes(
attribute.String("plugin", m.plugin),
diff --git a/core/services/ocr3_1/plugins/queue/README.md b/core/services/ocr3_1/plugins/queue/README.md
new file mode 100644
index 00000000000..3df8b798d25
--- /dev/null
+++ b/core/services/ocr3_1/plugins/queue/README.md
@@ -0,0 +1,174 @@
+# Consensus Queue Reporting Plugin
+
+An OCR3.1 reporting plugin that makes a DON agree on which trigger events to execute, so that each event runs once,
+however many nodes saw it. See the package documentation in `queue.go` for the design; this file is the map.
+
+## Round
+
+Every node keeps a local queue of the coordinated trigger events it has seen (`triggers.Queue`). Each OCR round:
+
+```mermaid
+sequenceDiagram
+ participant trigger@{ "type" : "boundary" } as Trigger
+ participant local@{ "type" : "queue" } as Local
queue
+
+ actor Observation as Observation()
+
+ actor StateTransition as StateTransition()
+
+ box KV state
+ participant observed@{ "type" : "collections" } as Observed
events
+ participant queued@{ "type" : "queue" } as Queued
events
+ participant consensus@{ "type" : "collections" } as Consensus
events
+ end
+
+ box Blob store
+ participant blobs@{ "type" : "database" } as Event
blobs
+ end
+
+ actor Committed as Committed()
+
+ participant coord@{ "type" : "entity" } as Trigger
coordinator
+
+ alt
+ trigger->>local: Cron
+ else
+ trigger->>local: HTTP
+ else
+ trigger->>local: Log
+ end
+
+ rect
+ Note over Observation: Observation(), on every node
+
+ par TryStartExecute (idempotent)
+ consensus->>Observation: Read()
+ and
+ queued->>Observation: Read()
+ and
+ blobs->>Observation: FetchBlob()
+ end
+ Observation->>coord: StartExecution()
+ Observation->>local: Remove(consensus + queued)
+
+ alt KV drain mode (this node's setting)
+ Observation->>local: Sorted() + Remove(): discard, not observed
+ Note over Observation: no events, no blobs, kvDrainActive
+ else
+ local->>Observation: Sorted(): by deadline, skipping events already voted for
+ Observation->>blobs: BroadcastBlob(): up to 10, concurrently
+ end
+ Note over Observation: events, blob handles, capacities,
expiration, kvDrainActive
+ end
+
+ rect
+ Note over StateTransition: StateTransition(), from 2F+1 observations: the same on every node
+
+ Observation-->>StateTransition: ValidateObservation(), then the observations
+ par
+ Note over StateTransition: aggregate: median expiration,
F+1th lowest capacities, F+1 drain votes
+ and
+ observed->>StateTransition: Read()
+ queued->>StateTransition: Read()
+ end
+ Note over StateTransition: drop expired votes
+
+ alt more than F nodes report KV drain
+ Note over StateTransition: nothing new is added
+ StateTransition->>consensus: Write(): every queued event, whatever the capacity
+ else
+ alt >=2F+1 votes for an event
+ StateTransition->>queued: Write(): by deadline, then hash
+ else >=F+1 votes
+ StateTransition->>observed: Write(): the vote and its blob
+ end
+ StateTransition->>consensus: Write(): capacity limited batch (overall and per workflow)
+ end
+ Note over StateTransition: expired events are dropped,
then pruned to fit the KV limits
+ end
+
+ rect
+ Note over Committed: Committed(), on every node
+
+ par TryStartExecute (idempotent)
+ consensus->>Committed: Read()
+ and
+ blobs->>Committed: FetchBlob(): the first voter's blob that works
+ end
+ Committed->>coord: StartExecution(), without waiting for the execution
+ Committed->>local: Remove(consensus + queued)
+ end
+```
+
+`Observation` also runs the start-and-remove step because `Committed` is not guaranteed to run (a restarted node may have
+missed it). It is safe to repeat: starting is deduplicated by the workflow engine on the execution ID, and removing is
+idempotent.
+
+## An event's life
+
+```mermaid
+stateDiagram-v2
+ [*] --> Local: trigger fires
+ Local --> Observed: a node votes for it (observation + blob)
+ Observed --> Queued: F+1 votes, so at least one honest
+ Observed --> [*]: votes expire, or pruned to fit
+ Queued --> Consensus: 2F+1, up to capacity (overall and for its workflow)
+ Queued --> [*]: deadline + grace passes, or pruned to fit
+ Consensus --> Started: Committed() / next Observation()
+ Started --> [*]: removed from every local queue
+```
+
+Nothing retries a failed start: once an event is in consensus it leaves the queue whether or not starting it worked.
+
+## KV state
+
+| Key | Holds |
+| --- | --- |
+| `observed_events::index` | events with fewer than F+1 votes: who voted, and each voter's blob |
+| `queued_events::index` | events with 2F+1 consensus, waiting for capacity, in priority order |
+| `consensus_events::index` | events chosen to run this round |
+| `blob_handles::index` | the blob handles that queued and consensus events refer to |
+
+Everything is bounded by the limits in the job's `PluginConfig`, which `Validate` checks (and the calibration tests in
+`config_test.go` size). A voter has one blob per event, so repeated votes never grow the state.
+
+## Fault tolerance (N = 3F+1)
+
+- Capacity is the F+1th lowest of what nodes report, with nodes that don't report a workflow counting as zero, so F
+ faulty nodes can neither raise it nor starve a workflow. Expiration is the median.
+- An event needs F+1 votes, so a faulty node can't make one up. Its blob is checked when the observation is validated.
+- Observations are bounded (events, blob handles, sizes) and an oversize blob is rejected when it is read, so a faulty
+ node can't make the others spend unbounded CPU or storage.
+
+## KV drain recovery mode
+
+`FeatureConsensusQueueKVDrainActivePeriod` is a global setting for emptying the plugin's state without consensus on new
+events. Each node reads it every round (never cached) and reports the result as `kvDrainActive`. With more than F nodes
+reporting it, the round is a drain round:
+
+- `Observation` reports no events and no blobs (`ValidateObservation` rejects anything else), and discards the front of
+ the local queue so it doesn't fill up.
+- `StateTransition` adds nothing from observations, takes every queued event whatever the capacity, and drops expired ones.
+- `Committed` starts the consensus events as usual.
+
+## Shadow mode
+
+The plugin doesn't know about shadow mode. During `FeatureShadowTriggerModeActivePeriod` the coordinator's
+`StartExecution` logs and counts the event (`platform_engine_trigger_event_shadow_skipped_total`) instead of starting it;
+the workflow runs it from its own queue.
+
+## Metrics
+
+All carry `configDigest`. Prefix `platform_consensus_queue_`; the beholder wrapper adds the usual method duration, size,
+KV and blob metrics, and `platform_ocr3_1_reporting_plugin_committed_seq_nr`.
+
+| Metric | Meaning |
+| --- | --- |
+| `observed_events_total`, `observation_events` | events in this node's observations |
+| `admitted_events_total` | events that reached consensus and joined the queue |
+| `consensus_events_total` | events chosen to run |
+| `dropped_events_total{reason}` | events removed without running: `expired`, `expired_observed`, `pruned_observed`, `pruned_queued` |
+| `discarded_events_total` | events removed from the local queue by drain mode |
+| `queue_depth{orgID}` | queued events by org (`unknown` for workflows not registered on this node) |
+| `observed_depth` | events waiting for F+1 votes |
+| `state_bytes{key}` | size of each KV value written by the last transition |
diff --git a/core/services/ocr3_1/plugins/queue/blobs.go b/core/services/ocr3_1/plugins/queue/blobs.go
new file mode 100644
index 00000000000..1e3da60304a
--- /dev/null
+++ b/core/services/ocr3_1/plugins/queue/blobs.go
@@ -0,0 +1,257 @@
+package queue
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "sort"
+ "sync"
+ "time"
+
+ "google.golang.org/protobuf/encoding/protowire"
+ "google.golang.org/protobuf/proto"
+
+ "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types"
+
+ "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb"
+)
+
+// 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
+
+ mu sync.RWMutex
+ cache map[string]func() ([]byte, error) // blob handle -> blob
+ elements map[string]func() ([][]byte, error) // blob handle -> its events, split up
+}
+
+// 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)
+}
+
+// uncancelled returns what get returns, except that a result which is a context ending is not kept for others. The
+// result of a fetch is shared by every caller, but it was made with the context of the first one, so if that context
+// ended, its cancellation is not the answer for a caller whose context did not. evict removes the result from the cache,
+// and the caller then tries again, once, with its own context. A caller whose own context ended gets the error.
+func uncancelled[T any](ctx context.Context, get func() (T, error), evict func()) (T, error) {
+ for attempt := 0; ; attempt++ {
+ v, err := get()
+ if err == nil || !isCancellation(err) {
+ return v, err
+ }
+ evict()
+ if ctx.Err() != nil || attempt > 0 {
+ return v, err
+ }
+ }
+}
+
+// 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) {
+ return uncancelled(ctx, func() ([]byte, error) { return c.fetchBlobCached(ctx, handle) }, func() {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ delete(c.cache, string(handle))
+ })
+}
+
+func (c *blobCache) fetchBlobCached(ctx context.Context, handle []byte) ([]byte, error) {
+ c.mu.RLock()
+ if fn, ok := c.cache[string(handle)]; ok {
+ c.mu.RUnlock()
+ return fn()
+ }
+
+ c.mu.RUnlock()
+
+ c.mu.Lock()
+ if fn, ok := c.cache[string(handle)]; ok {
+ c.mu.Unlock()
+ return fn()
+ }
+
+ fn := sync.OnceValues(func() ([]byte, error) {
+ var blobHandle ocr3_1types.BlobHandle
+ if err := blobHandle.UnmarshalBinary(handle); err != nil {
+ return nil, fmt.Errorf("failed to unmarshal blob handle: %w", err)
+ }
+
+ return c.fetcher.FetchBlob(ctx, blobHandle)
+ })
+
+ c.cache[string(handle)] = fn
+ c.mu.Unlock()
+ return fn()
+}
+
+// fetchElements fetches the blob and splits it into its events once, however many events are read from it. Finding an
+// 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) {
+ return uncancelled(ctx, func() ([][]byte, error) { return c.fetchElementsCached(ctx, handle) }, func() {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ delete(c.elements, string(handle))
+ })
+}
+
+func (c *blobCache) fetchElementsCached(ctx context.Context, handle []byte) ([][]byte, error) {
+ c.mu.Lock()
+ fn, ok := c.elements[string(handle)]
+ if !ok {
+ fn = sync.OnceValues(func() ([][]byte, error) {
+ blob, err := c.fetchBlob(ctx, handle)
+ if err != nil {
+ return nil, err
+ }
+ return splitEvents(blob, maxEventsPerBlob)
+ })
+ if c.elements == nil {
+ c.elements = make(map[string]func() ([][]byte, error))
+ }
+ c.elements[string(handle)] = fn
+ }
+ c.mu.Unlock()
+ return fn()
+}
+
+// fetchCoordinatedEventFromBlob fetches the blob and returns the idx-th event in it, and its marshaled bytes, without
+// unmarshaling any other events.
+func fetchCoordinatedEventFromBlob(ctx context.Context, fetcher *blobCache, handle []byte, idx int) (*pb.CoordinatedEvent, []byte, error) {
+ elements, err := fetcher.fetchElements(ctx, handle)
+ if err != nil {
+ return nil, nil, fmt.Errorf("failed to fetch blob: %w", err)
+ }
+ if idx < 0 || idx >= len(elements) {
+ return nil, nil, fmt.Errorf("index %d out of range", idx)
+ }
+
+ var event pb.CoordinatedEvent
+ if err := proto.Unmarshal(elements[idx], &event); err != nil {
+ return nil, elements[idx], fmt.Errorf("failed to unmarshal event: %w", err)
+ }
+ return &event, elements[idx], nil
+}
+
+const coordinatedEventsFieldNumber = 1 // 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))
+
+// maxEventBytes returns the largest encoded event (without timestamps) guaranteed to fit alone in a blob.
+// It is conservative by at most a few bytes.
+func (c *consensusQueuePlugin) maxEventBytes() int {
+ return max(0, c.limits.MaxBlobPayloadBytes-maxEventFramingOverhead)
+}
+
+// maxEventsPerBlob is the most events a blob may hold. An observation has at most maxObservedEvents events in all of
+// its blobs, so an honest blob has no more. Anything else only makes reading it costly.
+const maxEventsPerBlob = maxObservedEvents
+
+// splitEvents splits a blob into its marshaled events, without unmarshaling any of them. It rejects a blob with more
+// than limit events.
+func splitEvents(b []byte, limit int) ([][]byte, error) {
+ var events [][]byte
+ for len(b) > 0 {
+ num, typ, n := protowire.ConsumeTag(b)
+ if n < 0 {
+ return nil, protowire.ParseError(n)
+ }
+
+ b = b[n:]
+ if num != coordinatedEventsFieldNumber {
+ n := protowire.ConsumeFieldValue(num, typ, b)
+ if n < 0 {
+ return nil, protowire.ParseError(n)
+ }
+
+ b = b[n:]
+ continue
+ }
+
+ if typ != protowire.BytesType {
+ return nil, fmt.Errorf("expected bytes type for field %d, got %d", coordinatedEventsFieldNumber, typ)
+ }
+
+ v, m := protowire.ConsumeBytes(b)
+ if m < 0 {
+ return nil, protowire.ParseError(m)
+ }
+
+ if len(events) == limit {
+ return nil, fmt.Errorf("blob has more than %d events", limit)
+ }
+
+ events = append(events, v)
+ b = b[m:]
+ }
+ return events, nil
+}
+
+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
+ // 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
+)
+
+// blobExpirySeqNr returns the sequence number at which a blob broadcast in round seqNr may expire, so that it outlives
+// the time remaining until its last event expires, plus minBlobLifetime.
+//
+// The time is converted to rounds by dividing by the estimated round interval, which in OCR3.1 is DeltaRound: the
+// leader waits at least that long between rounds. Rounds are normally longer, so this over-counts the rounds in the
+// remaining time and keeps the blob a little longer than needed. That is the safe direction, as an early expiry
+// loses events but a late one only holds storage. Partial rounds are rounded up. If the interval is unknown, the blob
+// is kept for minBlobLifetimeRounds.
+func blobExpirySeqNr(seqNr uint64, remaining, roundDur time.Duration) uint64 {
+ rounds := uint64(minBlobLifetimeRounds)
+ if roundDur > 0 {
+ lifetime := max(0, remaining) + minBlobLifetime
+ rounds = max(rounds, uint64((lifetime+roundDur-1)/roundDur)) //nolint:gosec // G115: lifetime and roundDur are positive
+ }
+
+ return seqNr + rounds
+}
+
+// blobPrefix returns how many of the events (from the first) fit in one blob.
+func (c *consensusQueuePlugin) blobPrefix(events []*pb.CoordinatedEvent) int {
+ protoOpts := proto.MarshalOptions{Deterministic: true}
+ return sort.Search(len(events), func(i int) bool {
+ return protoOpts.Size(&pb.CoordinatedEventList{Events: events[:i+1]}) > c.limits.MaxBlobPayloadBytes
+ })
+}
+
+// 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
+ for _, event := range events {
+ if t := event.Deadline.AsTime(); t.After(maxDeadline) {
+ maxDeadline = t
+ }
+ }
+
+ // 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 {
+ c.lggr.Warnw("Failed to get expiration grace duration - using default", "grace", grace, "err", err)
+ }
+
+ expSeqNr := blobExpirySeqNr(seqNr, time.Until(maxDeadline.Add(max(0, grace))), c.onchainCfg.EstimatedRoundInterval)
+
+ data, err := proto.MarshalOptions{Deterministic: true}.Marshal(&pb.CoordinatedEventList{Events: events})
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal blob: %w", err)
+ }
+
+ bh, err := broadcaster.BroadcastBlob(ctx, data, ocr3_1types.BlobExpirationHintSequenceNumber{SeqNr: expSeqNr})
+ if err != nil {
+ return nil, fmt.Errorf("failed to broadcast blob: %w", err)
+ }
+
+ return bh.MarshalBinary()
+}
diff --git a/core/services/ocr3_1/plugins/queue/blobs_test.go b/core/services/ocr3_1/plugins/queue/blobs_test.go
new file mode 100644
index 00000000000..9a04450f914
--- /dev/null
+++ b/core/services/ocr3_1/plugins/queue/blobs_test.go
@@ -0,0 +1,722 @@
+package queue
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "math"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/encoding/protowire"
+ "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/types/known/anypb"
+ "google.golang.org/protobuf/types/known/timestamppb"
+
+ "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types"
+
+ "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb"
+)
+
+func Test_extractEvent(t *testing.T) {
+ t.Parallel()
+ payload, err := anypb.New(timestamppb.New(time.Now()))
+ require.NoError(t, err)
+ event := &pb.CoordinatedEvent{
+ WorkflowID: "want",
+ TriggerCapID: "capID",
+ TriggerIndex: 1,
+ ObservedAt: ×tamppb.Timestamp{Seconds: 10, Nanos: 42},
+ Deadline: timestamppb.New(time.Now()),
+ Event: &pb.TriggerResponse{
+ Event: &pb.TriggerEvent{
+ TriggerType: "type",
+ Id: "id",
+ Outputs: nil,
+ Payload: payload,
+ },
+ Error: "asdf",
+ },
+ }
+ otherPayload, err := anypb.New(&pb.CapabilityResponse{})
+ require.NoError(t, err)
+ others := &pb.CoordinatedEvent{
+ WorkflowID: "foo",
+ TriggerCapID: "bar",
+ TriggerIndex: 99,
+ ObservedAt: ×tamppb.Timestamp{Nanos: 99},
+ Deadline: ×tamppb.Timestamp{Seconds: 1000},
+ Event: &pb.TriggerResponse{
+ Event: &pb.TriggerEvent{
+ TriggerType: "baz",
+ Id: "trigger-id",
+ Outputs: nil,
+ Payload: otherPayload,
+ },
+ Error: "none",
+ },
+ }
+ for _, tt := range []struct {
+ name string
+ len, idx int
+ }{
+ {"first", 4, 0},
+ {"last", 4, 3},
+ {"middle", 4, 2},
+ {"bounds", 4, 4},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ var events []*pb.CoordinatedEvent
+ for i := range tt.len {
+ if i == tt.idx {
+ events = append(events, event)
+ } else {
+ events = append(events, others)
+ }
+ }
+ b, err := proto.MarshalOptions{Deterministic: true}.Marshal(&pb.CoordinatedEventList{Events: events})
+ require.NoError(t, err)
+ got, _, err := extractEvent(b, tt.idx)
+ if tt.idx < tt.len {
+ require.True(t, proto.Equal(event, got))
+ } else {
+ require.Error(t, err)
+ }
+ })
+ }
+}
+
+func Test_coordinatedEventsFieldNumber(t *testing.T) {
+ t.Parallel()
+ fd := (&pb.CoordinatedEventList{}).ProtoReflect().Descriptor().Fields().ByName("events")
+ require.NotNil(t, fd)
+ require.Equal(t, protowire.Number(coordinatedEventsFieldNumber), fd.Number())
+}
+
+var errBoom = errors.New("boom")
+
+// handleBytes returns the wire encoding of a minimal valid blob handle; distinct b gives distinct handles.
+func handleBytes(b byte) []byte {
+ root := make([]byte, 32)
+ root[0] = b
+ return append([]byte{1, 0x0a, 0x20}, root...)
+}
+
+func newBlobCache(f ocr3_1types.BlobFetcher) *blobCache {
+ return &blobCache{fetcher: f, cache: make(map[string]func() ([]byte, error))}
+}
+
+// countingFetcher counts FetchBlob calls and returns a fixed payload/error.
+type countingFetcher struct {
+ mu sync.Mutex
+ calls int
+ payload []byte
+ err error
+ gate chan struct{} // if set, FetchBlob blocks until closed
+}
+
+func (f *countingFetcher) FetchBlob(context.Context, ocr3_1types.BlobHandle) ([]byte, error) {
+ f.mu.Lock()
+ f.calls++
+ f.mu.Unlock()
+ if f.gate != nil {
+ <-f.gate
+ }
+ return f.payload, f.err
+}
+
+func (f *countingFetcher) count() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.calls
+}
+
+func marshalEvents(t testing.TB, events ...*pb.CoordinatedEvent) []byte {
+ t.Helper()
+ b, err := proto.MarshalOptions{Deterministic: true}.Marshal(&pb.CoordinatedEventList{Events: events})
+ require.NoError(t, err)
+ return b
+}
+
+func TestBlobCache_FetchBlob(t *testing.T) {
+ t.Parallel()
+
+ t.Run("concurrent fetches of one handle hit the fetcher once", func(t *testing.T) {
+ t.Parallel()
+ f := &countingFetcher{payload: []byte("data"), gate: make(chan struct{})}
+ c := newBlobCache(f)
+
+ var wg sync.WaitGroup
+ results := make([][]byte, 20)
+ for i := range results {
+ wg.Go(func() {
+ b, err := c.fetchBlob(t.Context(), handleBytes(1))
+ assert.NoError(t, err)
+ results[i] = b
+ })
+ }
+ close(f.gate)
+ wg.Wait()
+
+ assert.Equal(t, 1, f.count())
+ for _, r := range results {
+ assert.Equal(t, []byte("data"), r)
+ }
+ })
+
+ t.Run("distinct handles are fetched separately", func(t *testing.T) {
+ t.Parallel()
+ f := &countingFetcher{payload: []byte("data")}
+ c := newBlobCache(f)
+ for _, h := range [][]byte{handleBytes(1), handleBytes(2), handleBytes(1), handleBytes(2)} {
+ _, err := c.fetchBlob(t.Context(), h)
+ require.NoError(t, err)
+ }
+ assert.Equal(t, 2, f.count())
+ })
+
+ t.Run("invalid handle errors without fetching", func(t *testing.T) {
+ t.Parallel()
+ f := &countingFetcher{}
+ _, err := newBlobCache(f).fetchBlob(t.Context(), []byte("not a handle"))
+ require.Error(t, err)
+ assert.Zero(t, f.count())
+ })
+
+ t.Run("fetch error is returned and cached for the round", func(t *testing.T) {
+ t.Parallel()
+ f := &countingFetcher{err: errBoom}
+ c := newBlobCache(f)
+ for range 3 {
+ _, err := c.fetchBlob(t.Context(), handleBytes(1))
+ require.ErrorIs(t, err, errBoom)
+ }
+ assert.Equal(t, 1, f.count())
+ })
+}
+
+// ctxFetcher is a fetcher that ends with the context it is given, or with the payload once gate is closed (or at once,
+// with no gate).
+type ctxFetcher struct {
+ mu sync.Mutex
+ calls int
+ payload []byte
+ gate chan struct{}
+}
+
+func (f *ctxFetcher) FetchBlob(ctx context.Context, _ ocr3_1types.BlobHandle) ([]byte, error) {
+ f.mu.Lock()
+ f.calls++
+ f.mu.Unlock()
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ if f.gate != nil {
+ select {
+ case <-f.gate:
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ }
+ return f.payload, nil
+}
+
+func (f *ctxFetcher) count() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.calls
+}
+
+// A fetch that ended because a context ended says nothing about the blob, so it is not kept for the callers after it.
+func TestBlobCache_CancellationIsNotCached(t *testing.T) {
+ t.Parallel()
+
+ t.Run("a later fetch with a live context fetches again", func(t *testing.T) {
+ t.Parallel()
+ f := &ctxFetcher{payload: []byte("data")}
+ c := newBlobCache(f)
+
+ _, err := c.fetchBlob(cancelledCtx(t), handleBytes(1))
+ require.ErrorIs(t, err, context.Canceled, "the caller whose context ended gets the error")
+
+ b, err := c.fetchBlob(t.Context(), handleBytes(1))
+ require.NoError(t, err)
+ assert.Equal(t, []byte("data"), b)
+ assert.Equal(t, 2, f.count())
+
+ _, err = c.fetchBlob(t.Context(), handleBytes(1))
+ require.NoError(t, err)
+ assert.Equal(t, 2, f.count(), "and a result that is a blob is kept, as before")
+ })
+
+ t.Run("a caller sharing the fetch of one whose context ends fetches again with its own", func(t *testing.T) {
+ t.Parallel()
+ f := &ctxFetcher{payload: []byte("data"), gate: make(chan struct{})}
+ c := newBlobCache(f)
+
+ first, cancelFirst := context.WithCancel(t.Context())
+ firstDone := make(chan error, 1)
+ go func() {
+ _, err := c.fetchBlob(first, handleBytes(1))
+ firstDone <- err
+ }()
+ require.Eventually(t, func() bool { return f.count() == 1 }, 5*time.Second, time.Millisecond)
+
+ type result struct {
+ b []byte
+ err error
+ }
+ secondDone := make(chan result, 1)
+ go func() {
+ b, err := c.fetchBlob(t.Context(), handleBytes(1)) // joins the first one's fetch, or starts its own
+ secondDone <- result{b, err}
+ }()
+
+ cancelFirst()
+ require.ErrorIs(t, <-firstDone, context.Canceled)
+ close(f.gate)
+ res := <-secondDone
+ require.NoError(t, res.err, "the second caller's context did not end")
+ assert.Equal(t, []byte("data"), res.b)
+ })
+
+ t.Run("a rejected or failed fetch that is not a cancellation is still kept", func(t *testing.T) {
+ t.Parallel()
+ f := &countingFetcher{err: errBoom}
+ c := newBlobCache(f)
+ for range 3 {
+ _, err := c.fetchBlob(t.Context(), handleBytes(1))
+ require.ErrorIs(t, err, errBoom)
+ }
+ assert.Equal(t, 1, f.count())
+ })
+
+ t.Run("the split of a blob is not kept either", func(t *testing.T) {
+ t.Parallel()
+ _, e0 := newCoordinatedEvent(t, testWF, "e0")
+ f := &ctxFetcher{payload: marshalEvents(t, e0)}
+ c := newBlobCache(f)
+
+ _, err := c.fetchElements(cancelledCtx(t), handleBytes(1))
+ require.ErrorIs(t, err, context.Canceled)
+
+ elements, err := c.fetchElements(t.Context(), handleBytes(1))
+ require.NoError(t, err)
+ assert.Len(t, elements, 1)
+ })
+}
+
+func TestFetchCoordinatedEventFromBlob(t *testing.T) {
+ t.Parallel()
+
+ _, e0 := newCoordinatedEvent(t, "wf", "e0")
+ _, e1 := newCoordinatedEvent(t, "wf", "e1")
+ e0.ObservedAt, e0.Deadline, e1.ObservedAt, e1.Deadline = nil, nil, nil, nil
+ payload := marshalEvents(t, e0, e1)
+
+ t.Run("returns the element and its raw bytes", func(t *testing.T) {
+ t.Parallel()
+ got, raw, err := fetchCoordinatedEventFromBlob(t.Context(), newBlobCache(&countingFetcher{payload: payload}), handleBytes(1), 1)
+ require.NoError(t, err)
+ assert.True(t, proto.Equal(e1, got))
+ want, err := proto.MarshalOptions{Deterministic: true}.Marshal(e1)
+ require.NoError(t, err)
+ assert.Equal(t, want, raw, "raw bytes must equal the deterministic marshaling the hash was computed over")
+ })
+
+ t.Run("fetch error", func(t *testing.T) {
+ t.Parallel()
+ _, _, err := fetchCoordinatedEventFromBlob(t.Context(), newBlobCache(&countingFetcher{err: errBoom}), handleBytes(1), 0)
+ require.ErrorIs(t, err, errBoom)
+ })
+
+ t.Run("index out of range", func(t *testing.T) {
+ t.Parallel()
+ _, _, err := fetchCoordinatedEventFromBlob(t.Context(), newBlobCache(&countingFetcher{payload: payload}), handleBytes(1), 2)
+ require.Error(t, err)
+ })
+}
+
+func Test_extractEvent_edgeCases(t *testing.T) {
+ t.Parallel()
+
+ _, e := newCoordinatedEvent(t, "wf", "e")
+ e.ObservedAt, e.Deadline = nil, nil
+ eb, err := proto.MarshalOptions{Deterministic: true}.Marshal(e)
+ require.NoError(t, err)
+
+ t.Run("empty and nil blob", func(t *testing.T) {
+ t.Parallel()
+ _, _, err := extractEvent(nil, 0)
+ require.Error(t, err)
+ _, _, err = extractEvent([]byte{}, 0)
+ require.Error(t, err)
+ })
+
+ t.Run("negative index", func(t *testing.T) {
+ t.Parallel()
+ _, _, err := extractEvent(marshalEvents(t, e), -1)
+ require.Error(t, err)
+ })
+
+ t.Run("unknown fields between events are skipped", func(t *testing.T) {
+ t.Parallel()
+ var b []byte
+ b = protowire.AppendTag(b, 2, protowire.VarintType) // unknown field 2
+ b = protowire.AppendVarint(b, 12345)
+ b = protowire.AppendTag(b, coordinatedEventsFieldNumber, protowire.BytesType)
+ b = protowire.AppendBytes(b, eb)
+ b = protowire.AppendTag(b, 3, protowire.BytesType) // unknown field 3
+ b = protowire.AppendBytes(b, []byte("junk"))
+ got, raw, err := extractEvent(b, 0)
+ require.NoError(t, err)
+ assert.True(t, proto.Equal(e, got))
+ assert.Equal(t, eb, raw)
+ _, _, err = extractEvent(b, 1)
+ require.Error(t, err, "unknown fields are not counted as elements")
+ })
+
+ t.Run("wrong wire type for events field", func(t *testing.T) {
+ t.Parallel()
+ b := protowire.AppendTag(nil, coordinatedEventsFieldNumber, protowire.VarintType)
+ b = protowire.AppendVarint(b, 1)
+ _, _, err := extractEvent(b, 0)
+ require.Error(t, err)
+ })
+
+ t.Run("truncated element", func(t *testing.T) {
+ t.Parallel()
+ b := marshalEvents(t, e)
+ _, _, err := extractEvent(b[:len(b)-3], 0)
+ require.Error(t, err)
+ })
+
+ t.Run("truncated tag", func(t *testing.T) {
+ t.Parallel()
+ _, _, err := extractEvent([]byte{0xff}, 0)
+ require.Error(t, err)
+ })
+
+ t.Run("element that is not a valid event returns an error and its bytes", func(t *testing.T) {
+ t.Parallel()
+ b := protowire.AppendTag(nil, coordinatedEventsFieldNumber, protowire.BytesType)
+ b = protowire.AppendBytes(b, []byte{0xff, 0xff, 0xff})
+ got, raw, err := extractEvent(b, 0)
+ require.Error(t, err)
+ assert.Nil(t, got)
+ assert.NotNil(t, raw)
+ })
+}
+
+// hintBlobs records expiration hints and can be told to fail.
+type hintBlobs struct {
+ memBlobs
+ hints []ocr3_1types.BlobExpirationHint
+ err error
+}
+
+func (h *hintBlobs) BroadcastBlob(ctx context.Context, payload []byte, hint ocr3_1types.BlobExpirationHint) (ocr3_1types.BlobHandle, error) {
+ if h.err != nil {
+ return ocr3_1types.BlobHandle{}, h.err
+ }
+ h.hints = append(h.hints, hint)
+ return h.memBlobs.BroadcastBlob(ctx, payload, hint)
+}
+
+func eventsWithDeadline(t testing.TB, n int, deadline time.Time) []*pb.CoordinatedEvent {
+ t.Helper()
+ events := make([]*pb.CoordinatedEvent, 0, n)
+ for i := range n {
+ _, e := newCoordinatedEvent(t, "wf", string(rune('a'+i)))
+ e.Deadline = timestamppb.New(deadline)
+ events = append(events, e)
+ }
+ return events
+}
+
+func TestBroadcastAsBlob(t *testing.T) {
+ t.Parallel()
+
+ t.Run("all events fit", func(t *testing.T) {
+ t.Parallel()
+ blobs := &hintBlobs{}
+ c := testPlugin(t, sliceQueue{}, blobs, ocr3_1types.MaxMaxObservationBytes)
+ events := eventsWithDeadline(t, 3, time.Now().Add(10*time.Second))
+
+ handle, n, err := c.broadcastAsBlob(t.Context(), blobs, events, 100)
+ require.NoError(t, err)
+ assert.Equal(t, 3, n)
+ assert.NotEmpty(t, handle)
+ require.Len(t, blobs.payloads, 1)
+ got, _, err := extractEvent(blobs.payloads[0], 2)
+ require.NoError(t, err)
+ assert.True(t, proto.Equal(events[2], got))
+ })
+
+ t.Run("trims to the payload limit", func(t *testing.T) {
+ t.Parallel()
+ blobs := &hintBlobs{}
+ c := testPlugin(t, sliceQueue{}, blobs, ocr3_1types.MaxMaxObservationBytes)
+ events := eventsWithDeadline(t, 4, time.Now().Add(10*time.Second))
+ c.limits.MaxBlobPayloadBytes = proto.Size(&pb.CoordinatedEventList{Events: events[:2]})
+
+ _, n, err := c.broadcastAsBlob(t.Context(), blobs, events, 100)
+ require.NoError(t, err)
+ assert.Equal(t, 2, n)
+ assert.LessOrEqual(t, len(blobs.payloads[0]), c.limits.MaxBlobPayloadBytes)
+ })
+
+ t.Run("nothing fits", func(t *testing.T) {
+ t.Parallel()
+ blobs := &hintBlobs{}
+ c := testPlugin(t, sliceQueue{}, blobs, ocr3_1types.MaxMaxObservationBytes)
+ c.limits.MaxBlobPayloadBytes = 1
+ _, n, err := c.broadcastAsBlob(t.Context(), blobs, eventsWithDeadline(t, 2, time.Now().Add(time.Minute)), 100)
+ require.Error(t, err)
+ assert.Zero(t, n)
+ assert.Empty(t, blobs.payloads)
+ })
+
+ t.Run("no events", func(t *testing.T) {
+ t.Parallel()
+ blobs := &hintBlobs{}
+ c := testPlugin(t, sliceQueue{}, blobs, ocr3_1types.MaxMaxObservationBytes)
+ _, _, err := c.broadcastAsBlob(t.Context(), blobs, nil, 100)
+ require.Error(t, err)
+ })
+
+ t.Run("broadcast error is wrapped", func(t *testing.T) {
+ t.Parallel()
+ blobs := &hintBlobs{err: errBoom}
+ c := testPlugin(t, sliceQueue{}, blobs, ocr3_1types.MaxMaxObservationBytes)
+ _, _, err := c.broadcastAsBlob(t.Context(), blobs, eventsWithDeadline(t, 1, time.Now().Add(time.Minute)), 100)
+ require.ErrorIs(t, err, errBoom)
+ })
+
+ t.Run("expiration hint follows the latest deadline", func(t *testing.T) {
+ t.Parallel()
+ blobs := &hintBlobs{}
+ c := testPlugin(t, sliceQueue{}, blobs, ocr3_1types.MaxMaxObservationBytes) // 1s rounds
+ events := eventsWithDeadline(t, 2, time.Now().Add(5*time.Second))
+ events[0].Deadline = timestamppb.New(time.Now().Add(60 * time.Second)) // the latest
+
+ _, _, err := c.broadcastAsBlob(t.Context(), blobs, events, 100)
+ require.NoError(t, err)
+ hint := blobs.hints[0].(ocr3_1types.BlobExpirationHintSequenceNumber)
+ // 60s to the latest deadline + 60s grace + 30s minimum lifetime, at 1s per round
+ assert.InDelta(t, 100+150, int(hint.SeqNr), 1) //nolint:gosec // G115: small test values
+ })
+}
+
+// Known issues in broadcastAsBlob's expiration math (SHOULD FIX): these fail until the hint is clamped.
+func TestBroadcastAsBlob_ExpirationHintIsClamped(t *testing.T) {
+ t.Parallel()
+
+ t.Run("already expired deadline does not wrap the sequence number", func(t *testing.T) {
+ t.Parallel()
+ blobs := &hintBlobs{}
+ c := testPlugin(t, sliceQueue{}, blobs, ocr3_1types.MaxMaxObservationBytes)
+ events := eventsWithDeadline(t, 1, time.Now().Add(-time.Hour))
+
+ _, _, err := c.broadcastAsBlob(t.Context(), blobs, events, 100)
+ require.NoError(t, err)
+ hint := blobs.hints[0].(ocr3_1types.BlobExpirationHintSequenceNumber)
+ assert.GreaterOrEqual(t, hint.SeqNr, uint64(100))
+ assert.Less(t, hint.SeqNr, uint64(1_000_000), "negative duration must not convert to a huge uint64")
+ })
+
+ t.Run("zero round interval does not panic", func(t *testing.T) {
+ t.Parallel()
+ blobs := &hintBlobs{}
+ c := testPlugin(t, sliceQueue{}, blobs, ocr3_1types.MaxMaxObservationBytes)
+ c.onchainCfg.EstimatedRoundInterval = 0
+ require.NotPanics(t, func() {
+ _, _, _ = c.broadcastAsBlob(t.Context(), blobs, eventsWithDeadline(t, 1, time.Now().Add(time.Minute)), 100)
+ })
+ })
+}
+
+// maxEventFramingOverhead must cover the framing of an event of any size a blob can hold, including at length prefix boundaries.
+func TestMaxEventFramingOverhead(t *testing.T) {
+ t.Parallel()
+
+ for _, size := range []int{0, 1, 127, 128, 129, 1<<14 - 1, 1 << 14, 1<<21 - 1, 1 << 21, ocr3_1types.MaxMaxBlobPayloadBytes - maxEventFramingOverhead} {
+ framed := protowire.SizeTag(coordinatedEventsFieldNumber) + protowire.SizeBytes(size)
+ assert.LessOrEqual(t, framed-size, maxEventFramingOverhead, "event of %d bytes", size)
+ }
+ assert.Equal(t, 5, maxEventFramingOverhead, "1 tag byte plus a 4 byte length for blobs up to libocr's 5MiB maximum")
+}
+
+func TestBlobExpirySeqNr(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ remaining time.Duration
+ roundDur time.Duration
+ want uint64 // added to seqNr
+ }{
+ {"remaining time and the minimum lifetime, in rounds", 60 * time.Second, time.Second, 90},
+ {"partial rounds round up", 60*time.Second + time.Millisecond, time.Second, 91},
+ {"slower rounds need fewer", 60 * time.Second, 10 * time.Second, 9},
+ {"already expired still gets the minimum lifetime", -time.Hour, time.Second, 30},
+ {"minimum rounds when rounds are long", 0, time.Hour, minBlobLifetimeRounds},
+ {"unknown round interval gets the minimum rounds", time.Hour, 0, minBlobLifetimeRounds},
+ {"negative round interval gets the minimum rounds", time.Hour, -time.Second, minBlobLifetimeRounds},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ assert.Equal(t, 1000+tt.want, blobExpirySeqNr(1000, tt.remaining, tt.roundDur))
+ })
+ }
+
+ t.Run("never expires before the events in it do", func(t *testing.T) {
+ t.Parallel()
+ // rounds are never faster than the estimate, so the sequence number the blob expires at is always reached
+ // after the remaining time has passed
+ for _, remaining := range []time.Duration{0, time.Second, 90 * time.Second, 11 * time.Minute, time.Hour} {
+ for _, roundDur := range []time.Duration{100 * time.Millisecond, time.Second, 3 * time.Second} {
+ rounds := blobExpirySeqNr(0, remaining, roundDur)
+ assert.GreaterOrEqual(t, time.Duration(rounds)*roundDur, remaining+minBlobLifetime, "%s remaining at %s per round", remaining, roundDur) //nolint:gosec // G115: small test values
+ }
+ }
+ })
+}
+
+func TestBroadcastAsBlob_GraceIsOptional(t *testing.T) {
+ t.Parallel()
+
+ blobs := &hintBlobs{}
+ c := testPlugin(t, sliceQueue{}, blobs, ocr3_1types.MaxMaxObservationBytes) // 1s rounds
+ events := eventsWithDeadline(t, 1, time.Now().Add(60*time.Second))
+
+ for _, tt := range []struct {
+ name string
+ grace time.Duration
+ err error
+ want int // sequence number offset: 60s + grace + 30s at 1s per round
+ }{
+ {"no grace", 0, nil, 90},
+ {"grace", 2 * time.Minute, nil, 210},
+ {"error still uses the returned default", 2 * time.Minute, errBoom, 210},
+ {"negative grace is none", -time.Hour, nil, 90},
+ } {
+ c.expirationDur = func(context.Context) (time.Duration, error) { return tt.grace, tt.err }
+ blobs.hints = nil
+ _, _, err := c.broadcastAsBlob(t.Context(), blobs, events, 0)
+ require.NoError(t, err, tt.name)
+ assert.InDelta(t, tt.want, int(blobs.hints[0].(ocr3_1types.BlobExpirationHintSequenceNumber).SeqNr), 1, tt.name) //nolint:gosec // G115: small test values
+ }
+}
+
+// broadcastAsBlob (used by tests: Observation divides events between blobs up front) broadcasts a blob with as many coordinated events as possible, returning the blob handle and count of events included.
+func (c *consensusQueuePlugin) broadcastAsBlob(ctx context.Context, broadcaster ocr3_1types.BlobBroadcaster, events []*pb.CoordinatedEvent,
+ seqNr uint64) (blobHandle []byte, n int, err error) {
+ n = c.blobPrefix(events)
+ if n == 0 {
+ return nil, 0, errors.New("failed to package any events in blob")
+ }
+
+ blobHandle, err = c.broadcastBlob(ctx, broadcaster, events[:n], seqNr)
+ if err != nil {
+ return nil, -1, err
+ }
+
+ return blobHandle, n, nil
+}
+
+// extractEvent returns the idx-th event in the blob, and its marshaled bytes. (Production code reads events through
+// blobCache, which splits a blob once.)
+func extractEvent(b []byte, idx int) (*pb.CoordinatedEvent, []byte, error) {
+ events, err := splitEvents(b, math.MaxInt)
+ if err != nil {
+ return nil, nil, err
+ }
+ if idx < 0 || idx >= len(events) {
+ return nil, nil, fmt.Errorf("index %d out of range", idx)
+ }
+ var event pb.CoordinatedEvent
+ if err := proto.Unmarshal(events[idx], &event); err != nil {
+ return nil, events[idx], fmt.Errorf("failed to unmarshal event: %w", err)
+ }
+ return &event, events[idx], nil
+}
+
+func TestSplitEvents(t *testing.T) {
+ t.Parallel()
+
+ element := func(b []byte) []byte {
+ out := protowire.AppendTag(nil, coordinatedEventsFieldNumber, protowire.BytesType)
+ return protowire.AppendBytes(out, b)
+ }
+ blobOf := func(n int) (b []byte) {
+ for range n {
+ b = append(b, element([]byte{0x0a, 0x01, 'x'})...)
+ }
+ return b
+ }
+
+ t.Run("a blob of exactly the maximum is split", func(t *testing.T) {
+ t.Parallel()
+ events, err := splitEvents(blobOf(maxEventsPerBlob), maxEventsPerBlob)
+ require.NoError(t, err)
+ assert.Len(t, events, maxEventsPerBlob)
+ })
+
+ t.Run("a blob of more than the maximum is rejected", func(t *testing.T) {
+ t.Parallel()
+ _, err := splitEvents(blobOf(maxEventsPerBlob+1), maxEventsPerBlob)
+ require.ErrorContains(t, err, "more than")
+ })
+
+ t.Run("fields that are not events are not counted", func(t *testing.T) {
+ t.Parallel()
+ b := blobOf(2)
+ for range 10 {
+ b = protowire.AppendTag(b, 2, protowire.VarintType)
+ b = protowire.AppendVarint(b, 7)
+ }
+ events, err := splitEvents(b, 2)
+ require.NoError(t, err)
+ assert.Len(t, events, 2)
+ })
+}
+
+// A blob is fetched and split once however many of its events are read, so reading them costs the size of the blob, not
+// the size of the blob for each event.
+func TestBlobCache_SplitsOnce(t *testing.T) {
+ t.Parallel()
+
+ _, e0 := newCoordinatedEvent(t, testWF, "e0")
+ _, e1 := newCoordinatedEvent(t, testWF, "e1")
+ f := &countingFetcher{payload: marshalEvents(t, e0, e1)}
+ c := newBlobCache(f)
+
+ first, err := c.fetchElements(t.Context(), handleBytes(1))
+ require.NoError(t, err)
+ second, err := c.fetchElements(t.Context(), handleBytes(1))
+ require.NoError(t, err)
+ require.Len(t, first, 2)
+ assert.Same(t, &first[0], &second[0], "the same split is returned, not a new one")
+ assert.Equal(t, 1, f.count())
+
+ t.Run("a rejected blob stays rejected without fetching again", func(t *testing.T) {
+ var big []byte
+ for range maxEventsPerBlob + 1 {
+ big = protowire.AppendTag(big, coordinatedEventsFieldNumber, protowire.BytesType)
+ big = protowire.AppendBytes(big, nil)
+ }
+ f := &countingFetcher{payload: big}
+ c := newBlobCache(f)
+ for range 3 {
+ _, _, err := fetchCoordinatedEventFromBlob(t.Context(), c, handleBytes(2), 0)
+ require.ErrorContains(t, err, "more than")
+ }
+ assert.Equal(t, 1, f.count())
+ })
+}
diff --git a/core/services/ocr3_1/plugins/queue/config_test.go b/core/services/ocr3_1/plugins/queue/config_test.go
new file mode 100644
index 00000000000..f8dbbb733a8
--- /dev/null
+++ b/core/services/ocr3_1/plugins/queue/config_test.go
@@ -0,0 +1,237 @@
+package queue
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "math/rand"
+ "sort"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "google.golang.org/protobuf/encoding/protowire"
+ "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/types/known/anypb"
+ "google.golang.org/protobuf/types/known/timestamppb"
+ "google.golang.org/protobuf/types/known/wrapperspb"
+
+ "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types"
+
+ "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb"
+ "github.com/smartcontractkit/chainlink-common/pkg/settings/cresettings"
+)
+
+// The tests below calibrate the constants in queue.go (and the libocr limits they must fit within) by measuring real
+// protobuf sizes. They log a table (run with -v) and assert the invariants that keep the plugin inside libocr's hard limits.
+// Inputs that are assumptions, rather than measurements, are marked as such.
+
+// hexID returns a deterministic 64 character hex string, like workflow and execution IDs.
+func hexID(prefix string, i int) string {
+ h := sha256.Sum256([]byte(fmt.Sprint(prefix, "-", i)))
+ return hex.EncodeToString(h[:])
+}
+
+// randTS returns a current-era timestamp with random nanos, so varint sizes are realistic (most nanos need 5 bytes).
+func randTS(rng *rand.Rand) *timestamppb.Timestamp {
+ return ×tamppb.Timestamp{Seconds: 1_800_000_000 + rng.Int63n(100_000_000), Nanos: rng.Int31n(1_000_000_000)}
+}
+
+// summarize returns the average and maximum of f(i) over n samples.
+func summarize(n int, f func(i int) int) (avg float64, maxVal int) {
+ var sum int
+ for i := range n {
+ v := f(i)
+ sum += v
+ maxVal = max(maxVal, v)
+ }
+ return float64(sum) / float64(n), maxVal
+}
+
+// observedEventFor is an event as it appears in an observation, with distinct realistic IDs.
+func observedEventFor(rng *rand.Rand, i int) *pb.ConsensusQueueEvent {
+ hash := sha256.Sum256([]byte(hexID("hash", i)))
+ return &pb.ConsensusQueueEvent{
+ WorkflowID: hexID("wf", i),
+ ExecutionID: hexID("exec", i),
+ ObservedAt: randTS(rng),
+ Deadline: randTS(rng),
+ TimelessHash: hash[:],
+ Blobs: []*pb.CoordinatedEventBlobHandle{{Blob: uint32(rng.Intn(maxObservedBlobHandles)), Element: uint32(rng.Intn(maxObservedEvents))}}, //nolint:gosec // G115: bounded by small constants
+ }
+}
+
+// oracleCounts are DON sizes to calibrate for, as (N, F=(N-1)/3).
+var oracleCounts = []int{4, 7, 16, 31, 100}
+
+func TestCalibration_ObservationFitsLimit(t *testing.T) {
+ t.Parallel()
+
+ rng := rand.New(rand.NewSource(1))
+ avgEvent, maxEvent := summarize(maxObservedEvents, func(i int) int { return proto.Size(observedEventFor(rng, i)) })
+
+ // worst case: every event is for a different workflow, so each also adds a capacity entry
+ worstCaseObservation := func(n int) *pb.ConsensusQueueObservation {
+ f := (n - 1) / 3
+ obs := &pb.ConsensusQueueObservation{
+ Expiration: randTS(rng),
+ Capacity: 1<<32 - 1,
+ WorkflowCapacities: map[string]uint32{},
+ }
+ for i := range maxObservedEvents {
+ e := observedEventFor(rng, i)
+ obs.Events = append(obs.Events, e)
+ obs.WorkflowCapacities[e.WorkflowID] = 1<<32 - 1
+ }
+ for range maxObservedBlobHandles { // the real handles take up no more than the placeholders reserved for them
+ obs.BlobHandles = append(obs.BlobHandles, make([]byte, ocr3_1types.BlobHandleMarshalledBytesUpperBound(n, f)))
+ }
+ return obs
+ }
+
+ t.Logf("event in an observation: avg %.0fB, max %dB (IDs are 64 hex chars)", avgEvent, maxEvent)
+ for _, n := range append(oracleCounts, 256) {
+ size := proto.Size(worstCaseObservation(n))
+ headroom := ocr3_1types.MaxMaxObservationBytes - size
+ t.Logf("N=%-3d %d events + %d blob handles (%dB each): %d of %d bytes (%.0f%% of libocr's maximum, %dB headroom)",
+ n, maxObservedEvents, maxObservedBlobHandles, ocr3_1types.BlobHandleMarshalledBytesUpperBound(n, (n-1)/3),
+ size, ocr3_1types.MaxMaxObservationBytes, 100*float64(size)/ocr3_1types.MaxMaxObservationBytes, headroom)
+ if n <= 100 { // N=256 is libocr's theoretical maximum, and is only logged
+ assert.LessOrEqual(t, size, ocr3_1types.MaxMaxObservationBytes,
+ "a full observation (maxObservedEvents, maxObservedBlobHandles) must fit in libocr's observation limit at N=%d", n)
+ }
+ }
+}
+
+// eventOfPayload is an event as it appears in a blob, with an opaque trigger payload of the given size.
+func eventOfPayload(i, payload int) *pb.CoordinatedEvent {
+ payloadAny, err := anypb.New(wrapperspb.Bytes(make([]byte, payload)))
+ if err != nil {
+ panic(err)
+ }
+ return &pb.CoordinatedEvent{
+ WorkflowID: hexID("wf", i), TriggerCapID: "evm@1.0.0", TriggerIndex: int64(i % 3),
+ Event: &pb.TriggerResponse{Event: &pb.TriggerEvent{TriggerType: "evm@1.0.0", Id: hexID("evt", i) + ":" + hexID("blk", i) + ":7", Payload: payloadAny}},
+ }
+}
+
+// blobsNeeded is how many blobs maxObservedEvents events with this payload take, with each blob full to blobLimit.
+func blobsNeeded(payload, blobLimit int) (blobs, perBlob, element int) {
+ b, err := proto.MarshalOptions{Deterministic: true}.Marshal(eventOfPayload(0, payload))
+ if err != nil {
+ panic(err)
+ }
+ element = protowire.SizeTag(coordinatedEventsFieldNumber) + protowire.SizeBytes(len(b))
+ perBlob = blobLimit / element
+ if perBlob == 0 {
+ return 0, 0, element // does not fit at all
+ }
+ return (maxObservedEvents + perBlob - 1) / perBlob, perBlob, element
+}
+
+func TestCalibration_BlobPacking(t *testing.T) {
+ t.Parallel()
+
+ // Trigger payload sizes are ASSUMPTIONS (the plugin does not interpret payloads): adjust to what triggers really emit.
+ kinds := []struct {
+ name string
+ payload int
+ typical bool // typical loads must fit maxObservedEvents in maxObservedBlobHandles blobs
+ }{
+ {"cron tick", 128, true},
+ {"EVM log", 1 << 10, true},
+ {"EVM log with large data", 8 << 10, true},
+ {"HTTP trigger request", 32 << 10, true},
+ }
+ for _, k := range kinds {
+ blobs, perBlob, element := blobsNeeded(k.payload, ocr3_1types.MaxMaxBlobPayloadBytes)
+ t.Logf("%-24s payload %6dB -> %6dB per event in a blob: %5d events per %dMiB blob, %2d blobs for %d events (%d handles available)",
+ k.name, k.payload, element, perBlob, ocr3_1types.MaxMaxBlobPayloadBytes>>20, blobs, maxObservedEvents, maxObservedBlobHandles)
+ if k.typical {
+ assert.LessOrEqual(t, blobs, maxObservedBlobHandles, "%s: maxObservedEvents must be broadcastable in maxObservedBlobHandles blobs", k.name)
+ }
+ }
+
+ // the largest payload for which a full observation (maxObservedEvents) still fits in maxObservedBlobHandles blobs
+ limit := sort.Search(ocr3_1types.MaxMaxBlobPayloadBytes, func(p int) bool {
+ blobs, _, _ := blobsNeeded(p, ocr3_1types.MaxMaxBlobPayloadBytes)
+ return blobs == 0 || blobs > maxObservedBlobHandles
+ }) - 1
+ blobs, perBlob, element := blobsNeeded(limit, ocr3_1types.MaxMaxBlobPayloadBytes)
+ t.Logf("%d events fit in %d blobs up to a payload of %dB (%dB per event, %d per blob, %d blobs)",
+ maxObservedEvents, maxObservedBlobHandles, limit, element, perBlob, blobs)
+ assert.Positive(t, limit, "a full observation must be able to carry some payload")
+ assert.LessOrEqual(t, blobs, maxObservedBlobHandles)
+ // beyond that, Observation drops the events that do not fit, rather than failing
+}
+
+func TestCalibration_KVState(t *testing.T) {
+ t.Parallel()
+
+ rng := rand.New(rand.NewSource(2))
+
+ // consensus and queued events carry one blob ref each
+ queuedAvg, queuedMax := summarize(1000, func(i int) int {
+ e := observedEventFor(rng, i)
+ e.Blobs = []*pb.CoordinatedEventBlobHandle{{Blob: uint32(rng.Intn(maxObservedBlobHandles * 31)), Element: uint32(rng.Intn(maxObservedEvents))}} //nolint:gosec // G115: bounded by small constants
+ return protowire.SizeBytes(proto.Size(e)) + protowire.SizeTag(1) // as an element of ConsensusQueueEventList
+ })
+ t.Logf("queued/consensus event in KV: avg %.0fB, max %dB", queuedAvg, queuedMax)
+ queuedCapacity := maxKeyValueValueBytes / queuedMax
+ t.Logf("the %dMiB value limit holds %d queued events (maxObservedEvents is %d)", maxKeyValueValueBytes>>20, queuedCapacity, maxObservedEvents)
+ assert.GreaterOrEqual(t, queuedCapacity, 2*maxObservedEvents, "the queue must hold at least two full observation rounds' worth of events")
+
+ for _, n := range []int{4, 7, 16, 31} {
+ f := (n - 1) / 3
+
+ // an observed event waits at between f+1 and 2f votes, each with a node ID and two timestamps
+ observedAvg, observedMax := summarize(1000, func(i int) int {
+ e := &pb.ConsensusQueueObservedEvent{WorkflowID: hexID("wf", i), ExecutionID: hexID("exec", i)}
+ for v := range 2 * f {
+ e.NodeIds = append(e.NodeIds, byte(v))
+ e.ObservedAts = append(e.ObservedAts, randTS(rng))
+ e.Deadlines = append(e.Deadlines, randTS(rng))
+ }
+ for range 2 * f { // the blob of each vote
+ e.Blobs = append(e.Blobs, &pb.CoordinatedEventBlobHandle{Blob: uint32(rng.Intn(maxObservedBlobHandles * n)), Element: uint32(rng.Intn(maxObservedEvents))}) //nolint:gosec // G115: bounded by small constants
+ }
+ entry := &pb.ConsensusQueueObservedEventEntry{TimelessHash: make([]byte, sha256.Size), Event: e}
+ return protowire.SizeBytes(proto.Size(entry)) + protowire.SizeTag(1)
+ })
+ observedCapacity := maxKeyValueValueBytes / observedMax
+ t.Logf("N=%-2d observed event at 2f=%d votes in KV: avg %.0fB, max %dB -> %d fit in the value limit", n, 2*f, observedAvg, observedMax, observedCapacity)
+ assert.GreaterOrEqual(t, observedCapacity, maxObservedEvents, "N=%d: a full round of events must fit in the observed set", n)
+
+ // each of N nodes can broadcast maxObservedBlobHandles blobs in a round; their handles are kept while events reference them
+ handles := maxObservedBlobHandles * n * ocr3_1types.BlobHandleMarshalledBytesUpperBound(n, f)
+ t.Logf("N=%-2d one round of blob handles from every node: %dB (%.0f%% of the value limit)", n, handles, 100*float64(handles)/maxKeyValueValueBytes)
+ assert.LessOrEqual(t, handles, maxKeyValueValueBytes, "N=%d: a round's blob handles must fit in the blob handles value", n)
+ }
+
+ // All four keys can be full at once: observed, queued and consensus events, and blob handles.
+ total := numKVKeys*maxKeyValueValueBytes + numKVKeys*len(consensusEventsKey) + len(observedEventsKey)
+ t.Logf("all %d KV values full: %dMiB of libocr's %dMiB modified-keys-plus-values limit", numKVKeys, total>>20, ocr3_1types.MaxMaxKeyValueModifiedKeysPlusValuesBytes>>20)
+ assert.LessOrEqual(t, total, ocr3_1types.MaxMaxKeyValueModifiedKeysPlusValuesBytes)
+ assert.LessOrEqual(t, maxKeyValueValueBytes, ocr3_1types.MaxMaxKeyValueValueBytes)
+ assert.LessOrEqual(t, numKVKeys, ocr3_1types.MaxMaxKeyValueModifiedKeys)
+}
+
+// Blobs are kept until their events expire (the workflow's timeout plus the grace period), so the blob quotas are set by
+// how long that is in rounds. This logs what a sustained load needs, using the real defaults.
+func TestCalibration_BlobLifetime(t *testing.T) {
+ t.Parallel()
+
+ timeout := cresettings.Default.PerWorkflow.TriggerEventQueueTimeout.DefaultValue
+ grace := cresettings.Default.ConsensusQueueExpirationGraceInterval.DefaultValue
+ t.Logf("event timeout %s, grace %s", timeout, grace)
+ assert.LessOrEqual(t, grace*10, timeout, "the grace period is slack for clock skew and consensus latency, a small fraction of the timeout")
+
+ for _, roundDur := range []time.Duration{250 * time.Millisecond, 500 * time.Millisecond, time.Second, 2 * time.Second} {
+ rounds := blobExpirySeqNr(0, timeout+grace, roundDur)
+ perRoundBlobs := maxObservedBlobHandles // a full observation every round: the worst case
+ t.Logf("DeltaRound %-6s: a blob is kept for %5d rounds (%s); sustained full observations would hold %6d blobs = %5.1f GiB per oracle",
+ 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
+ }
+}
diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go
new file mode 100644
index 00000000000..70c6bac2005
--- /dev/null
+++ b/core/services/ocr3_1/plugins/queue/kvstate.go
@@ -0,0 +1,699 @@
+package queue
+
+import (
+ "cmp"
+ "container/heap"
+ "fmt"
+ "maps"
+ "math"
+ "slices"
+ "sort"
+ "time"
+
+ "google.golang.org/protobuf/encoding/protowire"
+ "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/types/known/timestamppb"
+
+ "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types"
+
+ "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb"
+)
+
+// numKVKeys is the number of KV keys written each round.
+const numKVKeys = 4
+
+// 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 }
+ // priority queue of events waiting for capacity
+ queuedEventsKey = "queued_events::index" // pb.ConsensusQueueEventList { []*pb.ConsensusQueueEvent }
+ // events the plugin committed to sending to nodes
+ consensusEventsKey = "consensus_events::index" // pb.ConsensusQueueEventList { []*pb.ConsensusQueueEvent }
+ // blob handles referenced from events in the PQ and consensus set
+ blobHandlesKey = "blob_handles::index" // pb.ConsensusQueueBlobHandleList{ [][]byte }
+)
+
+type stateWriter struct {
+ kv ocr3_1types.KeyValueStateReadWriter
+ sizes map[string]int // key -> bytes written
+}
+
+func (s *stateWriter) writeValue[M proto.Message](key string, m M) error {
+ val, err := proto.MarshalOptions{Deterministic: true}.Marshal(m)
+ if err != nil {
+ return fmt.Errorf("failed to marshal %T: %w", m, err)
+ }
+
+ if s.sizes == nil {
+ s.sizes = make(map[string]int)
+ }
+ s.sizes[key] = len(val)
+ return s.kv.Write([]byte(key), val)
+}
+
+var _ heap.Interface = (*priorityQueue)(nil)
+
+// priorityQueue is a heap of coordinated events, ordered by deadline and then trigger event ID.
+type priorityQueue []*pb.ConsensusQueueEvent
+
+func (p *priorityQueue) Len() int {
+ if p == nil {
+ return 0
+ }
+
+ return len(*p)
+}
+
+func (p *priorityQueue) Less(i, j int) bool {
+ a, b := (*p)[i], (*p)[j]
+ return a.CompareDeadline(b) < 0
+}
+
+func (p *priorityQueue) Swap(i, j int) {
+ (*p)[i], (*p)[j] = (*p)[j], (*p)[i]
+}
+
+func (p *priorityQueue) Push(x any) {
+ *p = append(*p, x.(*pb.ConsensusQueueEvent))
+}
+
+func (p *priorityQueue) Pop() any {
+ if p.Len() == 0 {
+ return nil
+ }
+
+ e := (*p)[len(*p)-1]
+ *p = (*p)[:len(*p)-1]
+ return e
+}
+
+func (p *priorityQueue) push(x *pb.ConsensusQueueEvent) { heap.Push(p, x) }
+
+func (s *kvState) queueObservations(timelessHash string, obs *pb.ConsensusQueueObservedEvent) *pb.ConsensusQueueEvent {
+ event := &pb.ConsensusQueueEvent{
+ WorkflowID: obs.WorkflowID,
+ ExecutionID: obs.ExecutionID,
+ ObservedAt: medianTimestamp(obs.ObservedAts),
+ Deadline: medianTimestamp(obs.Deadlines),
+ TimelessHash: []byte(timelessHash),
+ // note: observedBlobs tracks blobs while in memory
+ }
+
+ s.queuedEvents.push(event)
+ return event
+}
+
+// mustPop pops the next event from the queue, or returns nil if the queue is empty.
+// The value must be of type *pb.ConsensusQueueEvent. Use push to ensure this.
+func (p *priorityQueue) mustPop() *pb.ConsensusQueueEvent {
+ if p.Len() == 0 {
+ return nil
+ }
+
+ return heap.Pop(p).(*pb.ConsensusQueueEvent)
+}
+
+// popEligible pops up to n events from the queue, in priority order, each of which also has capacity left for its
+// workflow, which it uses up. Expired events are dropped. Events without workflow capacity stay in the queue.
+// Note: capPerWF is mutated.
+//
+// It makes a single pass, and puts back the events it skipped once at the end. A workflow's capacity only goes down
+// while popping, so an event that was skipped stays ineligible, and looking at it again for each event popped (as popping
+// one at a time did) is wasted work: quadratic in the events waiting on workflows without capacity (1.9s for 10000).
+func (p *priorityQueue) popEligible(n int, capPerWF map[string]uint32, expiration time.Time) (popped []*pb.ConsensusQueueEvent, expired int) {
+ var skipped []*pb.ConsensusQueueEvent
+ for len(popped) < n {
+ event := p.mustPop()
+ if event == nil {
+ break
+ }
+
+ if event.Deadline.AsTime().Before(expiration) {
+ expired++
+ continue // drop expired
+ }
+
+ if capPerWF[event.WorkflowID] == 0 {
+ skipped = append(skipped, event)
+ continue
+ }
+
+ capPerWF[event.WorkflowID]--
+ popped = append(popped, event)
+ }
+
+ for _, event := range skipped {
+ p.push(event)
+ }
+
+ return popped, expired
+}
+
+type blobHandleMap map[string]map[string]uint32 // eventHash -> blobHandle -> idx
+
+func (m blobHandleMap) add(eventHash string, blobHandle string, element uint32) {
+ if _, ok := m[eventHash]; !ok {
+ m[eventHash] = make(map[string]uint32)
+ }
+
+ m[eventHash][blobHandle] = element
+}
+
+func (m blobHandleMap) addAll(eventHash string, blobHandles map[string]uint32) {
+ if _, ok := m[eventHash]; !ok {
+ m[eventHash] = make(map[string]uint32)
+ }
+
+ maps.Copy(m[eventHash], blobHandles)
+}
+
+// voterBlobs is the blob each voter observed each event in: eventHash -> voter -> blob. There is one per voter, so a voter
+// that votes again replaces its blob instead of adding to those that the event refers to, which would let it grow
+// without limit.
+type voterBlobs map[string]map[uint8]blobRef
+
+type blobRef struct {
+ handle string
+ element uint32 // the index of the event in the blob
+}
+
+func (m voterBlobs) add(eventHash string, voter uint8, blobHandle string, element uint32) {
+ if _, ok := m[eventHash]; !ok {
+ m[eventHash] = make(map[uint8]blobRef)
+ }
+
+ m[eventHash][voter] = blobRef{handle: blobHandle, element: element}
+}
+
+// handles returns the distinct blobs of the event's voters, and where the event is in each. Voters may share a blob,
+// but if they disagree on where the event is in it, the lowest index is used so that the result is deterministic.
+func (m voterBlobs) handles(eventHash string) map[string]uint32 {
+ handles := make(map[string]uint32, len(m[eventHash]))
+ for _, ref := range m[eventHash] {
+ if element, ok := handles[ref.handle]; !ok || ref.element < element {
+ handles[ref.handle] = ref.element
+ }
+ }
+
+ return handles
+}
+
+// kvStats counts what a state transition removed from the state, other than by executing it.
+type kvStats struct {
+ expiredObserved int // observed events whose votes had all expired
+ expiredQueued int // queued events that had expired
+ prunedObserved int // observed events dropped to fit the state limits
+ prunedQueued int // queued events dropped to fit the state limits
+}
+
+type kvState struct {
+ stats kvStats
+
+ // observedEventsKey
+ observedEvents map[string]*pb.ConsensusQueueObservedEvent // key: timeless hash
+ observedEventEntries []*pb.ConsensusQueueObservedEventEntry // only populated before write
+ observedBlobs voterBlobs
+ observedBlobHandles [][]byte // only populated before write
+
+ // priorityQueueKey
+ queuedEvents priorityQueue
+ // consensusEventsKey
+ consensusEvents []*pb.ConsensusQueueEvent
+ // blobHandlesKey
+ queuedBlobs blobHandleMap
+ queuedBlobHandles [][]byte // only populated before write
+}
+
+// loadFrom loads the kvState from the KV store, excluding consensus events, which are not required to transition.
+func (s *kvState) loadFrom(kv ocr3_1types.KeyValueStateReadWriter) error {
+ var err error
+ s.observedEvents, s.observedBlobs, err = readObservedEvents(kv)
+ if err != nil {
+ return err
+ }
+
+ queuedEvents, err := readQueuedEvents(kv)
+ if err != nil {
+ return err
+ }
+
+ s.queuedEvents = queuedEvents
+
+ s.queuedBlobs = make(blobHandleMap)
+ queuedBlobs, err := readBlobHandles(kv)
+ if err != nil {
+ return err
+ }
+
+ for _, event := range s.queuedEvents {
+ for _, blob := range event.GetBlobs() {
+ if int(blob.Blob) < len(queuedBlobs) {
+ s.queuedBlobs.add(string(event.TimelessHash), string(queuedBlobs[blob.Blob]), blob.Element)
+ }
+ }
+ }
+
+ return nil
+}
+
+func readQueuedEvents(kv ocr3_1types.KeyValueStateReader) ([]*pb.ConsensusQueueEvent, error) {
+ v, err := kv.Read([]byte(queuedEventsKey))
+ if err != nil {
+ return nil, fmt.Errorf("failed to read queued events: %w", err)
+ }
+
+ if v != nil {
+ var queued pb.ConsensusQueueEventList
+ if err = proto.Unmarshal(v, &queued); err != nil {
+ return nil, fmt.Errorf("failed to unmarshal queued events: %w", err)
+ }
+
+ return queued.GetEvents(), nil
+ }
+
+ return nil, nil
+}
+
+func readObservedEvents(kv ocr3_1types.KeyValueStateReader) (observedEvents map[string]*pb.ConsensusQueueObservedEvent, observedBlobs voterBlobs, err error) {
+ v, err := kv.Read([]byte(observedEventsKey))
+ if err != nil {
+ return nil, nil, fmt.Errorf("failed to read observed events: %w", err)
+ }
+
+ observedBlobs = make(voterBlobs)
+ if v != nil {
+ var observed pb.ConsensusQueueObservedEvents
+ if err = proto.Unmarshal(v, &observed); err != nil {
+ return nil, nil, fmt.Errorf("failed to unmarshal observed events: %w", err)
+ }
+
+ observedEvents = make(map[string]*pb.ConsensusQueueObservedEvent)
+ for _, e := range observed.GetObservations() {
+ observedEvents[string(e.TimelessHash)] = e.Event
+ }
+
+ blobHandles := observed.GetBlobHandles()
+ for eventHash, event := range observedEvents {
+ // Blobs[i] is the blob of the vote of NodeIds[i]
+ for i, voter := range event.GetNodeIds() {
+ if i < len(event.Blobs) && int(event.Blobs[i].Blob) < len(blobHandles) {
+ observedBlobs.add(eventHash, voter, string(blobHandles[event.Blobs[i].Blob]), event.Blobs[i].Element)
+ }
+ }
+ }
+ } else {
+ observedEvents = make(map[string]*pb.ConsensusQueueObservedEvent)
+ }
+
+ return observedEvents, observedBlobs, nil
+}
+
+// sizeOf returns the size of the state when serialized and written to the KV store via writeAll.
+func (s *kvState) sizeOf() (size int) {
+ size += len(observedEventsKey) + len(queuedEventsKey) + len(consensusEventsKey) + len(blobHandlesKey)
+ size += s.sizeOfObservedEvents() + s.sizeOfQueuedEvents() + s.sizeOfConsensusEvents() + s.sizeOfBlobHandles()
+ return
+}
+
+func (s *kvState) sizeOfObservedEvents() int {
+ s.prepareWriteObservedEvents()
+ return proto.MarshalOptions{Deterministic: true}.Size(&pb.ConsensusQueueObservedEvents{Observations: s.observedEventEntries, BlobHandles: s.observedBlobHandles})
+}
+
+func (s *kvState) sizeOfQueuedEvents() int {
+ s.prepareWriteBlobHandles() // events must carry their blob refs to be sized accurately
+ return proto.MarshalOptions{Deterministic: true}.Size(&pb.ConsensusQueueEventList{Events: s.queuedEvents})
+}
+
+func (s *kvState) sizeOfConsensusEvents() int {
+ s.prepareWriteBlobHandles() // events must carry their blob refs to be sized accurately
+ return proto.MarshalOptions{Deterministic: true}.Size(&pb.ConsensusQueueEventList{Events: s.consensusEvents})
+}
+
+func (s *kvState) sizeOfBlobHandles() int {
+ s.prepareWriteBlobHandles()
+ return proto.MarshalOptions{Deterministic: true}.Size(&pb.ConsensusQueueBlobHandleList{BlobHandles: s.queuedBlobHandles})
+}
+
+// prepareWrite initializes observed blob handles & entries, and updates the event references.
+func (s *kvState) prepareWriteObservedEvents() {
+ // gather blob handles and update events
+ s.observedBlobHandles = nil
+ observedBlobIndexes := make(map[string]int)
+ s.observedEventEntries = nil
+
+ // sort so that we can drop lowest priority efficiently
+ for _, eventHash := range slices.SortedFunc(maps.Keys(s.observedEvents), func(a string, b string) int {
+ ea, eb := s.observedEvents[a], s.observedEvents[b]
+ // Most votes first, so the events dropped first are those furthest from the F+1 they need. The deadline is not
+ // used: until an event has F+1 votes it has no value that is certain to be honest to take it from.
+ return cmp.Or(cmp.Compare(len(eb.NodeIds), len(ea.NodeIds)), cmp.Compare(a, b))
+ }) {
+ event := s.observedEvents[eventHash]
+ event.Blobs = nil // replace all, with one per vote
+ for _, voter := range event.NodeIds {
+ ref, ok := s.observedBlobs[eventHash][voter]
+ if !ok { // every vote has a blob, but keep Blobs aligned with NodeIds regardless
+ event.Blobs = append(event.Blobs, &pb.CoordinatedEventBlobHandle{Blob: math.MaxUint32})
+ continue
+ }
+
+ idx, ok := observedBlobIndexes[ref.handle]
+ if !ok {
+ idx = len(s.observedBlobHandles)
+ observedBlobIndexes[ref.handle] = idx
+ s.observedBlobHandles = append(s.observedBlobHandles, []byte(ref.handle))
+ }
+
+ event.Blobs = append(event.Blobs, &pb.CoordinatedEventBlobHandle{
+ Blob: uint32(idx), //nolint:gosec // G115: an index into at most maxObservedBlobHandles blob handles
+ Element: ref.element,
+ })
+ }
+
+ s.observedEventEntries = append(s.observedEventEntries, &pb.ConsensusQueueObservedEventEntry{
+ TimelessHash: []byte(eventHash), Event: event})
+ }
+}
+
+// prepareWrite initializes queued blob handles and updates the event references.
+func (s *kvState) prepareWriteBlobHandles() {
+ // gather blob handles and update events
+ s.queuedBlobHandles = nil
+ queuedBlobIndexes := make(map[string]int)
+ addBlobs := func(blobs map[string]uint32) []*pb.CoordinatedEventBlobHandle {
+ if len(blobs) == 0 {
+ return nil
+ }
+
+ blobHandles := make([]*pb.CoordinatedEventBlobHandle, 0, len(blobs))
+ for _, blobHandle := range slices.Sorted(maps.Keys(blobs)) {
+ ei := blobs[blobHandle]
+ idx, ok := queuedBlobIndexes[blobHandle]
+ if !ok {
+ idx = len(s.queuedBlobHandles)
+ queuedBlobIndexes[blobHandle] = idx
+ s.queuedBlobHandles = append(s.queuedBlobHandles, []byte(blobHandle))
+ }
+
+ blobHandles = append(blobHandles, &pb.CoordinatedEventBlobHandle{
+ Blob: uint32(idx), //nolint:gosec // G115: an index into at most maxObservedBlobHandles blob handles
+ Element: ei,
+ })
+ }
+
+ return blobHandles
+ }
+
+ for _, event := range s.queuedEvents {
+ event.Blobs = addBlobs(s.queuedBlobs[string(event.TimelessHash)])
+ }
+
+ for _, event := range s.consensusEvents {
+ event.Blobs = addBlobs(s.queuedBlobs[string(event.TimelessHash)])
+ }
+}
+
+// trimConsensusEvents moves the lowest priority consensus events (the last ones) back to the queue until the consensus
+// events and the blob handles fit: each in a value, and together in half of maxTotalBytes. The blob handles cover every
+// queued and consensus event, so they are the same wherever an event sits, and the events can be sized once.
+func (s *kvState) trimConsensusEvents(maxTotalBytes int) {
+ s.prepareWriteBlobHandles() // events carry their blob refs, and the handles are collected
+ blobs := proto.MarshalOptions{Deterministic: true}.Size(&pb.ConsensusQueueBlobHandleList{BlobHandles: s.queuedBlobHandles})
+
+ var events, n int
+ for ; n < len(s.consensusEvents); n++ {
+ next := events + protowire.SizeTag(1) + protowire.SizeBytes(proto.Size(s.consensusEvents[n])) // as an element of the list
+ if next > maxKeyValueValueBytes || blobs > maxKeyValueValueBytes || next+blobs > maxTotalBytes/2 {
+ break
+ }
+
+ events = next
+ }
+
+ for _, event := range s.consensusEvents[n:] {
+ s.queuedEvents.push(event)
+ }
+
+ s.consensusEvents = s.consensusEvents[:n]
+}
+
+// queuedWorkflowCapacities returns a capacity of n for every workflow that has a queued event.
+func (s *kvState) queuedWorkflowCapacities(n uint32) map[string]uint32 {
+ caps := make(map[string]uint32)
+ for _, event := range s.queuedEvents {
+ caps[event.WorkflowID] = n
+ }
+ return caps
+}
+
+// popConsensusEvents pops as many queuedEvents as possible in to consensusEvents, up to capacity (overall, and per
+// workflow) or the KV limits. Expired events are dropped.
+func (s *kvState) popConsensusEvents(capacity int, capPerWF map[string]uint32, expiration time.Time, maxTotalBytes int) {
+ popped, expired := s.queuedEvents.popEligible(capacity-len(s.consensusEvents), capPerWF, expiration)
+ s.stats.expiredQueued += expired
+ s.consensusEvents = append(s.consensusEvents, popped...)
+ s.trimConsensusEvents(maxTotalBytes)
+}
+
+// pruneObservedToFit drops the lowest priority observed events until that value, and the overall size, fit.
+//
+// Size only ever shrinks as more events are dropped, so the fewest to drop is found by binary search, rather than by
+// dropping one at a time and measuring the whole state again each time (which is quadratic, and took 300ms to drop 500).
+func (s *kvState) pruneObservedToFit(maxTotalBytes int) {
+ s.prepareWriteObservedEvents() // populates the entries, sorted by decreasing priority, so the last are dropped first
+ fits := func() bool { return s.sizeOfObservedEvents() <= maxKeyValueValueBytes && s.sizeOf() <= maxTotalBytes }
+ if len(s.observedEventEntries) == 0 || fits() {
+ return
+ }
+
+ entries, all := s.observedEventEntries, s.observedEvents
+ keepFirst := func(n int) { // n is how many of the highest priority events to keep
+ kept := make(map[string]*pb.ConsensusQueueObservedEvent, n)
+ for _, e := range entries[:n] {
+ kept[string(e.TimelessHash)] = all[string(e.TimelessHash)]
+ }
+ s.observedEvents = kept
+ }
+ // the most that fit, in terms of those dropped: fewest dropped is the most kept
+ dropped := sort.Search(len(entries), func(drop int) bool {
+ keepFirst(len(entries) - drop)
+ return fits()
+ })
+ keepFirst(len(entries) - dropped)
+ s.stats.prunedObserved += dropped
+}
+
+// pruneQueuedToFit drops the lowest priority events of those that were newly queued until the queued events, the blob
+// handles, and the overall size fit. As for pruneObservedToFit, the fewest to drop is found by binary search.
+func (s *kvState) pruneQueuedToFit(newlyQueued []string, maxTotalBytes int) {
+ fits := func() bool {
+ return s.sizeOfQueuedEvents() <= maxKeyValueValueBytes && s.sizeOfBlobHandles() <= maxKeyValueValueBytes && s.sizeOf() <= maxTotalBytes
+ }
+ if len(newlyQueued) == 0 || fits() {
+ return
+ }
+
+ newlyQueuedSet := map[string]struct{}{}
+ for _, hash := range newlyQueued {
+ newlyQueuedSet[hash] = struct{}{}
+ }
+ eligibleEvents := make([]*pb.ConsensusQueueEvent, 0, len(s.queuedEvents))
+ for _, e := range s.queuedEvents {
+ if _, ok := newlyQueuedSet[string(e.TimelessHash)]; ok {
+ eligibleEvents = append(eligibleEvents, e)
+ }
+ }
+ // lowest priority (latest deadline) first, which is the order they are dropped in
+ slices.SortFunc(eligibleEvents, func(a, b *pb.ConsensusQueueEvent) int { return b.CompareDeadline(a) })
+
+ queued := s.queuedEvents
+ drop := func(n int) {
+ dropped := make(map[*pb.ConsensusQueueEvent]struct{}, n)
+ for _, e := range eligibleEvents[:n] {
+ dropped[e] = struct{}{}
+ }
+ s.queuedEvents = slices.DeleteFunc(slices.Clone(queued), func(e *pb.ConsensusQueueEvent) bool { _, ok := dropped[e]; return ok })
+ }
+ n := sort.Search(len(eligibleEvents), func(n int) bool {
+ drop(n)
+ return fits()
+ })
+ drop(n)
+ s.stats.prunedQueued += n
+
+ // rebuild the priority queue
+ heap.Init(&s.queuedEvents)
+}
+
+// writeAll writes full state to the KV store, including consensus events.
+// prepareWrite must be called to include blob handles.
+func (s *kvState) writeTo(w *stateWriter) error {
+ s.prepareWriteObservedEvents()
+ s.prepareWriteBlobHandles()
+
+ err := w.writeValue(observedEventsKey, &pb.ConsensusQueueObservedEvents{Observations: s.observedEventEntries, BlobHandles: s.observedBlobHandles})
+ if err != nil {
+ return fmt.Errorf("failed to write observed events: %w", err)
+ }
+
+ err = w.writeValue(queuedEventsKey, &pb.ConsensusQueueEventList{Events: s.queuedEvents})
+ if err != nil {
+ return fmt.Errorf("failed to write queued events: %w", err)
+ }
+
+ err = w.writeValue(consensusEventsKey, &pb.ConsensusQueueEventList{Events: s.consensusEvents})
+ if err != nil {
+ return fmt.Errorf("failed to write consensus events: %w", err)
+ }
+
+ err = w.writeValue(blobHandlesKey, &pb.ConsensusQueueBlobHandleList{BlobHandles: s.queuedBlobHandles})
+ if err != nil {
+ return fmt.Errorf("failed to write blob handles: %w", err)
+ }
+
+ return nil
+}
+
+// pruneExpiredObservations deletes expired observations, but does not evict on = 2*f+1:
+ // new proposal straight to priority queue
+ s.queuedBlobs.addAll(eventHash, observedBlobs.handles(eventHash))
+ event := s.queueObservations(eventHash, eventToAdd)
+ onQueued(event)
+ case len(eventToAdd.NodeIds) >= f+1:
+ // new proposal to the observation set
+ s.observedBlobs[eventHash] = maps.Clone(observedBlobs[eventHash])
+ s.observedEvents[eventHash] = eventToAdd
+ default:
+ // new proposal without enough observations < f + 1
+ }
+ } else {
+ // update proposal
+ // (quadratic in the number of nodes, which is small)
+ for i, node := range eventToAdd.NodeIds {
+ if prev := slices.Index(obsEvent.NodeIds, node); prev == -1 {
+ obsEvent.NodeIds = append(obsEvent.NodeIds, node)
+ obsEvent.ObservedAts = append(obsEvent.ObservedAts, eventToAdd.ObservedAts[i])
+ obsEvent.Deadlines = append(obsEvent.Deadlines, eventToAdd.Deadlines[i])
+ } else { // overwrite previous observation
+ obsEvent.ObservedAts[prev] = eventToAdd.ObservedAts[i]
+ obsEvent.Deadlines[prev] = eventToAdd.Deadlines[i]
+ }
+
+ // the voter's blob, which replaces its previous one
+ if ref, ok := observedBlobs[eventHash][node]; ok {
+ s.observedBlobs.add(eventHash, node, ref.handle, ref.element)
+ }
+ }
+
+ if len(obsEvent.NodeIds) >= 2*f+1 {
+ // promote proposal to priority queue
+ delete(s.observedEvents, eventHash)
+ s.queuedBlobs.addAll(eventHash, s.observedBlobs.handles(eventHash))
+ delete(s.observedBlobs, eventHash)
+ event := s.queueObservations(eventHash, obsEvent)
+ onQueued(event)
+ }
+ }
+ }
+}
+
+// readConsensusState reads the consensus events and blob handles from the kvReader.
+func readConsensusState(kvReader ocr3_1types.KeyValueStateReader) ([]*pb.ConsensusQueueEvent, [][]byte, error) {
+ v, err := kvReader.Read([]byte(consensusEventsKey))
+ if err != nil {
+ return nil, nil, fmt.Errorf("failed to read consensus events: %w", err)
+ }
+
+ var consensusEvents []*pb.ConsensusQueueEvent
+ if v != nil {
+ var pbs pb.ConsensusQueueEventList
+ if err = proto.Unmarshal(v, &pbs); err != nil {
+ return nil, nil, fmt.Errorf("failed to unmarshal consensus events: %w", err)
+ }
+
+ consensusEvents = pbs.GetEvents()
+ }
+
+ blobHandles, err := readBlobHandles(kvReader)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ return consensusEvents, blobHandles, nil
+}
+
+// readBlobHandles reads the blob handles from the kvReader.
+func readBlobHandles(kvReader ocr3_1types.KeyValueStateReader) ([][]byte, error) {
+ v, err := kvReader.Read([]byte(blobHandlesKey))
+ if err != nil {
+ return nil, fmt.Errorf("failed to read blob handles: %w", err)
+ }
+
+ var blobHandles [][]byte
+ if v != nil {
+ var bs pb.ConsensusQueueBlobHandleList
+ if err = proto.Unmarshal(v, &bs); err != nil {
+ return nil, fmt.Errorf("failed to unmarshal consensus blob handles: %w", err)
+ }
+
+ blobHandles = bs.GetBlobHandles()
+ }
+
+ return blobHandles, err
+}
diff --git a/core/services/ocr3_1/plugins/queue/kvstate_test.go b/core/services/ocr3_1/plugins/queue/kvstate_test.go
new file mode 100644
index 00000000000..c2a901b0ebc
--- /dev/null
+++ b/core/services/ocr3_1/plugins/queue/kvstate_test.go
@@ -0,0 +1,1027 @@
+package queue
+
+import (
+ "container/heap"
+ "fmt"
+ "maps"
+ "math/rand"
+ "slices"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/types/known/timestamppb"
+
+ "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb"
+)
+
+// memKV is an in-memory ocr3_1types.KeyValueStateReadWriter.
+type memKV map[string][]byte
+
+func (m memKV) Read(k []byte) ([]byte, error) { return m[string(k)], nil }
+func (m memKV) Write(k, v []byte) error {
+ if v == nil {
+ v = []byte{}
+ }
+ m[string(k)] = v
+ return nil
+}
+func (m memKV) Delete(k []byte) error { delete(m, string(k)); return nil }
+
+func qEvent(wf, execID, hash string, deadlineSec int64) *pb.ConsensusQueueEvent {
+ return &pb.ConsensusQueueEvent{
+ WorkflowID: wf, ExecutionID: execID, TimelessHash: []byte(hash),
+ ObservedAt: ts(deadlineSec - 1), Deadline: ts(deadlineSec),
+ }
+}
+
+// obsEvent is an observed event seen by the given nodes, each with deadline base+nodeID.
+func obsEvent(wf, execID string, base int64, nodes ...byte) *pb.ConsensusQueueObservedEvent {
+ e := &pb.ConsensusQueueObservedEvent{WorkflowID: wf, ExecutionID: execID, NodeIds: nodes}
+ for _, n := range nodes {
+ e.ObservedAts = append(e.ObservedAts, ts(base+int64(n)-1))
+ e.Deadlines = append(e.Deadlines, ts(base+int64(n)))
+ }
+ return e
+}
+
+func newKVState() *kvState {
+ return &kvState{
+ observedEvents: map[string]*pb.ConsensusQueueObservedEvent{},
+ observedBlobs: voterBlobs{},
+ queuedBlobs: blobHandleMap{},
+ }
+}
+
+func TestPriorityQueue_Order(t *testing.T) {
+ t.Parallel()
+
+ var pq priorityQueue
+ pq.push(qEvent("wf", "c", "h3", 30))
+ pq.push(qEvent("wf", "a", "h2", 10)) // same deadline as next, ordered by hash
+ pq.push(qEvent("wf", "b", "h1", 10))
+ pq.push(qEvent("wf", "d", "h4", 20))
+
+ var got []string
+ for pq.Len() > 0 {
+ got = append(got, string(pq.mustPop().TimelessHash))
+ }
+ require.Equal(t, []string{"h1", "h2", "h4", "h3"}, got)
+ require.Nil(t, pq.mustPop(), "empty queue pops nil")
+}
+
+func TestPopLimited(t *testing.T) {
+ t.Parallel()
+
+ now := int64(100)
+ expiration := time.Unix(now, 0)
+
+ t.Run("drops expired", func(t *testing.T) {
+ t.Parallel()
+ var pq priorityQueue
+ pq.push(qEvent("wf", "old", "h1", now-10))
+ pq.push(qEvent("wf", "new", "h2", now+10))
+ got := pq.popLimited(map[string]uint32{"wf": 5}, expiration)
+ require.NotNil(t, got)
+ assert.Equal(t, "new", got.ExecutionID)
+ assert.Equal(t, 0, pq.Len(), "expired event is dropped, not restored")
+ })
+
+ t.Run("workflow capacity limits and restores", func(t *testing.T) {
+ t.Parallel()
+ var pq priorityQueue
+ pq.push(qEvent("full", "a", "h1", now+1)) // first by deadline, but no capacity
+ pq.push(qEvent("ok", "b", "h2", now+2))
+ caps := map[string]uint32{"ok": 1}
+ got := pq.popLimited(caps, expiration)
+ require.NotNil(t, got)
+ assert.Equal(t, "b", got.ExecutionID)
+ assert.Equal(t, uint32(0), caps["ok"], "capacity is decremented")
+ require.Equal(t, 1, pq.Len(), "limited event is restored")
+ assert.Equal(t, "a", pq.mustPop().ExecutionID)
+ })
+
+ t.Run("absent workflow has no capacity", func(t *testing.T) {
+ t.Parallel()
+ var pq priorityQueue
+ pq.push(qEvent("unknown", "a", "h1", now+1))
+ require.Nil(t, pq.popLimited(map[string]uint32{}, expiration))
+ assert.Equal(t, 1, pq.Len())
+ })
+
+ t.Run("empty", func(t *testing.T) {
+ t.Parallel()
+ var pq priorityQueue
+ require.Nil(t, pq.popLimited(nil, expiration))
+ })
+}
+
+func TestBlobHandleMap(t *testing.T) {
+ t.Parallel()
+
+ m := blobHandleMap{}
+ m.add("h1", "b1", 3)
+ m.add("h1", "b2", 4)
+ m.addAll("h1", map[string]uint32{"b2": 9, "b3": 1})
+ m.addAll("h2", nil)
+
+ assert.Equal(t, map[string]uint32{"b1": 3, "b2": 9, "b3": 1}, m["h1"], "addAll overwrites and merges")
+ assert.Contains(t, m, "h2")
+ assert.Empty(t, m["h2"])
+}
+
+func TestVoterBlobs(t *testing.T) {
+ t.Parallel()
+
+ m := voterBlobs{}
+ m.add("h", 1, "b1", 3)
+ m.add("h", 2, "b1", 5) // shares a blob, and disagrees about where the event is
+ m.add("h", 3, "b2", 9)
+ m.add("h", 1, "b3", 4) // voter 1 votes again
+
+ assert.Equal(t, map[uint8]blobRef{1: {"b3", 4}, 2: {"b1", 5}, 3: {"b2", 9}}, m["h"], "a voter has one blob, the latest")
+ assert.Equal(t, map[string]uint32{"b1": 5, "b3": 4, "b2": 9}, m.handles("h"))
+ assert.Empty(t, m.handles("unknown"))
+
+ t.Run("handles picks the lowest index when voters disagree, whatever the order", func(t *testing.T) {
+ for range 50 {
+ m := voterBlobs{}
+ for _, voter := range rand.Perm(10) {
+ m.add("h", uint8(voter), "shared", uint32(100+voter)) //nolint:gosec // G115: small test values
+ }
+ require.Equal(t, map[string]uint32{"shared": 100}, m.handles("h"))
+ }
+ })
+}
+
+// A voter that votes again, round after round, must not make the blobs of an event grow: that would let one oracle
+// fill the KV state, and have every other event pruned from it, and give the event a dead blob to try for each round.
+func TestAddObservedEvents_OneBlobPerVoter(t *testing.T) {
+ t.Parallel()
+ const f = 2 // so that 2 or 3 votes stay in the observed set (it takes 2f+1=5 to promote)
+
+ s := newKVState()
+ s.observedEvents["h"] = obsEvent("wf", "e", 100, 1, 2)
+ s.observedBlobs.add("h", 1, "blob-1", 0)
+ s.observedBlobs.add("h", 2, "blob-2", 0)
+
+ for round := range 200 {
+ blobs := voterBlobs{}
+ blobs.add("h", 2, fmt.Sprintf("fresh-blob-%d", round), uint32(round)) // node 2 keeps voting, with a new blob each time
+ s.addObservedEvents(f, map[string]*pb.ConsensusQueueObservedEvent{"h": obsEvent("wf", "e", 100, 2)}, blobs, func(*pb.ConsensusQueueEvent) {})
+ }
+
+ require.Contains(t, s.observedEvents, "h")
+ assert.Equal(t, []byte{1, 2}, s.observedEvents["h"].NodeIds)
+ assert.Equal(t, map[uint8]blobRef{1: {"blob-1", 0}, 2: {"fresh-blob-199", 199}}, s.observedBlobs["h"], "still one blob each")
+
+ // and so it is on disk
+ s.prepareWriteObservedEvents()
+ assert.Len(t, s.observedEventEntries[0].Event.Blobs, 2)
+ assert.Len(t, s.observedBlobHandles, 2)
+}
+
+func TestPruneExpiredObservations(t *testing.T) {
+ t.Parallel()
+
+ expiration := time.Unix(100, 0)
+
+ t.Run("all expired deletes entry", func(t *testing.T) {
+ t.Parallel()
+ s := newKVState()
+ s.observedEvents["gone"] = obsEvent("wf", "e1", 10, 1, 2)
+ s.pruneExpiredObservations(expiration)
+ assert.Empty(t, s.observedEvents)
+ })
+
+ t.Run("none expired keeps entry intact", func(t *testing.T) {
+ t.Parallel()
+ s := newKVState()
+ s.observedEvents["keep"] = obsEvent("wf", "e1", 200, 1, 2)
+ s.pruneExpiredObservations(expiration)
+ require.Contains(t, s.observedEvents, "keep")
+ assert.Equal(t, []byte{1, 2}, s.observedEvents["keep"].NodeIds)
+ })
+
+ t.Run("partially expired removes only expired and keeps slices aligned", func(t *testing.T) {
+ t.Parallel()
+ s := newKVState()
+ e := obsEvent("wf", "e1", 0, 1, 2, 3, 4)
+ // nodes 1 & 3 expired, 2 & 4 live
+ e.Deadlines = []*timestamppb.Timestamp{ts(50), ts(150), ts(60), ts(160)}
+ s.observedEvents["h"] = e
+ s.pruneExpiredObservations(expiration)
+
+ got := s.observedEvents["h"]
+ require.NotNil(t, got)
+ assert.Equal(t, []byte{2, 4}, got.NodeIds)
+ require.Len(t, got.Deadlines, 2)
+ require.Len(t, got.ObservedAts, 2)
+ assert.Equal(t, int64(150), got.Deadlines[0].Seconds)
+ assert.Equal(t, int64(160), got.Deadlines[1].Seconds)
+ assert.Equal(t, int64(1), got.ObservedAts[0].Seconds, "observedAts stay paired with node 2")
+ assert.Equal(t, int64(3), got.ObservedAts[1].Seconds, "observedAts stay paired with node 4")
+ })
+}
+
+func TestAddObservedEvents(t *testing.T) {
+ t.Parallel()
+ const f = 1
+
+ collect := func(into *[]*pb.ConsensusQueueEvent) func(*pb.ConsensusQueueEvent) {
+ return func(e *pb.ConsensusQueueEvent) { *into = append(*into, e) }
+ }
+
+ t.Run("fewer than f+1 is ignored", func(t *testing.T) {
+ t.Parallel()
+ s := newKVState()
+ var queued []*pb.ConsensusQueueEvent
+ s.addObservedEvents(f, map[string]*pb.ConsensusQueueObservedEvent{"h": obsEvent("wf", "e", 100, 1)}, voterBlobs{}, collect(&queued))
+ assert.Empty(t, s.observedEvents)
+ assert.Empty(t, s.queuedEvents)
+ assert.Empty(t, queued)
+ })
+
+ t.Run("f+1 goes to observed set", func(t *testing.T) {
+ t.Parallel()
+ s := newKVState()
+ var queued []*pb.ConsensusQueueEvent
+ blobs := voterBlobs{}
+ blobs.add("h", 1, "blob-1", 0)
+ blobs.add("h", 2, "blob-2", 3)
+ s.addObservedEvents(f, map[string]*pb.ConsensusQueueObservedEvent{"h": obsEvent("wf", "e", 100, 1, 2)}, blobs, collect(&queued))
+ require.Contains(t, s.observedEvents, "h")
+ assert.Empty(t, s.queuedEvents)
+ assert.Empty(t, queued)
+ assert.Equal(t, map[uint8]blobRef{1: {"blob-1", 0}, 2: {"blob-2", 3}}, s.observedBlobs["h"], "each voter's blob")
+ })
+
+ t.Run("2f+1 goes straight to the priority queue", func(t *testing.T) {
+ t.Parallel()
+ s := newKVState()
+ var queued []*pb.ConsensusQueueEvent
+ blobs := voterBlobs{}
+ for voter := range uint8(3) {
+ blobs.add("h", voter+1, "blob", 0) // the voters share a blob
+ }
+ s.addObservedEvents(f, map[string]*pb.ConsensusQueueObservedEvent{"h": obsEvent("wf", "e", 100, 1, 2, 3)}, blobs, collect(&queued))
+ assert.Empty(t, s.observedEvents)
+ require.Len(t, s.queuedEvents, 1)
+ require.Len(t, queued, 1)
+ assert.Equal(t, "h", string(queued[0].TimelessHash))
+ assert.Equal(t, int64(102), queued[0].Deadline.Seconds, "median of 101,102,103")
+ assert.Equal(t, map[string]uint32{"blob": 0}, s.queuedBlobs["h"])
+ })
+
+ t.Run("update promotes at 2f+1 and carries blobs", func(t *testing.T) {
+ t.Parallel()
+ s := newKVState()
+ var queued []*pb.ConsensusQueueEvent
+ // previously observed by nodes 1 & 2 (with their blobs)
+ s.observedEvents["h"] = obsEvent("wf", "e", 100, 1, 2)
+ s.observedBlobs.add("h", 1, "blob-1", 1)
+ s.observedBlobs.add("h", 2, "old-blob-2", 2)
+
+ newBlobs := voterBlobs{}
+ newBlobs.add("h", 2, "new-blob-2", 5) // node 2 votes again, with a new blob
+ newBlobs.add("h", 3, "blob-3", 7)
+ // node 3 is new; node 2 re-observes with a new deadline
+ toAdd := obsEvent("wf", "e", 100, 2, 3)
+ toAdd.Deadlines[0] = ts(500)
+ s.addObservedEvents(f, map[string]*pb.ConsensusQueueObservedEvent{"h": toAdd}, newBlobs, collect(&queued))
+
+ assert.Empty(t, s.observedEvents, "promoted out of the observed set")
+ assert.Empty(t, s.observedBlobs, "observed blobs moved")
+ require.Len(t, queued, 1)
+ assert.Equal(t, map[string]uint32{"blob-1": 1, "new-blob-2": 5, "blob-3": 7}, s.queuedBlobs["h"], "node 2's old blob is replaced, not kept")
+ })
+
+ t.Run("update below 2f+1 stays observed and does not panic", func(t *testing.T) {
+ t.Parallel()
+ s := newKVState()
+ s.observedEvents["h"] = obsEvent("wf", "e", 100, 1, 2)
+ toAdd := obsEvent("wf", "e", 200, 2) // existing node, overwrite
+ require.NotPanics(t, func() {
+ s.addObservedEvents(f, map[string]*pb.ConsensusQueueObservedEvent{"h": toAdd}, voterBlobs{}, func(*pb.ConsensusQueueEvent) {})
+ })
+ got := s.observedEvents["h"]
+ require.NotNil(t, got)
+ assert.Equal(t, []byte{1, 2}, got.NodeIds)
+ assert.Equal(t, int64(202), got.Deadlines[1].Seconds, "node 2's deadline overwritten")
+ })
+}
+
+func TestKVState_RoundTrip(t *testing.T) {
+ t.Parallel()
+
+ s := newKVState()
+ s.observedEvents["obs"] = obsEvent("wf", "e-obs", 100, 1, 2)
+ s.observedBlobs.add("obs", 1, "blobA", 0)
+ s.observedBlobs.add("obs", 2, "blobC", 4)
+ s.queuedEvents.push(qEvent("wf", "e-q", "q", 300))
+ s.queuedBlobs.add("q", "blobB", 2)
+ s.consensusEvents = append(s.consensusEvents, qEvent("wf", "e-c", "c", 200))
+ s.queuedBlobs.add("c", "blobB", 7)
+
+ // size* calls prepare the write; mirrors what StateTransition does.
+ require.Positive(t, s.sizeOf())
+
+ kv := memKV{}
+ require.NoError(t, s.writeTo(&stateWriter{kv: kv}))
+
+ var loaded kvState
+ require.NoError(t, loaded.loadFrom(kv))
+ require.Contains(t, loaded.observedEvents, "obs")
+ assert.Equal(t, map[uint8]blobRef{1: {"blobA", 0}, 2: {"blobC", 4}}, loaded.observedBlobs["obs"], "each voter's blob survives a round trip")
+ require.Len(t, loaded.queuedEvents, 1)
+ assert.Equal(t, map[string]uint32{"blobB": 2}, loaded.queuedBlobs["q"])
+
+ consensus, handles, err := readConsensusState(kv)
+ require.NoError(t, err)
+ require.Len(t, consensus, 1)
+ require.Len(t, consensus[0].Blobs, 1)
+ assert.Equal(t, "blobB", string(handles[consensus[0].Blobs[0].Blob]))
+ assert.Equal(t, uint32(7), consensus[0].Blobs[0].Element)
+}
+
+// writeTo is called by StateTransition without any size check having run first when no events are popped/pruned.
+// It must still persist observed events and blob handles.
+func TestKVState_WriteToWithoutSizeCheck(t *testing.T) {
+ t.Parallel()
+
+ s := newKVState()
+ s.observedEvents["obs"] = obsEvent("wf", "e-obs", 100, 1, 2)
+ s.observedBlobs.add("obs", 1, "blobA", 0)
+ s.observedBlobs.add("obs", 2, "blobA", 0)
+ s.queuedEvents.push(qEvent("wf", "e-q", "q", 300))
+ s.queuedBlobs.add("q", "blobB", 2)
+
+ kv := memKV{}
+ require.NoError(t, s.writeTo(&stateWriter{kv: kv}))
+
+ var loaded kvState
+ require.NoError(t, loaded.loadFrom(kv))
+ assert.Contains(t, loaded.observedEvents, "obs", "observed events must be persisted")
+ require.Len(t, loaded.queuedEvents, 1)
+ assert.Equal(t, map[string]uint32{"blobB": 2}, loaded.queuedBlobs["q"], "queued event must keep its blob reference")
+}
+
+func TestPrepareWriteObservedEvents_Order(t *testing.T) {
+ t.Parallel()
+
+ s := newKVState()
+ s.observedEvents["few"] = obsEvent("wf", "zzz", 100, 1, 2)
+ s.observedEvents["many"] = obsEvent("wf", "b", 100, 1, 2, 3)
+ s.observedEvents["tie-x"] = obsEvent("wf", "same", 100, 1, 2)
+ s.observedEvents["tie-y"] = obsEvent("wf", "same", 100, 1, 2)
+
+ order := func() (got []string) {
+ s.prepareWriteObservedEvents()
+ for _, e := range s.observedEventEntries {
+ got = append(got, string(e.TimelessHash))
+ }
+ return
+ }
+ first := order()
+ require.Equal(t, "many", first[0], "most endorsed first, so the last (pruned) is the least endorsed")
+ require.Equal(t, []string{"few", "tie-x", "tie-y"}, first[1:], "ties on votes break on hash")
+ for range 50 { // map iteration is random; ties on votes and execution ID must still order identically
+ require.Equal(t, first, order())
+ }
+}
+
+// errKV fails reads and/or writes of specific keys.
+type errKV struct {
+ memKV
+ readErrKey, writeErrKey string
+}
+
+func (e *errKV) Read(k []byte) ([]byte, error) {
+ if string(k) == e.readErrKey {
+ return nil, errBoom
+ }
+ return e.memKV.Read(k)
+}
+
+func (e *errKV) Write(k, v []byte) error {
+ if string(k) == e.writeErrKey {
+ return errBoom
+ }
+ return e.memKV.Write(k, v)
+}
+
+var allKeys = []string{observedEventsKey, queuedEventsKey, consensusEventsKey, blobHandlesKey}
+
+func TestPriorityQueue_EdgeCases(t *testing.T) {
+ t.Parallel()
+
+ var nilPQ *priorityQueue
+ assert.Equal(t, 0, nilPQ.Len())
+
+ var pq priorityQueue
+ assert.Nil(t, pq.Pop())
+ assert.Nil(t, pq.mustPop())
+}
+
+func TestQueueObservations(t *testing.T) {
+ t.Parallel()
+
+ s := newKVState()
+ got := s.queueObservations("hash", obsEvent("wf", "exec", 100, 1, 2, 3))
+
+ assert.Equal(t, "wf", got.WorkflowID)
+ assert.Equal(t, "exec", got.ExecutionID)
+ assert.Equal(t, []byte("hash"), got.TimelessHash)
+ assert.Equal(t, int64(101), got.ObservedAt.Seconds, "median of 100,101,102")
+ assert.Equal(t, int64(102), got.Deadline.Seconds, "median of 101,102,103")
+ assert.Empty(t, got.Blobs, "blobs are tracked separately and attached on write")
+ require.Len(t, s.queuedEvents, 1)
+ assert.Same(t, got, s.queuedEvents[0])
+}
+
+func TestPopLimited_Sequence(t *testing.T) {
+ t.Parallel()
+
+ var pq priorityQueue
+ for i, d := range []int64{400, 100, 300, 200} {
+ pq.push(qEvent("a", string(rune('a'+i)), string(rune('a'+i)), d))
+ }
+ caps := map[string]uint32{"a": 2}
+ past := time.Unix(0, 0)
+
+ assert.Equal(t, int64(100), pq.popLimited(caps, past).Deadline.Seconds)
+ assert.Equal(t, int64(200), pq.popLimited(caps, past).Deadline.Seconds)
+ assert.Nil(t, pq.popLimited(caps, past), "workflow capacity exhausted")
+ require.Equal(t, 2, pq.Len(), "limited events are restored")
+
+ caps["a"] = 5
+ assert.Equal(t, int64(300), pq.popLimited(caps, past).Deadline.Seconds, "restored events keep priority order")
+ assert.Equal(t, int64(400), pq.popLimited(caps, past).Deadline.Seconds)
+}
+
+func TestReadFunctions(t *testing.T) {
+ t.Parallel()
+
+ t.Run("absent keys read as empty", func(t *testing.T) {
+ t.Parallel()
+ kv := memKV{}
+
+ queued, err := readQueuedEvents(kv)
+ require.NoError(t, err)
+ assert.Empty(t, queued)
+
+ observed, blobs, err := readObservedEvents(kv)
+ require.NoError(t, err)
+ assert.NotNil(t, observed, "must be usable as a map")
+ assert.NotNil(t, blobs)
+ assert.Empty(t, observed)
+
+ consensus, handles, err := readConsensusState(kv)
+ require.NoError(t, err)
+ assert.Empty(t, consensus)
+ assert.Empty(t, handles)
+
+ handles, err = readBlobHandles(kv)
+ require.NoError(t, err)
+ assert.Empty(t, handles)
+ })
+
+ t.Run("corrupt values error", func(t *testing.T) {
+ t.Parallel()
+ for _, key := range allKeys {
+ kv := memKV{key: {0xff, 0xff, 0xff}}
+ var err error
+ switch key {
+ case queuedEventsKey:
+ _, err = readQueuedEvents(kv)
+ case observedEventsKey:
+ _, _, err = readObservedEvents(kv)
+ case consensusEventsKey:
+ _, _, err = readConsensusState(kv)
+ case blobHandlesKey:
+ _, err = readBlobHandles(kv)
+ }
+ require.Error(t, err, key)
+ }
+ })
+
+ t.Run("read errors are returned", func(t *testing.T) {
+ t.Parallel()
+ _, err := readQueuedEvents(&errKV{readErrKey: queuedEventsKey})
+ require.ErrorIs(t, err, errBoom)
+ _, _, err = readObservedEvents(&errKV{readErrKey: observedEventsKey})
+ require.ErrorIs(t, err, errBoom)
+ _, _, err = readConsensusState(&errKV{readErrKey: consensusEventsKey})
+ require.ErrorIs(t, err, errBoom)
+ _, _, err = readConsensusState(&errKV{readErrKey: blobHandlesKey}) // blob handles are read as part of consensus state
+ require.ErrorIs(t, err, errBoom)
+ _, err = readBlobHandles(&errKV{readErrKey: blobHandlesKey})
+ require.ErrorIs(t, err, errBoom)
+ })
+}
+
+func TestLoadFrom_Errors(t *testing.T) {
+ t.Parallel()
+
+ for _, key := range []string{observedEventsKey, queuedEventsKey, blobHandlesKey} {
+ t.Run("read error "+key, func(t *testing.T) {
+ t.Parallel()
+ var s kvState
+ require.ErrorIs(t, s.loadFrom(&errKV{memKV: memKV{}, readErrKey: key}), errBoom)
+ })
+ t.Run("corrupt "+key, func(t *testing.T) {
+ t.Parallel()
+ var s kvState
+ require.Error(t, s.loadFrom(memKV{key: {0xff, 0xff, 0xff}}))
+ })
+ }
+
+ t.Run("consensus events are not loaded", func(t *testing.T) {
+ t.Parallel()
+ var s kvState
+ require.NoError(t, s.loadFrom(memKV{consensusEventsKey: {0xff, 0xff, 0xff}}))
+ assert.Empty(t, s.consensusEvents)
+ })
+}
+
+func TestWriteTo_Errors(t *testing.T) {
+ t.Parallel()
+
+ for _, key := range allKeys {
+ t.Run(key, func(t *testing.T) {
+ t.Parallel()
+ s := newKVState()
+ err := s.writeTo(&stateWriter{kv: &errKV{memKV: memKV{}, writeErrKey: key}})
+ require.ErrorIs(t, err, errBoom)
+ })
+ }
+}
+
+// sizeOf is used to stay within libocr's KV limits, so it must equal what is actually written.
+func TestKVState_SizeOfMatchesWrittenBytes(t *testing.T) {
+ t.Parallel()
+
+ s := newKVState()
+ s.observedEvents["o1"] = obsEvent("wf", "e-o1", 100, 1, 2)
+ s.observedEvents["o2"] = obsEvent("wf", "e-o2", 100, 1, 2, 3)
+ for _, voter := range []uint8{1, 2} {
+ s.observedBlobs.add("o1", voter, "blobA", 0)
+ }
+ for _, voter := range []uint8{1, 2, 3} {
+ s.observedBlobs.add("o2", voter, "blobA", 1)
+ }
+ s.queuedEvents.push(qEvent("wf", "e-q", "q", 300))
+ s.queuedBlobs.add("q", "blobB", 2)
+ s.consensusEvents = append(s.consensusEvents, qEvent("wf", "e-c", "c", 200))
+ s.queuedBlobs.add("c", "blobB", 3)
+
+ size := s.sizeOf()
+ kv := memKV{}
+ require.NoError(t, s.writeTo(&stateWriter{kv: kv}))
+
+ var written int
+ for k, v := range kv {
+ written += len(k) + len(v)
+ }
+ assert.Equal(t, written, size)
+}
+
+func TestPrepareWriteBlobHandles(t *testing.T) {
+ t.Parallel()
+
+ // resolve returns an event's blob refs as handle -> element
+ resolve := func(s *kvState, e *pb.ConsensusQueueEvent) map[string]uint32 {
+ out := map[string]uint32{}
+ for _, b := range e.Blobs {
+ out[string(s.queuedBlobHandles[b.Blob])] = b.Element
+ }
+ return out
+ }
+
+ s := newKVState()
+ s.queuedEvents.push(qEvent("wf", "e1", "h1", 10))
+ s.queuedEvents.push(qEvent("wf", "e2", "h2", 20))
+ s.consensusEvents = append(s.consensusEvents, qEvent("wf", "e3", "h3", 5))
+ s.queuedBlobs.add("h1", "blobX", 0)
+ s.queuedBlobs.add("h2", "blobX", 1)
+ s.queuedBlobs.add("h3", "blobY", 0)
+ s.queuedBlobs.add("h3", "blobX", 2)
+
+ s.prepareWriteBlobHandles()
+
+ assert.ElementsMatch(t, [][]byte{[]byte("blobX"), []byte("blobY")}, s.queuedBlobHandles, "shared handles are stored once")
+ for _, e := range slices.Concat(s.queuedEvents, s.consensusEvents) {
+ assert.Equal(t, s.queuedBlobs[string(e.TimelessHash)], resolve(s, e), e.ExecutionID)
+ }
+
+ t.Run("idempotent", func(t *testing.T) {
+ t.Parallel()
+ handles := slices.Clone(s.queuedBlobHandles)
+ s.prepareWriteBlobHandles()
+ assert.Equal(t, handles, s.queuedBlobHandles)
+ for _, e := range slices.Concat(s.queuedEvents, s.consensusEvents) {
+ assert.Equal(t, s.queuedBlobs[string(e.TimelessHash)], resolve(s, e))
+ assert.Len(t, e.Blobs, len(s.queuedBlobs[string(e.TimelessHash)]), "blobs are replaced, not appended")
+ }
+ })
+
+ t.Run("event without blobs", func(t *testing.T) {
+ t.Parallel()
+ s := newKVState()
+ s.queuedEvents.push(qEvent("wf", "e1", "h1", 10))
+ require.NotPanics(t, s.prepareWriteBlobHandles)
+ assert.Empty(t, s.queuedBlobHandles)
+ assert.Empty(t, s.queuedEvents[0].Blobs)
+ })
+}
+
+func TestPrepareWriteObservedEvents_SharedBlobs(t *testing.T) {
+ t.Parallel()
+
+ s := newKVState()
+ s.observedEvents["h1"] = obsEvent("wf", "e1", 100, 1, 2)
+ s.observedEvents["h2"] = obsEvent("wf", "e2", 100, 1, 2)
+ s.observedBlobs.add("h1", 1, "blobX", 0)
+ s.observedBlobs.add("h1", 2, "blobX", 0)
+ s.observedBlobs.add("h2", 1, "blobX", 1)
+ s.observedBlobs.add("h2", 2, "blobY", 0) // two observers used different blobs
+
+ s.prepareWriteObservedEvents()
+
+ assert.ElementsMatch(t, [][]byte{[]byte("blobX"), []byte("blobY")}, s.observedBlobHandles, "a shared blob is stored once")
+ require.Len(t, s.observedEventEntries, 2)
+ for _, entry := range s.observedEventEntries {
+ hash := string(entry.TimelessHash)
+ require.Len(t, entry.Event.Blobs, len(entry.Event.NodeIds), "one blob per vote, aligned with NodeIds")
+ for i, voter := range entry.Event.NodeIds {
+ b := entry.Event.Blobs[i]
+ assert.Equal(t, blobRef{string(s.observedBlobHandles[b.Blob]), b.Element}, s.observedBlobs[hash][voter], "event %s voter %d", hash, voter)
+ }
+ }
+}
+
+// pruneExpiredObservations and popLimited must agree on whether a deadline equal to the expiration is expired.
+// popLimited keeps it (Deadline.Before(expiration) is false); pruning must not delete it either.
+func TestPruneExpiredObservations_BoundaryMatchesPopLimited(t *testing.T) {
+ t.Parallel()
+
+ expiration := time.Unix(100, 0)
+
+ var pq priorityQueue
+ pq.push(qEvent("wf", "e", "h", 100))
+ require.NotNil(t, pq.popLimited(map[string]uint32{"wf": 1}, expiration), "popLimited keeps an event whose deadline equals the expiration")
+
+ s := newKVState()
+ s.observedEvents["h"] = &pb.ConsensusQueueObservedEvent{
+ WorkflowID: "wf", ExecutionID: "e", NodeIds: []byte{1},
+ ObservedAts: []*timestamppb.Timestamp{ts(99)}, Deadlines: []*timestamppb.Timestamp{ts(100)}, // deadline == expiration
+ }
+ s.pruneExpiredObservations(expiration)
+ assert.Contains(t, s.observedEvents, "h", "pruning must not delete an observation popLimited would still accept")
+}
+
+func TestAddObservedEvents_Order(t *testing.T) {
+ t.Parallel()
+
+ toAdd := map[string]*pb.ConsensusQueueObservedEvent{}
+ for _, h := range []string{"d", "b", "e", "a", "c"} {
+ toAdd[h] = obsEvent("wf", "exec-"+h, 100, 1, 2, 3)
+ }
+ for range 20 { // map iteration is random; callbacks must not depend on it
+ s := newKVState()
+ var got []string
+ s.addObservedEvents(1, toAdd, voterBlobs{}, func(e *pb.ConsensusQueueEvent) { got = append(got, string(e.TimelessHash)) })
+ require.Equal(t, []string{"a", "b", "c", "d", "e"}, got)
+ }
+}
+
+// An event that already sits in the priority queue must not be promoted again if it is observed again
+// (e.g. by a node that was slow to drop it from its local queue).
+func TestAddObservedEvents_AlreadyQueued(t *testing.T) {
+ t.Parallel()
+
+ s := newKVState()
+ s.queuedEvents.push(qEvent("wf", "exec", "h", 100))
+ s.queuedBlobs.add("h", "blob", 0)
+
+ var queued int
+ s.addObservedEvents(1, map[string]*pb.ConsensusQueueObservedEvent{"h": obsEvent("wf", "exec", 100, 1, 2, 3)},
+ voterBlobs{}, func(*pb.ConsensusQueueEvent) { queued++ })
+
+ assert.Zero(t, queued, "already queued")
+ assert.Len(t, s.queuedEvents, 1, "no duplicate in the priority queue")
+}
+
+func TestAddObservedEvents_UpdateDeduplicatesNodes(t *testing.T) {
+ t.Parallel()
+
+ s := newKVState()
+ s.observedEvents["h"] = obsEvent("wf", "e", 100, 1, 2)
+ s.addObservedEvents(2, map[string]*pb.ConsensusQueueObservedEvent{"h": obsEvent("wf", "e", 100, 1, 2)}, voterBlobs{}, func(*pb.ConsensusQueueEvent) {})
+ assert.Equal(t, []byte{1, 2}, s.observedEvents["h"].NodeIds, "re-observation by the same nodes adds no votes")
+ assert.Empty(t, s.queuedEvents)
+}
+
+// revPQ pops the latest deadline first.
+type revPQ struct{ *priorityQueue }
+
+func (r *revPQ) Less(i, j int) bool {
+ a, b := (*r.priorityQueue)[i], (*r.priorityQueue)[j]
+ return b.CompareDeadline(a) < 0
+}
+
+// naivePruneObservedToFit is the original algorithm: drop the last event and measure everything again, until it fits.
+// (The original read the entries before they were refreshed, so it panicked when the rest of the state alone was over
+// the limit and the last observed event was dropped. This one refreshes them first.)
+func naivePruneObservedToFit(s *kvState, maxTotalBytes int) {
+ for {
+ s.prepareWriteObservedEvents()
+ if len(s.observedEventEntries) == 0 || (s.sizeOfObservedEvents() <= maxKeyValueValueBytes && s.sizeOf() <= maxTotalBytes) {
+ return
+ }
+ delete(s.observedEvents, string(s.observedEventEntries[len(s.observedEventEntries)-1].TimelessHash))
+ }
+}
+
+// naivePruneQueuedToFit is the original algorithm: pop the lowest priority new event, drop it, and measure everything again.
+func naivePruneQueuedToFit(s *kvState, newlyQueued []string, maxTotalBytes int) {
+ fits := func() bool {
+ return s.sizeOfQueuedEvents() <= maxKeyValueValueBytes && s.sizeOfBlobHandles() <= maxKeyValueValueBytes && s.sizeOf() <= maxTotalBytes
+ }
+ if len(newlyQueued) == 0 || fits() {
+ return
+ }
+ set := map[string]struct{}{}
+ for _, h := range newlyQueued {
+ set[h] = struct{}{}
+ }
+ var eligible []*pb.ConsensusQueueEvent
+ for _, e := range s.queuedEvents {
+ if _, ok := set[string(e.TimelessHash)]; ok {
+ eligible = append(eligible, e)
+ }
+ }
+ backwards := &revPQ{priorityQueue: new(priorityQueue(eligible))}
+ heap.Init(backwards)
+ for backwards.Len() > 0 && !fits() {
+ toRemove := heap.Pop(backwards).(*pb.ConsensusQueueEvent)
+ s.queuedEvents = slices.DeleteFunc(s.queuedEvents, func(e *pb.ConsensusQueueEvent) bool { return e == toRemove })
+ }
+ heap.Init(&s.queuedEvents)
+}
+
+// randomState builds a state with observed and queued events sharing a pool of blob handles.
+func randomState(seed int64) (s *kvState, newlyQueued []string) {
+ rng := rand.New(rand.NewSource(seed))
+ s = newKVState()
+ pool := make([]string, 3+rng.Intn(12))
+ for i := range pool {
+ pool[i] = string(handleBytes(byte(i + 1)))
+ }
+ for i := range 5 + rng.Intn(120) {
+ hash := fmt.Sprintf("observed-%03d", i)
+ nodes := make([]byte, 2+rng.Intn(3))
+ for v := range nodes {
+ nodes[v] = byte(v)
+ }
+ s.observedEvents[hash] = obsEvent(hexID("wf", i%7), hexID("exec-o", i), int64(100+rng.Intn(1000)), nodes...)
+ for _, node := range nodes {
+ s.observedBlobs.add(hash, node, pool[rng.Intn(len(pool))], uint32(rng.Intn(1000))) //nolint:gosec // G115: small test values
+ }
+ }
+ for i := range 5 + rng.Intn(200) {
+ hash := fmt.Sprintf("queued-%03d", i)
+ s.queuedEvents.push(&pb.ConsensusQueueEvent{
+ WorkflowID: hexID("wf", i%7), ExecutionID: hexID("exec-q", i), TimelessHash: []byte(hash),
+ ObservedAt: ts(int64(rng.Intn(100))), Deadline: ts(int64(100 + rng.Intn(1000))),
+ })
+ for range 1 + rng.Intn(3) {
+ s.queuedBlobs.add(hash, pool[rng.Intn(len(pool))], uint32(rng.Intn(1000))) //nolint:gosec // G115: small test values
+ }
+ if rng.Intn(2) == 0 {
+ newlyQueued = append(newlyQueued, hash)
+ }
+ }
+ return s, newlyQueued
+}
+
+// The binary searches must drop exactly the events the one-at-a-time algorithms did, for any state and limit.
+func TestPruneToFit_MatchesNaive(t *testing.T) {
+ t.Parallel()
+
+ for seed := range int64(12) {
+ sizeProbe, _ := randomState(seed)
+ full := sizeProbe.sizeOf()
+ rng := rand.New(rand.NewSource(seed*7 + 1))
+ limits := []int{1, full / 8, full/4 + rng.Intn(full), full + 1} // nothing fits, a lot dropped, some dropped, none dropped
+ for _, maxTotal := range limits {
+ naive, newlyQueued := randomState(seed)
+ fast, _ := randomState(seed)
+
+ naivePruneObservedToFit(naive, maxTotal)
+ naivePruneQueuedToFit(naive, newlyQueued, maxTotal)
+ fast.pruneObservedToFit(maxTotal)
+ fast.pruneQueuedToFit(newlyQueued, maxTotal)
+
+ require.ElementsMatch(t, slices.Collect(maps.Keys(naive.observedEvents)), slices.Collect(maps.Keys(fast.observedEvents)),
+ "seed %d limit %d: observed events", seed, maxTotal)
+ hashes := func(q priorityQueue) (out []string) {
+ for _, e := range q {
+ out = append(out, string(e.TimelessHash))
+ }
+ return
+ }
+ require.Equal(t, hashes(naive.queuedEvents), hashes(fast.queuedEvents), "seed %d limit %d: queued events (and heap order)", seed, maxTotal)
+ }
+ }
+}
+
+// popLimited is the original way to pop: one event at a time, putting back the skipped events after each.
+func (p *priorityQueue) popLimited(capPerWF map[string]uint32, expiration time.Time) (event *pb.ConsensusQueueEvent) {
+ var wfLimited []*pb.ConsensusQueueEvent // omitted due to workflow limit
+ for {
+ event = p.mustPop()
+ if event == nil {
+ break
+ }
+
+ if event.Deadline.AsTime().Before(expiration) {
+ // drop expired
+ continue
+ }
+
+ if capPerWF[event.WorkflowID] == 0 {
+ // ignore but restore after
+ wfLimited = append(wfLimited, event)
+ continue
+ }
+
+ capPerWF[event.WorkflowID]--
+ break
+ }
+
+ // restore omitted for next time
+ for _, limited := range wfLimited {
+ p.push(limited)
+ }
+
+ return
+}
+
+func randomQueue(rng *rand.Rand, n int, workflows int) (priorityQueue, map[string]uint32) {
+ var pq priorityQueue
+ caps := map[string]uint32{}
+ for w := range workflows {
+ if rng.Intn(3) != 0 { // some workflows have no capacity at all
+ caps[hexID("wf", w)] = uint32(rng.Intn(6)) //nolint:gosec // G115: small test values
+ }
+ }
+ for i := range n {
+ pq.push(&pb.ConsensusQueueEvent{
+ WorkflowID: hexID("wf", rng.Intn(workflows)), ExecutionID: hexID("exec", i), TimelessHash: []byte(fmt.Sprintf("h%05d", i)),
+ ObservedAt: ts(1), Deadline: ts(int64(50 + rng.Intn(200))), // some are before the expiration
+ })
+ }
+ return pq, caps
+}
+
+// Popping in a single pass must pop the same events, in the same order, and leave the same ones queued, as popping
+// one at a time did.
+func TestPopEligible_MatchesPoppingOneAtATime(t *testing.T) {
+ t.Parallel()
+
+ expiration := time.Unix(100, 0)
+ for seed := range int64(100) {
+ rng := rand.New(rand.NewSource(seed))
+ n, workflows, want := rng.Intn(300), 1+rng.Intn(12), rng.Intn(60)
+
+ oneByOne, capsA := randomQueue(rand.New(rand.NewSource(seed*3+1)), n, workflows)
+ singlePass, capsB := randomQueue(rand.New(rand.NewSource(seed*3+1)), n, workflows)
+
+ var wantPopped []string
+ for len(wantPopped) < want {
+ event := oneByOne.popLimited(capsA, expiration)
+ if event == nil {
+ break
+ }
+ wantPopped = append(wantPopped, event.ExecutionID)
+ }
+ var gotPopped []string
+ popped, _ := singlePass.popEligible(want, capsB, expiration)
+ for _, event := range popped {
+ gotPopped = append(gotPopped, event.ExecutionID)
+ }
+
+ require.Equal(t, wantPopped, gotPopped, "seed %d: popped events", seed)
+ require.Equal(t, capsA, capsB, "seed %d: workflow capacities left", seed)
+ remaining := func(q priorityQueue) (out []string) {
+ for _, e := range q {
+ out = append(out, e.ExecutionID)
+ }
+ slices.Sort(out)
+ return
+ }
+ require.Equal(t, remaining(oneByOne), remaining(singlePass), "seed %d: events left in the queue", seed)
+ }
+}
+
+func TestPopEligible_Edges(t *testing.T) {
+ t.Parallel()
+
+ var pq priorityQueue
+ pq.push(qEvent(testWF, "a", "h1", 200))
+ popped, _ := pq.popEligible(0, map[string]uint32{testWF: 5}, time.Unix(0, 0))
+ assert.Empty(t, popped, "nothing wanted")
+ popped, _ = pq.popEligible(-3, map[string]uint32{testWF: 5}, time.Unix(0, 0))
+ assert.Empty(t, popped, "a negative amount is nothing")
+ assert.Equal(t, 1, pq.Len())
+ popped, expired := (&priorityQueue{}).popEligible(5, nil, time.Unix(0, 0))
+ assert.Empty(t, popped, "an empty queue")
+ assert.Zero(t, expired)
+}
+
+// Events waiting on a workflow without capacity must not slow down popping the rest: it was quadratic in them, with
+// 10000 of them taking 1.9s to pop 1000 events for other workflows.
+func BenchmarkPopEligible_StuckEvents(b *testing.B) {
+ for _, stuck := range []int{0, 1000, 10000} {
+ fill := func() priorityQueue {
+ var pq priorityQueue
+ for i := range stuck {
+ pq.push(&pb.ConsensusQueueEvent{WorkflowID: hexID("stuck", 0), ExecutionID: hexID("s", i), TimelessHash: []byte(fmt.Sprintf("s%06d", i)), Deadline: ts(int64(100 + i))})
+ }
+ for i := range 1000 {
+ pq.push(&pb.ConsensusQueueEvent{WorkflowID: hexID("ok", 0), ExecutionID: hexID("o", i), TimelessHash: []byte(fmt.Sprintf("o%06d", i)), Deadline: ts(int64(100000 + i))})
+ }
+ return pq
+ }
+ b.Run(fmt.Sprintf("single pass/%d stuck", stuck), func(b *testing.B) {
+ for range b.N {
+ b.StopTimer()
+ pq := fill()
+ b.StartTimer()
+ pq.popEligible(1000, map[string]uint32{hexID("ok", 0): 1000}, time.Unix(0, 0))
+ }
+ })
+ if stuck <= 1000 { // one at a time is too slow to wait for beyond this
+ b.Run(fmt.Sprintf("one at a time/%d stuck", stuck), func(b *testing.B) {
+ for range b.N {
+ b.StopTimer()
+ pq := fill()
+ caps := map[string]uint32{hexID("ok", 0): 1000}
+ b.StartTimer()
+ for range 1000 {
+ pq.popLimited(caps, time.Unix(0, 0))
+ }
+ }
+ })
+ }
+ }
+}
+
+// What a state transition removes from the state is counted, for the metrics.
+func TestKVState_Stats(t *testing.T) {
+ t.Parallel()
+
+ t.Run("observed events whose votes all expired", func(t *testing.T) {
+ t.Parallel()
+ s := newKVState()
+ s.observedEvents["old"] = obsEvent("wf", "e1", 10, 1, 2) // votes expired
+ s.observedEvents["old2"] = obsEvent("wf", "e2", 10, 1, 2) // votes expired
+ s.observedEvents["new"] = obsEvent("wf", "e3", 500, 1, 2)
+ s.pruneExpiredObservations(time.Unix(100, 0))
+ assert.Equal(t, 2, s.stats.expiredObserved)
+ assert.Len(t, s.observedEvents, 1)
+ })
+
+ t.Run("queued events that expired", func(t *testing.T) {
+ t.Parallel()
+ s := newKVState()
+ for i := range 5 {
+ s.queuedEvents.push(qEvent(testWF, fmt.Sprintf("e%d", i), fmt.Sprintf("h%d", i), int64(10+i*100))) // deadlines 10,110,210,...
+ }
+ s.popConsensusEvents(10, map[string]uint32{testWF: 10}, time.Unix(150, 0), 1<<20)
+ assert.Equal(t, 2, s.stats.expiredQueued, "those with deadlines before 150")
+ assert.Len(t, s.consensusEvents, 3)
+ })
+
+ t.Run("events pruned to fit", func(t *testing.T) {
+ t.Parallel()
+ naiveObserved, naiveQueued := 0, 0
+ for seed := range int64(12) {
+ s, newlyQueued := randomState(seed)
+ beforeObserved, beforeQueued := len(s.observedEvents), len(s.queuedEvents)
+ maxTotal := s.sizeOf() / 3
+
+ s.pruneObservedToFit(maxTotal)
+ s.pruneQueuedToFit(newlyQueued, maxTotal)
+
+ assert.Equal(t, beforeObserved-len(s.observedEvents), s.stats.prunedObserved, "seed %d", seed)
+ assert.Equal(t, beforeQueued-len(s.queuedEvents), s.stats.prunedQueued, "seed %d", seed)
+ naiveObserved += s.stats.prunedObserved
+ naiveQueued += s.stats.prunedQueued
+ }
+ assert.Positive(t, naiveObserved, "some of the cases prune observed events")
+ assert.Positive(t, naiveQueued, "some of the cases prune queued events")
+ })
+}
diff --git a/core/services/ocr3_1/plugins/queue/math.go b/core/services/ocr3_1/plugins/queue/math.go
new file mode 100644
index 00000000000..4d961b0ffd8
--- /dev/null
+++ b/core/services/ocr3_1/plugins/queue/math.go
@@ -0,0 +1,35 @@
+package queue
+
+import (
+ "slices"
+ "time"
+
+ "google.golang.org/protobuf/types/known/timestamppb"
+)
+
+// medianTimestamp returns the median value of a slice of timestamps.
+// len must be greater than 0.
+func medianTimestamp(s []*timestamppb.Timestamp) *timestamppb.Timestamp {
+ switch len(s) {
+ case 0:
+ panic("median: len must be greater than 0")
+ case 1:
+ return s[0]
+ }
+
+ times := make([]time.Time, len(s))
+ for i, t := range s {
+ times[i] = time.Unix(t.Seconds, int64(t.Nanos))
+ }
+
+ slices.SortFunc(times, time.Time.Compare)
+
+ if len(times)%2 == 1 {
+ return timestamppb.New(times[len(times)/2])
+ }
+
+ // avg of two
+ a, b := times[len(times)/2], times[len(times)/2-1]
+ diff := a.Sub(b)
+ return timestamppb.New(b.Add(diff / 2))
+}
diff --git a/core/services/ocr3_1/plugins/queue/math_test.go b/core/services/ocr3_1/plugins/queue/math_test.go
new file mode 100644
index 00000000000..d7c1c52e2c6
--- /dev/null
+++ b/core/services/ocr3_1/plugins/queue/math_test.go
@@ -0,0 +1,47 @@
+package queue
+
+import (
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/types/known/timestamppb"
+)
+
+func ts(sec int64) *timestamppb.Timestamp { return ×tamppb.Timestamp{Seconds: sec} }
+
+func TestMedianTimestamp(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ in []*timestamppb.Timestamp
+ want time.Time
+ }{
+ {"single", []*timestamppb.Timestamp{ts(7)}, time.Unix(7, 0)},
+ {"odd sorted", []*timestamppb.Timestamp{ts(1), ts(2), ts(3)}, time.Unix(2, 0)},
+ {"odd unsorted", []*timestamppb.Timestamp{ts(9), ts(1), ts(5)}, time.Unix(5, 0)},
+ {"even averages middle two", []*timestamppb.Timestamp{ts(10), ts(0), ts(4), ts(6)}, time.Unix(5, 0)},
+ {"even with nanos", []*timestamppb.Timestamp{{Seconds: 1, Nanos: 0}, {Seconds: 1, Nanos: 10}}, time.Unix(1, 5)},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ got := medianTimestamp(tt.in).AsTime()
+ assert.True(t, tt.want.Equal(got), "want %v got %v", tt.want, got)
+ })
+ }
+
+ t.Run("does not reorder input", func(t *testing.T) {
+ t.Parallel()
+ in := []*timestamppb.Timestamp{ts(3), ts(1), ts(2)}
+ medianTimestamp(in)
+ require.Equal(t, []int64{3, 1, 2}, []int64{in[0].Seconds, in[1].Seconds, in[2].Seconds})
+ })
+
+ t.Run("empty panics", func(t *testing.T) {
+ t.Parallel()
+ require.Panics(t, func() { medianTimestamp(nil) })
+ })
+}
diff --git a/core/services/ocr3_1/plugins/queue/metrics.go b/core/services/ocr3_1/plugins/queue/metrics.go
new file mode 100644
index 00000000000..1debd406d20
--- /dev/null
+++ b/core/services/ocr3_1/plugins/queue/metrics.go
@@ -0,0 +1,178 @@
+package queue
+
+import (
+ "context"
+ "fmt"
+ "sync"
+
+ "go.opentelemetry.io/otel/attribute"
+ "go.opentelemetry.io/otel/metric"
+ sdkmetric "go.opentelemetry.io/otel/sdk/metric"
+
+ "github.com/smartcontractkit/chainlink/v2/core/platform"
+)
+
+// MetricPrefix is the prefix of the consensus queue plugin's metrics. Those of its methods (durations, data sizes, the
+// KV and blob operations it makes) come from the beholder wrapper, as for any plugin.
+const MetricPrefix = "platform_consensus_queue"
+
+// unknownOrg labels the queue depth of workflows that are not registered on this node, so the depth adds up.
+const unknownOrg = "unknown"
+
+// The names of the KV values, as the state_bytes metric labels them.
+const (
+ stateObserved = "observed_events"
+ stateQueued = "queued_events"
+ stateConsensus = "consensus_events"
+ stateBlobs = "blob_handles"
+)
+
+// Why events left the consensus queue without being executed, for the dropped events metric.
+const (
+ dropExpired = "expired" // the event's deadline, and the grace period, had passed
+ dropExpiredObserved = "expired_observed" // every vote for the event expired before it had enough
+ dropPrunedObserved = "pruned_observed" // dropped from the observed events to fit the state limits
+ dropPrunedQueued = "pruned_queued" // dropped from the queued events to fit the state limits
+)
+
+// pluginMetrics are the consensus queue plugin's own instruments. They carry the plugin's config digest, and for the
+// depth the org of the workflows, but never a workflow.
+type pluginMetrics struct {
+ configDigest string
+
+ observedEvents metric.Int64Counter // events in this node's observations
+ observationEvents metric.Int64Histogram // events in each of this node's observations
+ admittedEvents metric.Int64Counter // events that reached consensus, and joined the queue
+ consensusEvents metric.Int64Counter // events chosen to be started, from the queue
+ droppedEvents metric.Int64Counter // events removed without being started, by reason
+ discardedEvents metric.Int64Counter // events removed from the local queue by KV drain mode, without being observed
+ queueDepth metric.Int64Gauge // events in the queue, by org
+ observedDepth metric.Int64Gauge // events waiting for enough votes to reach consensus
+ stateBytes metric.Int64Gauge // bytes in each KV value written by a state transition
+
+ mu sync.Mutex
+ depthOrgs map[string]struct{} // the orgs a depth was reported for, so that it is reported again as zero when it empties
+}
+
+func newPluginMetrics(meter metric.Meter, configDigest string) (*pluginMetrics, error) {
+ m := &pluginMetrics{configDigest: configDigest, depthOrgs: map[string]struct{}{}}
+ var err error
+ counter := func(name, description string) (c metric.Int64Counter) {
+ if err == nil {
+ c, err = meter.Int64Counter(MetricPrefix+"_"+name, metric.WithUnit("{event}"), metric.WithDescription(description))
+ }
+ return
+ }
+ gauge := func(name, description, unit string) (g metric.Int64Gauge) {
+ if err == nil {
+ g, err = meter.Int64Gauge(MetricPrefix+"_"+name, metric.WithUnit(unit), metric.WithDescription(description))
+ }
+ return
+ }
+ m.observedEvents = counter("observed_events_total", "Events in this node's observations")
+ m.admittedEvents = counter("admitted_events_total", "Events that reached consensus and were added to the queue")
+ m.consensusEvents = counter("consensus_events_total", "Events taken from the queue to be started, as decided by consensus")
+ m.droppedEvents = counter("dropped_events_total", "Events removed from the consensus queue without being started, by reason")
+ m.discardedEvents = counter("discarded_events_total", "Events removed from the local queue without being observed, because KV drain mode is on")
+ m.queueDepth = gauge("queue_depth", "Events in the consensus queue, by org (unknown for workflows not registered on this node)", "{event}")
+ m.observedDepth = gauge("observed_depth", "Events observed by too few nodes to have reached consensus yet", "{event}")
+ m.stateBytes = gauge("state_bytes", "Bytes in each of the KV values written by the last state transition", "By")
+ if err != nil {
+ return nil, fmt.Errorf("failed to create consensus queue metrics: %w", err)
+ }
+
+ m.observationEvents, err = meter.Int64Histogram(MetricPrefix+"_observation_events", metric.WithUnit("{event}"),
+ metric.WithDescription("Events in each of this node's observations"))
+ if err != nil {
+ return nil, fmt.Errorf("failed to create consensus queue observation events histogram: %w", err)
+ }
+ return m, nil
+}
+
+func (m *pluginMetrics) attrs(extra ...attribute.KeyValue) metric.MeasurementOption {
+ return metric.WithAttributes(append([]attribute.KeyValue{attribute.String("configDigest", m.configDigest)}, extra...)...)
+}
+
+// recordObservation records the events in an observation this node made.
+func (m *pluginMetrics) recordObservation(ctx context.Context, events int) {
+ m.observedEvents.Add(ctx, int64(events), m.attrs())
+ m.observationEvents.Record(ctx, int64(events), m.attrs())
+}
+
+// recordDiscarded records events removed from the local queue unobserved, in KV drain mode.
+func (m *pluginMetrics) recordDiscarded(ctx context.Context, events int) {
+ m.discardedEvents.Add(ctx, int64(events), m.attrs())
+}
+
+// transition is what a state transition did to the state, and what it left.
+type transition struct {
+ admitted int // events that reached consensus
+ consensus int // events chosen to be started
+ stats kvStats // events removed without being started
+ observed int // events waiting for votes
+ queuedByWF map[string]int // events in the queue, by workflow
+ stateBytes map[string]int // bytes written, by KV value
+}
+
+// recordTransition records a committed state transition. org maps a workflow to its org, if it has one on this node.
+func (m *pluginMetrics) recordTransition(ctx context.Context, t transition, org func(workflowID string) (string, bool)) {
+ m.admittedEvents.Add(ctx, int64(t.admitted), m.attrs())
+ m.consensusEvents.Add(ctx, int64(t.consensus), m.attrs())
+ for reason, n := range map[string]int{
+ dropExpired: t.stats.expiredQueued,
+ dropExpiredObserved: t.stats.expiredObserved,
+ dropPrunedObserved: t.stats.prunedObserved,
+ dropPrunedQueued: t.stats.prunedQueued,
+ } {
+ if n > 0 {
+ m.droppedEvents.Add(ctx, int64(n), m.attrs(attribute.String("reason", reason)))
+ }
+ }
+
+ m.observedDepth.Record(ctx, int64(t.observed), m.attrs())
+ for key, n := range t.stateBytes {
+ m.stateBytes.Record(ctx, int64(n), m.attrs(attribute.String("key", key)))
+ }
+ m.recordDepth(ctx, t.queuedByWF, org)
+}
+
+// recordDepth records the queue depth by org. An org that has no events now is recorded as zero once, as a gauge
+// would otherwise keep its last value.
+func (m *pluginMetrics) recordDepth(ctx context.Context, queuedByWF map[string]int, org func(workflowID string) (string, bool)) {
+ byOrg := make(map[string]int)
+ for workflowID, n := range queuedByWF {
+ orgID, ok := org(workflowID)
+ if !ok || orgID == "" {
+ orgID = unknownOrg
+ }
+ byOrg[orgID] += n
+ }
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ for orgID := range m.depthOrgs {
+ if _, ok := byOrg[orgID]; !ok {
+ byOrg[orgID] = 0
+ delete(m.depthOrgs, orgID)
+ }
+ }
+ for orgID, n := range byOrg {
+ m.queueDepth.Record(ctx, int64(n), m.attrs(attribute.String(platform.KeyOrganizationID, orgID)))
+ if n > 0 {
+ m.depthOrgs[orgID] = struct{}{}
+ }
+ }
+}
+
+// MetricViews returns the buckets of the plugin's histograms. All of a histogram's buckets must be defined when the
+// beholder client is created.
+func MetricViews() []sdkmetric.View {
+ return []sdkmetric.View{
+ sdkmetric.NewView(
+ sdkmetric.Instrument{Name: MetricPrefix + "_observation_events"},
+ sdkmetric.Stream{Aggregation: sdkmetric.AggregationExplicitBucketHistogram{
+ Boundaries: []float64{0, 1, 5, 10, 50, 100, 250, 500, 1000},
+ }},
+ ),
+ }
+}
diff --git a/core/services/ocr3_1/plugins/queue/metrics_test.go b/core/services/ocr3_1/plugins/queue/metrics_test.go
new file mode 100644
index 00000000000..53190f548bf
--- /dev/null
+++ b/core/services/ocr3_1/plugins/queue/metrics_test.go
@@ -0,0 +1,273 @@
+package queue
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "go.opentelemetry.io/otel/attribute"
+ sdkmetric "go.opentelemetry.io/otel/sdk/metric"
+ "go.opentelemetry.io/otel/sdk/metric/metricdata"
+
+ ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types"
+
+ "github.com/smartcontractkit/chainlink/v2/core/platform"
+ "github.com/smartcontractkit/chainlink/v2/core/services/workflows/v2/triggers"
+)
+
+// readerMetrics returns metrics recorded to a reader, which reads back what was recorded.
+func readerMetrics(t *testing.T) (*pluginMetrics, *sdkmetric.ManualReader) {
+ t.Helper()
+ reader := sdkmetric.NewManualReader()
+ mp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))
+ t.Cleanup(func() { _ = mp.Shutdown(context.Background()) })
+ m, err := newPluginMetrics(mp.Meter("test"), "digest-1")
+ require.NoError(t, err)
+ return m, reader
+}
+
+func matches(set attribute.Set, want map[string]string) bool {
+ for k, v := range want {
+ if got, ok := set.Value(attribute.Key(k)); !ok || got.AsString() != v {
+ return false
+ }
+ }
+ return true
+}
+
+func collectMetric(t *testing.T, reader *sdkmetric.ManualReader, name string) metricdata.Aggregation {
+ t.Helper()
+ var rm metricdata.ResourceMetrics
+ require.NoError(t, reader.Collect(t.Context(), &rm))
+ for _, sm := range rm.ScopeMetrics {
+ for _, m := range sm.Metrics {
+ if m.Name == MetricPrefix+"_"+name {
+ return m.Data
+ }
+ }
+ }
+ return nil
+}
+
+// total is the sum of a counter's series that have the attributes.
+func total(t *testing.T, reader *sdkmetric.ManualReader, name string, attrs map[string]string) (n int64) {
+ t.Helper()
+ data := collectMetric(t, reader, name)
+ if data == nil {
+ return 0
+ }
+ sum, ok := data.(metricdata.Sum[int64])
+ require.True(t, ok, "%s is %T", name, data)
+ for _, dp := range sum.DataPoints {
+ if matches(dp.Attributes, attrs) {
+ n += dp.Value
+ }
+ }
+ return n
+}
+
+// last is the value of the gauge series that has the attributes, and whether there is one.
+func last(t *testing.T, reader *sdkmetric.ManualReader, name string, attrs map[string]string) (int64, bool) {
+ t.Helper()
+ data := collectMetric(t, reader, name)
+ if data == nil {
+ return 0, false
+ }
+ g, ok := data.(metricdata.Gauge[int64])
+ require.True(t, ok, "%s is %T", name, data)
+ for _, dp := range g.DataPoints {
+ if matches(dp.Attributes, attrs) {
+ return dp.Value, true
+ }
+ }
+ return 0, false
+}
+
+func orgsOf(orgs map[string]string) func(string) (string, bool) {
+ return func(workflowID string) (string, bool) { org, ok := orgs[workflowID]; return org, ok }
+}
+
+func TestPluginMetrics_Observation(t *testing.T) {
+ t.Parallel()
+ m, reader := readerMetrics(t)
+
+ m.recordObservation(t.Context(), 7)
+ m.recordObservation(t.Context(), 0)
+ m.recordObservation(t.Context(), 3)
+
+ assert.Equal(t, int64(10), total(t, reader, "observed_events_total", map[string]string{"configDigest": "digest-1"}))
+ hist, ok := collectMetric(t, reader, "observation_events").(metricdata.Histogram[int64])
+ require.True(t, ok)
+ require.Len(t, hist.DataPoints, 1)
+ assert.Equal(t, uint64(3), hist.DataPoints[0].Count, "one per observation, including the empty one")
+ assert.Equal(t, int64(10), hist.DataPoints[0].Sum)
+}
+
+func TestPluginMetrics_Transition(t *testing.T) {
+ t.Parallel()
+ m, reader := readerMetrics(t)
+ ctx := t.Context()
+ orgs := orgsOf(map[string]string{"wf-a": "org-1", "wf-b": "org-1", "wf-c": "org-2"})
+
+ m.recordTransition(ctx, transition{
+ admitted: 3,
+ consensus: 2,
+ stats: kvStats{expiredQueued: 1, expiredObserved: 2, prunedObserved: 3, prunedQueued: 4},
+ observed: 5,
+ queuedByWF: map[string]int{
+ "wf-a": 2, "wf-b": 3, // org-1
+ "wf-c": 7, // org-2
+ "wf-gone": 4, // not registered on this node
+ "wf-no-org": 1, // registered, but with no org: counts as unknown too
+ },
+ stateBytes: map[string]int{stateObserved: 100, stateQueued: 200, stateConsensus: 300, stateBlobs: 400},
+ }, func(wf string) (string, bool) {
+ if wf == "wf-no-org" {
+ return "", true
+ }
+ return orgs(wf)
+ })
+
+ assert.Equal(t, int64(3), total(t, reader, "admitted_events_total", nil))
+ assert.Equal(t, int64(2), total(t, reader, "consensus_events_total", nil))
+ for reason, want := range map[string]int64{dropExpired: 1, dropExpiredObserved: 2, dropPrunedObserved: 3, dropPrunedQueued: 4} {
+ assert.Equal(t, want, total(t, reader, "dropped_events_total", map[string]string{"reason": reason}), reason)
+ }
+
+ depth := func(org string) int64 {
+ v, ok := last(t, reader, "queue_depth", map[string]string{platform.KeyOrganizationID: org})
+ require.True(t, ok, "depth for %s", org)
+ return v
+ }
+ assert.Equal(t, int64(5), depth("org-1"))
+ assert.Equal(t, int64(7), depth("org-2"))
+ assert.Equal(t, int64(5), depth(unknownOrg), "workflows without an org here are together")
+ assert.Equal(t, int64(5+7+5), depth("org-1")+depth("org-2")+depth(unknownOrg), "so that the depths add up to the queue")
+
+ observed, ok := last(t, reader, "observed_depth", nil)
+ require.True(t, ok)
+ assert.Equal(t, int64(5), observed)
+ for key, want := range map[string]int64{stateObserved: 100, stateQueued: 200, stateConsensus: 300, stateBlobs: 400} {
+ got, ok := last(t, reader, "state_bytes", map[string]string{"key": key})
+ require.True(t, ok, key)
+ assert.Equal(t, want, got, key)
+ }
+}
+
+func TestPluginMetrics_NothingDroppedIsNotRecorded(t *testing.T) {
+ t.Parallel()
+ m, reader := readerMetrics(t)
+ m.recordTransition(t.Context(), transition{admitted: 1}, orgsOf(nil))
+ assert.Nil(t, collectMetric(t, reader, "dropped_events_total"), "no series for reasons that did not happen")
+}
+
+// A gauge keeps its last value, so an org whose queue empties must be recorded as zero once.
+func TestPluginMetrics_DepthOfAnOrgThatEmpties(t *testing.T) {
+ t.Parallel()
+ m, reader := readerMetrics(t)
+ orgs := orgsOf(map[string]string{"wf-a": "org-1", "wf-b": "org-2"})
+ depth := func(org string) int64 {
+ v, ok := last(t, reader, "queue_depth", map[string]string{platform.KeyOrganizationID: org})
+ require.True(t, ok, org)
+ return v
+ }
+
+ m.recordTransition(t.Context(), transition{queuedByWF: map[string]int{"wf-a": 3, "wf-b": 4}}, orgs)
+ assert.Equal(t, int64(3), depth("org-1"))
+ assert.Equal(t, int64(4), depth("org-2"))
+
+ m.recordTransition(t.Context(), transition{queuedByWF: map[string]int{"wf-a": 1}}, orgs)
+ assert.Equal(t, int64(1), depth("org-1"))
+ assert.Equal(t, int64(0), depth("org-2"), "emptied, so recorded as zero rather than left at 4")
+
+ m.recordTransition(t.Context(), transition{}, orgs)
+ assert.Equal(t, int64(0), depth("org-1"))
+ assert.Equal(t, int64(0), depth("org-2"))
+
+ m.mu.Lock()
+ assert.Empty(t, m.depthOrgs, "orgs at zero are not tracked, so the set is bounded by the orgs with events")
+ m.mu.Unlock()
+}
+
+func TestMetricViews(t *testing.T) {
+ t.Parallel()
+ assert.NotEmpty(t, MetricViews())
+}
+
+// orgCoordinator knows the org of some workflows.
+type orgCoordinator struct {
+ noopCoordinator
+ orgs map[string]string
+}
+
+func (o orgCoordinator) WorkflowOrg(workflowID string) (string, bool) {
+ org, ok := o.orgs[workflowID]
+ return org, ok
+}
+
+var _ triggers.Coordinator = orgCoordinator{}
+
+// The metrics follow a plugin through rounds: the events it observes, those that reach consensus and wait in the queue
+// (by org), and those it then takes from the queue to start.
+func TestPluginMetrics_ThroughRounds(t *testing.T) {
+ t.Parallel()
+
+ c := newSTPlugin(t)
+ m, reader := readerMetrics(t)
+ c.metrics = m
+ c.triggerCoordinator = orgCoordinator{orgs: map[string]string{testWF: "org-1"}}
+ kv := memKV{}
+ events := mkEvents(t, 3, 2000)
+ allNodes := func(o nodeOpts) []ocrtypes.AttributedObservation {
+ return []ocrtypes.AttributedObservation{ao(t, 0, nodeObs(t, o, events...)), ao(t, 1, nodeObs(t, o, events...)), ao(t, 2, nodeObs(t, o, events...))}
+ }
+
+ // no capacity: three events reach consensus, and wait in the queue
+ noCapacity := nodeOpts{capacity: 0, wfCaps: map[string]uint32{testWF: 0}, expiration: 100}
+ require.NoError(t, stateTransition(t, c, kv, allNodes(noCapacity)...))
+ assert.Equal(t, int64(3), total(t, reader, "admitted_events_total", nil))
+ assert.Zero(t, total(t, reader, "consensus_events_total", nil))
+ depth, ok := last(t, reader, "queue_depth", map[string]string{platform.KeyOrganizationID: "org-1"})
+ require.True(t, ok)
+ assert.Equal(t, int64(3), depth, "the queue's depth, for the org of the workflow")
+ for key, size := range map[string]int{stateQueued: len(kv[queuedEventsKey]), stateObserved: len(kv[observedEventsKey]), stateBlobs: len(kv[blobHandlesKey])} {
+ got, _ := last(t, reader, "state_bytes", map[string]string{"key": key})
+ assert.Equal(t, int64(size), got, "%s is what was written", key)
+ }
+
+ // capacity for two: two are taken from the queue to be started
+ someCapacity := nodeOpts{capacity: 2, wfCaps: map[string]uint32{testWF: 2}, expiration: 100}
+ require.NoError(t, stateTransition(t, c, kv, allNodes(someCapacity)...))
+ assert.Equal(t, int64(3), total(t, reader, "admitted_events_total", nil), "nothing new was admitted")
+ assert.Equal(t, int64(2), total(t, reader, "consensus_events_total", nil))
+ depth, _ = last(t, reader, "queue_depth", map[string]string{platform.KeyOrganizationID: "org-1"})
+ assert.Equal(t, int64(1), depth)
+
+ // expired: the one left is dropped, not started. (No node observes anything, as the two that were started would
+ // be admitted again, which a pass through the engine's duplicate check is what prevents from being run.)
+ expired := nodeOpts{capacity: 5, wfCaps: map[string]uint32{testWF: 5}, expiration: 3000}
+ require.NoError(t, stateTransition(t, c, kv,
+ ao(t, 0, nodeObs(t, expired)), ao(t, 1, nodeObs(t, expired)), ao(t, 2, nodeObs(t, expired))))
+ assert.Equal(t, int64(2), total(t, reader, "consensus_events_total", nil))
+ assert.Equal(t, int64(1), total(t, reader, "dropped_events_total", map[string]string{"reason": dropExpired}))
+ depth, _ = last(t, reader, "queue_depth", map[string]string{platform.KeyOrganizationID: "org-1"})
+ assert.Zero(t, depth, "the queue is empty, which is recorded as zero")
+}
+
+// What an observation reports is counted when it is made.
+func TestPluginMetrics_ObservationsAreCounted(t *testing.T) {
+ t.Parallel()
+
+ events := mkEvents(t, 4, time.Now().Add(time.Hour).Unix())
+ blobs := &memBlobs{}
+ c := testPlugin(t, sliceQueue{events: events}, blobs, 1<<19)
+ m, reader := readerMetrics(t)
+ c.metrics = m
+
+ obs, err := observe(t, c, memKV{}, blobs)
+ require.NoError(t, err)
+ require.Len(t, obs.Events, 4)
+ assert.Equal(t, int64(4), total(t, reader, "observed_events_total", nil))
+}
diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go
index a3cdf43895b..a48d2a9f449 100644
--- a/core/services/ocr3_1/plugins/queue/queue.go
+++ b/core/services/ocr3_1/plugins/queue/queue.go
@@ -1,30 +1,122 @@
+// Package queue contains the consensus queue OCR 3.1 reporting plugin, which makes a DON agree on which coordinated
+// trigger events to execute, so that each runs once however many nodes saw it. The README has a diagram of a round.
+//
+// Each node has a local [triggers.Queue] of [triggers.CoordinatedEvent]. In Observation a node reports the events at the
+// front of its queue (that it hasn't voted for already), broadcasting them in blobs, and how much it can run. StateTransition
+// then turns the observations into one outcome, which is the same on every node:
+//
+// - an event that F+1 nodes observed (so at least one is honest) joins the KV state's priority queue, ordered by deadline
+// (with nanosecond precision) and then by hash;
+// - each round, events are popped from the priority queue into the consensus events, as many as the capacity allows,
+// both overall and per workflow, and expired events are dropped. Capacity is the F+1th lowest reported, with a node
+// that doesn't report a workflow counting as zero, so F faulty nodes can't raise or starve it. Expiration is the median.
+//
+// Committed (and the next Observation, as Committed isn't guaranteed to run) fetches the blob of each consensus event and
+// starts it with [triggers.Coordinator.StartExecution], without waiting for the execution, then removes it from the local
+// queue. Starting is idempotent, as the workflow engine ignores an execution ID it has seen, and is not retried: once an
+// event is in consensus it leaves the queue whether or not starting it worked.
+//
+// The KV state is bounded by the plugin's limits: events and blob handles are pruned, lowest priority first, to fit.
+// A faulty node can't make the others spend unbounded CPU, storage or blob handles, as observations and the blobs they
+// refer to are bounded, and each voter has one blob per event.
+//
+// FeatureConsensusQueueKVDrainActivePeriod is a recovery mode. While more than F nodes report it, rounds only work
+// through the existing state: no new events are observed or queued, and every queued event is taken regardless of capacity.
+//
+// The plugin knows nothing of shadow mode: the coordinator decides whether StartExecution runs an event.
package queue
import (
+ "bytes"
+ "cmp"
"context"
+ "crypto/sha256"
+ "errors"
"fmt"
+ "maps"
+ "math"
+ "slices"
+ "sync"
+ "time"
+ "go.opentelemetry.io/otel/metric"
+ "golang.org/x/sync/errgroup"
+ "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/reflect/protoreflect"
+ "google.golang.org/protobuf/types/known/timestamppb"
+
+ "github.com/smartcontractkit/libocr/commontypes"
"github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types"
"github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types"
ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types"
"github.com/smartcontractkit/libocr/quorumhelper"
+ "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb"
+ "github.com/smartcontractkit/chainlink-common/pkg/config"
"github.com/smartcontractkit/chainlink-common/pkg/logger"
"github.com/smartcontractkit/chainlink-common/pkg/services"
+ "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/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
+ maxKeyValueValueBytes = ocr3_1types.MaxMaxKeyValueValueBytes
)
var _ ocr3_1types.ReportingPluginFactory[[]byte] = &consensusQueuePluginFactory{}
type consensusQueuePluginFactory struct {
- lggr logger.Logger
+ lggr logger.Logger
+ triggerCoordinator triggers.Coordinator
+ triggerQueue triggers.Queue
+ expirationDur func(context.Context) (time.Duration, error)
+ kvDrain func(ctx context.Context, at time.Time) (bool, error)
+ meter metric.Meter
}
-func NewConsensusQueuePluginFactory(lggr logger.Logger, limitsFactory limits.Factory) (ocr3_1types.ReportingPluginFactory[[]byte], error) {
- // TODO pass CentralTriggerQueue, CapacityReporter, EngineRegistry
- // TODO construct limiters
- return &consensusQueuePluginFactory{lggr: lggr}, nil
+// KVDrainActive returns a func that reports whether the KV drain recovery mode is on at a time, according to
+// FeatureConsensusQueueKVDrainActivePeriod. The setting is read on every call, never cached, so a change applies to the
+// next round without a restart. A read error is returned with false.
+func KVDrainActive(lf limits.Factory) func(ctx context.Context, at time.Time) (bool, error) {
+ return func(ctx context.Context, at time.Time) (bool, error) {
+ period, err := cresettings.Default.FeatureConsensusQueueKVDrainActivePeriod.GetOrDefault(ctx, lf.Settings)
+ if err != nil {
+ return false, err
+ }
+ return period.Contains(config.NewTimestamp(at)), nil
+ }
+}
+
+func NewConsensusQueuePluginFactory(
+ lggr logger.Logger,
+ limitsFactory limits.Factory,
+ triggerCoordinator triggers.Coordinator,
+ triggerQueue triggers.Queue,
+ meter metric.Meter,
+) (ocr3_1types.ReportingPluginFactory[[]byte], error) {
+ if triggerCoordinator == nil {
+ return nil, errors.New("triggerCoordinator cannot be nil")
+ }
+ if triggerQueue == nil {
+ return nil, errors.New("triggerQueue cannot be nil")
+ }
+ if meter == nil {
+ return nil, errors.New("meter cannot be nil")
+ }
+ return &consensusQueuePluginFactory{
+ lggr: lggr,
+ triggerCoordinator: triggerCoordinator,
+ triggerQueue: triggerQueue,
+ expirationDur: triggers.ConsensusQueueExpirationGrace(limitsFactory),
+ kvDrain: KVDrainActive(limitsFactory),
+ meter: meter,
+ }, nil
}
// NewReportingPlugin reads the plugin's OCR limits from config.OffchainConfig, which the config digest covers.
@@ -40,7 +132,13 @@ func (c *consensusQueuePluginFactory) NewReportingPlugin(ctx context.Context, co
}
c.lggr.Infow("Creating consensus-queue reporting plugin", "configDigest", config.ConfigDigest.String(), "limits", pluginLimits)
- plugin := newConsensusQueuePlugin(c.lggr, config)
+ metrics, err := newPluginMetrics(c.meter, config.ConfigDigest.String())
+ if err != nil {
+ return nil, nil, err
+ }
+
+ plugin := newConsensusQueuePlugin(c.lggr, config, pluginLimits, c.triggerCoordinator, c.triggerQueue, c.expirationDur, fetcher, metrics)
+ plugin.kvDrain = c.kvDrain
pluginInfo := ocr3_1types.ReportingPluginInfo1{
Name: "ConsensusQueueReportingPlugin",
Limits: pluginLimits,
@@ -52,17 +150,61 @@ var _ ocr3_1types.ReportingPlugin[[]byte] = &consensusQueuePlugin{}
type consensusQueuePlugin struct {
services.Service
- eng *services.Engine
- lggr logger.Logger
- onchainCfg ocr3types.ReportingPluginConfig
+ eng *services.Engine
+ lggr logger.Logger
+ onchainCfg ocr3types.ReportingPluginConfig
+ limits ocr3_1types.ReportingPluginLimits
+ blobHandleMarshalledBytesUpperBound int
+ triggerCoordinator triggers.Coordinator
+ triggerQueue triggers.Queue
+ blobBroadcastFetcher ocr3_1types.BlobBroadcastFetcher
+ 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 newConsensusQueuePlugin(lggr logger.Logger, onchainCfg ocr3types.ReportingPluginConfig) *consensusQueuePlugin {
- c := &consensusQueuePlugin{lggr: logger.Named(lggr, "ConsensusQueuePlugin"), onchainCfg: onchainCfg}
+// 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.
+//
+// In this mode the plugin only works through the state it already has, without consensus on anything new: Observation
+// reports no events, and discards those in the local queue, and StateTransition adds nothing to the state, and takes
+// every queued event for execution, as well as dropping expired ones. Committed is unchanged.
+//
+// Each node checks at its own expiration time (the time of the round, less the grace period) and reports the result in
+// its observation. StateTransition never reads the setting: it acts on the nodes' agreement, so that every node makes the
+// same transition. See observations.kvDrain.
+func (c *consensusQueuePlugin) draining(ctx context.Context, at time.Time) bool {
+ if c.kvDrain == nil {
+ return false
+ }
+ on, err := c.kvDrain(ctx, at)
+ if err != nil {
+ c.lggr.Warnw("Failed to check KV drain mode - treating it as off", "err", err)
+ return false
+ }
+ return on
+}
+
+func newConsensusQueuePlugin(
+ lggr logger.Logger, onchainCfg ocr3types.ReportingPluginConfig, limits ocr3_1types.ReportingPluginLimits, triggerCoordinator triggers.Coordinator,
+ triggerQueue triggers.Queue, expirationGraceDur func(context.Context) (time.Duration, error),
+ blobs ocr3_1types.BlobBroadcastFetcher, metrics *pluginMetrics,
+) *consensusQueuePlugin {
+ c := &consensusQueuePlugin{
+ lggr: logger.Named(lggr, "ConsensusQueuePlugin"),
+ onchainCfg: onchainCfg,
+ limits: limits,
+ blobHandleMarshalledBytesUpperBound: ocr3_1types.BlobHandleMarshalledBytesUpperBound(onchainCfg.N, onchainCfg.F),
+ triggerCoordinator: triggerCoordinator,
+ triggerQueue: triggerQueue,
+ blobBroadcastFetcher: blobs,
+ expirationDur: expirationGraceDur,
+ metrics: metrics,
+ }
c.Service, c.eng = services.Config{
Name: "ConsensusQueueReportingPlugin",
}.NewServiceEngine(lggr)
-
return c
}
@@ -71,45 +213,775 @@ func (c *consensusQueuePlugin) Query(_ context.Context, _ uint64, _ ocr3_1types.
}
func (c *consensusQueuePlugin) Observation(
- ctx context.Context, seqNr uint64, _ ocrtypes.AttributedQuery, kvState ocr3_1types.KeyValueStateReader, _ ocr3_1types.BlobBroadcastFetcher,
+ ctx context.Context, seqNr uint64, _ ocrtypes.AttributedQuery, kvReader ocr3_1types.KeyValueStateReader,
+ blobBroadcaster ocr3_1types.BlobBroadcastFetcher,
) (ocrtypes.Observation, error) {
- return nil, nil
+ // Always attempt to start any executions from the KV Store in the event Committed was not called. commitState is idempotent.
+ queuedEvents, err := c.commitState(ctx, kvReader)
+ if err != nil {
+ return nil, fmt.Errorf("failed to commit state: %w", err)
+ }
+
+ observedEvents, _, err := readObservedEvents(kvReader)
+ if err != nil {
+ return nil, err
+ }
+
+ capacity, err := c.triggerCoordinator.AvailableCapacity(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("failed to get available capacity: %w", err)
+ }
+
+ expirationGraceDur, err := c.expirationDur(ctx)
+ if err != nil {
+ c.lggr.Warnw("Failed to get expiration grace duration - using default", "err", err)
+ }
+
+ expiration := time.Now().Add(-expirationGraceDur)
+ obs := &pb.ConsensusQueueObservation{
+ // placeholder for accurate size calculation
+ BlobHandles: slices.Repeat([][]byte{make([]byte, c.blobHandleMarshalledBytesUpperBound)}, maxObservedBlobHandles),
+ Expiration: timestamppb.New(expiration),
+ Capacity: clampUint32(capacity.Global),
+ WorkflowCapacities: stateWorkflowCapacities(capacity, observedEvents, queuedEvents),
+ }
+
+ if c.draining(ctx, expiration) {
+ // No new events, so nothing to broadcast. The local queue is emptied, or it would only fill up.
+ obs.KvDrainActive = true
+ obs.BlobHandles = nil
+ if err = c.discardQueue(ctx); err != nil {
+ return nil, err
+ }
+ c.metrics.recordObservation(ctx, 0)
+ return proto.MarshalOptions{Deterministic: true}.Marshal(obs)
+ }
+ kvWFCapacities := maps.Clone(obs.WorkflowCapacities) // in case we need to rebuild later
+
+ events, err := c.assembleEvents(ctx, obs, observedEvents, capacity.PerWorkflow)
+ if err != nil {
+ return nil, err
+ }
+ obs.BlobHandles = nil // remove placeholders
+
+ fit, err := c.broadcastObservationBlobs(ctx, obs, blobBroadcaster, events, seqNr)
+ if err != nil {
+ return nil, err
+ }
+ if !fit { // events did not all fit, so rebuild the wf capacities
+ obs.WorkflowCapacities = kvWFCapacities
+ for _, event := range obs.Events {
+ if _, ok := obs.WorkflowCapacities[event.WorkflowID]; !ok {
+ obs.WorkflowCapacities[event.WorkflowID] = clampUint32(capacity.PerWorkflow[event.WorkflowID])
+ }
+ }
+ }
+
+ c.metrics.recordObservation(ctx, len(obs.Events))
+ return proto.MarshalOptions{Deterministic: true}.Marshal(obs)
+}
+
+// discardQueue removes the events at the front of the local queue, without observing them.
+func (c *consensusQueuePlugin) discardQueue(ctx context.Context) error {
+ var executionIDs []string
+ for _, event := range c.triggerQueue.Sorted(ctx, maxObservedEvents, c.maxEventBytes()) {
+ id, err := workflows.GenerateExecutionIDWithTriggerIndex(event.WorkflowID, event.Event.Event.Id, int(event.TriggerIndex))
+ if err != nil {
+ return fmt.Errorf("failed to generate execution ID: %w", err)
+ }
+ executionIDs = append(executionIDs, id)
+ }
+ c.triggerQueue.Remove(ctx, slices.Values(executionIDs))
+ c.metrics.recordDiscarded(ctx, len(executionIDs))
+ return nil
+}
+
+func clampUint32(v int) uint32 { return uint32(max(0, min(v, math.MaxUint32))) }
+
+// stateWorkflowCapacities returns the capacity of every workflow that has an observed or queued event in the KV state.
+func stateWorkflowCapacities(
+ capacity triggers.Capacity, observedEvents map[string]*pb.ConsensusQueueObservedEvent, queuedEvents []*pb.ConsensusQueueEvent,
+) map[string]uint32 {
+ capacities := make(map[string]uint32)
+ add := func(workflowID string) {
+ if wfCap, ok := capacity.PerWorkflow[workflowID]; ok {
+ capacities[workflowID] = clampUint32(wfCap)
+ }
+ }
+ for _, e := range observedEvents {
+ add(e.WorkflowID)
+ }
+ for _, e := range queuedEvents {
+ add(e.WorkflowID)
+ }
+ return capacities
+}
+
+// assembleEvents adds the local queue's events to obs, in order, up to the observation size limit. It returns the
+// events (without timestamps, as they will appear in blobs) to be broadcast.
+func (c *consensusQueuePlugin) assembleEvents(
+ ctx context.Context, obs *pb.ConsensusQueueObservation, observedEvents map[string]*pb.ConsensusQueueObservedEvent,
+ wfCapacities map[string]int,
+) ([]*pb.CoordinatedEvent, error) {
+ seenHashes := make(map[string]struct{})
+ var events []*pb.CoordinatedEvent
+ for timelessHash, event := range c.triggerQueue.Sorted(ctx, maxObservedEvents, c.maxEventBytes()) {
+ if _, ok := seenHashes[string(timelessHash)]; ok {
+ continue // ensure we don't observe duplicate events
+ }
+ seenHashes[string(timelessHash)] = struct{}{}
+
+ // skip if kv observation exists already
+ if obsEvent, ok := observedEvents[string(timelessHash)]; ok {
+ if slices.Contains(obsEvent.NodeIds, uint8(c.onchainCfg.OracleID)) {
+ continue
+ }
+ }
+
+ events = append(events, event)
+ newWF, err := observeEvent(obs, timelessHash, event, wfCapacities)
+ if err != nil {
+ return nil, err
+ }
+
+ if observationSize(obs) > c.limits.MaxObservationBytes {
+ // too large, remove this one
+ events = events[:len(events)-1]
+ obs.Events = obs.Events[:len(obs.Events)-1]
+ if newWF {
+ delete(obs.WorkflowCapacities, event.WorkflowID)
+ }
+ break
+ }
+ }
+ return events, nil
+}
+
+// observationSize returns the encoded size of an observation that grows as events are appended, without sizing every
+// event again each time (which would make assembling an observation quadratic).
+//
+// It uses proto.MarshalOptions.UseCachedSize, which reuses the size a previous Size call stored in each message. That
+// is only correct for a message that has not changed since it was sized, so it is not applied to obs itself, which does
+// change. Instead it sizes a shallow copy, a new message whose own size was never cached, and which shares obs's fields
+// (including any added to the message in the future). The events are unchanged since they were added, so their sizes
+// are valid. An event not sized yet has no cached size, and is computed as usual.
+//
+// Callers must not modify events, or any message inside them, between calls. (Marshaling obs, which does not use
+// cached sizes, recomputes and refreshes them, so modifying events afterwards is fine.)
+func observationSize(obs *pb.ConsensusQueueObservation) int {
+ m := obs.ProtoReflect()
+ probe := m.New()
+ m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
+ probe.Set(fd, v)
+ return true
+ })
+ return proto.MarshalOptions{Deterministic: true, UseCachedSize: true}.Size(probe.Interface())
+}
+
+// observeEvent adds the event to the observation and updates the workflow capacities if required.
+func observeEvent(
+ obs *pb.ConsensusQueueObservation, timelessHash []byte, event *pb.CoordinatedEvent, wfCapacities map[string]int,
+) (newWF bool, err error) {
+ observedAt, deadline := event.ObservedAt, event.Deadline
+ event.ObservedAt, event.Deadline = nil, nil // for consistent hashing
+
+ executionID, err := workflows.GenerateExecutionIDWithTriggerIndex(event.WorkflowID, event.Event.Event.Id, int(event.TriggerIndex))
+ if err != nil {
+ return false, fmt.Errorf("failed to generate execution ID: %w", err)
+ }
+
+ idx := len(obs.Events)
+ obs.Events = append(obs.Events, &pb.ConsensusQueueEvent{
+ WorkflowID: event.WorkflowID,
+ ExecutionID: executionID,
+ ObservedAt: observedAt,
+ Deadline: deadline,
+ TimelessHash: timelessHash,
+ Blobs: []*pb.CoordinatedEventBlobHandle{{
+ Blob: 0,
+ Element: uint32(idx), //nolint:gosec // G115: an index into at most maxObservedEvents events
+ }},
+ })
+
+ if _, ok := obs.WorkflowCapacities[event.WorkflowID]; !ok {
+ newWF = true
+ obs.WorkflowCapacities[event.WorkflowID] = clampUint32(wfCapacities[event.WorkflowID])
+ }
+
+ return
+}
+
+// broadcastObservationBlobs broadcasts up to maxObservedBlobHandles blobs containing events, and updates the observation.
+// It may not be able to broadcast all events, in which case the observed events will be truncated and false returned:
+// the events that did not fit in the blobs are dropped, and so are those of a blob that failed to broadcast. The blobs
+// that did broadcast are all kept, wherever they are among the failed ones.
+// The events are divided between blobs first, so that the blobs can be broadcast concurrently.
+// opt: remember blobs so we don't have to rebroadcast events maxObservedBlobHandles {
+ return fmt.Errorf("blob handles are limited to %d but got %d", maxObservedBlobHandles, len(obs.BlobHandles))
+ }
+ if obs.Expiration == nil {
+ return errors.New("expiration is missing")
+ }
+ if err = obs.Expiration.CheckValid(); err != nil {
+ return fmt.Errorf("invalid expiration: %w", err)
+ }
+ for i, handle := range obs.BlobHandles {
+ if len(handle) > c.blobHandleMarshalledBytesUpperBound {
+ return fmt.Errorf("blob handle %d is %d bytes, more than the maximum %d", i, len(handle), c.blobHandleMarshalledBytesUpperBound)
+ }
+ }
+
+ if obs.KvDrainActive && (len(obs.Events) > 0 || len(obs.BlobHandles) > 0) {
+ return fmt.Errorf("KV drain mode reports no new events, but got %d events and %d blob handles", len(obs.Events), len(obs.BlobHandles))
+ }
+
+ if len(obs.Events) > maxObservedEvents {
+ return fmt.Errorf("events are limited to %d but got %d", maxObservedEvents, len(obs.Events))
+ }
+
+ // ensure no duplicate execution ID, timelessHash, or blob handle
+ execIDs, timelessHashes := make(map[string]struct{}), make(map[string]struct{})
+ type blobHandle struct{ blob, element uint32 }
+ blobHandles := make(map[blobHandle]struct{})
+ for i, event := range obs.Events {
+ if _, ok := execIDs[event.ExecutionID]; ok {
+ return fmt.Errorf("duplicate workflow execution ID: %s", event.ExecutionID)
+ }
+ execIDs[event.ExecutionID] = struct{}{}
+
+ timelessHash := string(event.TimelessHash)
+ if _, ok := timelessHashes[timelessHash]; ok {
+ return fmt.Errorf("duplicate timeless hash: %x", event.TimelessHash)
+ }
+ timelessHashes[timelessHash] = struct{}{}
+ if len(event.Blobs) > 0 {
+ // note: validateObservedEvent will ensure there were no other blobs
+ bh := blobHandle{event.Blobs[0].Blob, event.Blobs[0].Element}
+ if _, ok := blobHandles[bh]; ok {
+ return fmt.Errorf("duplicate blob handle in event %d: %d/%d", i, bh.blob, bh.element)
+ }
+ }
+ }
+
+ var eg errgroup.Group
+ fetcher := blobCache{fetcher: blobFetcher, 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 {
+ return fmt.Errorf("event %d failed validation: %w", i, verr)
+ }
+ return nil
+ })
+ }
+ if err = eg.Wait(); err != nil {
+ return err
+ }
+
+ // ensure every event has an entry in the capacity map
+ for _, event := range obs.Events {
+ if _, ok := obs.WorkflowCapacities[event.WorkflowID]; !ok {
+ return fmt.Errorf("missing capacity for workflow ID %s", event.WorkflowID)
+ }
+ }
+
+ // ensure the capacity map only covers workflows an honest node reports: those with events in this observation,
+ // or with observed or queued events in the KV state
+ allowed := make(map[string]struct{})
+ for _, event := range obs.Events {
+ allowed[event.WorkflowID] = struct{}{}
+ }
+ observedEvents, _, err := readObservedEvents(kvReader)
+ if err != nil {
+ return fmt.Errorf("failed to read observed events: %w", err)
+ }
+ for _, event := range observedEvents {
+ allowed[event.WorkflowID] = struct{}{}
+ }
+ queuedEvents, err := readQueuedEvents(kvReader)
+ if err != nil {
+ return fmt.Errorf("failed to read queued events: %w", err)
+ }
+ for _, event := range queuedEvents {
+ allowed[event.WorkflowID] = struct{}{}
+ }
+ for wf := range obs.WorkflowCapacities {
+ if _, ok := allowed[wf]; !ok {
+ return fmt.Errorf("unexpected capacity for workflow ID %s", wf)
+ }
+ }
+
+ // wait to do this since we depend on every event being valid
+ if !slices.IsSortedFunc(obs.Events, (*pb.ConsensusQueueEvent).CompareDeadline) {
+ return errors.New("events must be sorted")
+ }
+
+ return nil
+}
+
+func validateObservedEvent(ctx context.Context, fetcher *blobCache, event *pb.ConsensusQueueEvent, blobHandles [][]byte) error {
+ if event.WorkflowID == "" {
+ return errors.New("event workflow id is missing")
+ }
+ if _, err := types.WorkflowIDFromHex(event.WorkflowID); err != nil { // the format an execution requires, which also bounds its length
+ return fmt.Errorf("invalid event workflow id: %w", err)
+ }
+ if event.ExecutionID == "" {
+ return errors.New("event execution id is missing") // (the exact value is checked against the blob below)
+ }
+ if event.ObservedAt == nil {
+ return errors.New("event observation ts is missing")
+ } else if err := event.ObservedAt.CheckValid(); err != nil {
+ return fmt.Errorf("invalid event observation ts: %w", err)
+ }
+ if event.Deadline == nil {
+ return errors.New("event deadline is missing")
+ } else if err := event.Deadline.CheckValid(); err != nil {
+ return fmt.Errorf("invalid event deadline: %w", err)
+ }
+ if len(event.TimelessHash) == 0 {
+ return errors.New("event blob hash is missing")
+ } else if len(event.TimelessHash) != sha256.Size {
+ return fmt.Errorf("event blob hash must be %d bytes but got %d", sha256.Size, len(event.TimelessHash))
+ }
+
+ if len(event.Blobs) == 0 {
+ return errors.New("event blob is missing")
+ }
+ if len(event.Blobs) > 1 {
+ return errors.New("event has more than one blob")
+ }
+
+ blobIdx := int(event.Blobs[0].Blob)
+ if blobIdx >= len(blobHandles) {
+ return fmt.Errorf("event blob index %d is out of range", blobIdx)
+ }
+ blobHandle := blobHandles[blobIdx]
+
+ coordEvent, pbBytes, err := fetchCoordinatedEventFromBlob(ctx, fetcher, blobHandle, int(event.Blobs[0].Element))
+ if err != nil {
+ return fmt.Errorf("failed to fetch event from blob: %w", err)
+ } else if coordEvent == nil {
+ return errors.New("failed to fetch event from blob: event is nil")
+ }
+
+ if coordEvent.WorkflowID != event.WorkflowID {
+ return fmt.Errorf("blob workflow ID %s does not match event workflow ID %s", coordEvent.WorkflowID, event.WorkflowID)
+ }
+ executionID, err := workflows.GenerateExecutionIDWithTriggerIndex(event.WorkflowID, coordEvent.GetEvent().GetEvent().GetId(), int(coordEvent.TriggerIndex))
+ if err != nil {
+ return fmt.Errorf("failed to generate execution ID: %w", err)
+ }
+ if executionID != event.ExecutionID {
+ return fmt.Errorf("blob derived execution ID %s does not match event execution ID %s", executionID, event.ExecutionID)
+ }
+
+ if coordEvent.ObservedAt != nil {
+ return fmt.Errorf("blob observation timestamp is not nil: %v", coordEvent.ObservedAt)
+ }
+ if coordEvent.Deadline != nil {
+ return fmt.Errorf("blob deadline timestamp is not nil: %v", coordEvent.Deadline)
+ }
+
+ if shaSum := sha256.Sum256(pbBytes); !bytes.Equal(shaSum[:], event.TimelessHash) {
+ return fmt.Errorf("blob hash %x does not match observation hash %x", shaSum, event.TimelessHash)
+ }
+
return nil
}
func (c *consensusQueuePlugin) ObservationQuorum(
- ctx context.Context, seqNr uint64, _ ocrtypes.AttributedQuery, aos []ocrtypes.AttributedObservation,
+ _ context.Context, _ uint64, _ ocrtypes.AttributedQuery, aos []ocrtypes.AttributedObservation,
_ ocr3_1types.KeyValueStateReader, _ ocr3_1types.BlobFetcher,
) (quorumReached bool, err error) {
return quorumhelper.ObservationCountReachesObservationQuorum(quorumhelper.QuorumTwoFPlusOne, c.onchainCfg.N, c.onchainCfg.F, aos), nil
}
func (c *consensusQueuePlugin) StateTransition(
- ctx context.Context, seqNr uint64, aq ocrtypes.AttributedQuery, aos []ocrtypes.AttributedObservation,
- kvState ocr3_1types.KeyValueStateReadWriter, _ ocr3_1types.BlobFetcher,
+ ctx context.Context, _ uint64, _ ocrtypes.AttributedQuery, aos []ocrtypes.AttributedObservation,
+ kvReaderWriter ocr3_1types.KeyValueStateReadWriter, _ ocr3_1types.BlobFetcher,
) (ocr3_1types.ReportsPlusPrecursor, error) {
- return ocr3_1types.ReportsPlusPrecursor{}, nil
+ // Aggregating the observations (CPU) and loading the state (KV) are independent, so they overlap: this takes
+ // about 9ms off a 43ms full round at N=31. Wait returns only when both are done, so neither outlives the call.
+ var (
+ obs observations
+ state kvState
+ eg errgroup.Group
+ )
+ eg.Go(func() error {
+ obs.aggregate(ctx, c.onchainCfg.F, aos) // reports cancellation as its error, so a partial result is never used
+ if obs.err != nil {
+ return fmt.Errorf("failed to aggregate observations: %w", obs.err)
+ }
+ return nil
+ })
+ eg.Go(func() error {
+ if err := state.loadFrom(kvReaderWriter); err != nil {
+ return fmt.Errorf("failed to read state: %w", err)
+ }
+ return nil
+ })
+ if err := eg.Wait(); err != nil {
+ return nil, err
+ }
+
+ // update state
+ state.pruneExpiredObservations(obs.medianExpiration)
+ var queuedTimelessHashes []string // eligible for pruning later if necessary
+ var admitted int
+ if obs.kvDrain {
+ state.pruneObservations(c.onchainCfg.F)
+ // Recovery: nothing new is added, and everything queued is taken, whatever the capacity.
+ state.popConsensusEvents(math.MaxInt32, state.queuedWorkflowCapacities(math.MaxUint32), obs.medianExpiration, c.limits.MaxKeyValueModifiedKeysPlusValuesBytes)
+ } else {
+ state.addObservedEvents(c.onchainCfg.F, obs.newObservedEvents, obs.observedBlobs, func(event *pb.ConsensusQueueEvent) {
+ queuedTimelessHashes = append(queuedTimelessHashes, string(event.TimelessHash))
+ admitted++
+ })
+ state.pruneObservations(c.onchainCfg.F)
+ state.popConsensusEvents(int(obs.fPlus1thCap), obs.fPlus1thCapPerWF, obs.medianExpiration, c.limits.MaxKeyValueModifiedKeysPlusValuesBytes)
+ }
+ state.pruneObservedToFit(c.limits.MaxKeyValueModifiedKeysPlusValuesBytes)
+ state.pruneQueuedToFit(queuedTimelessHashes, c.limits.MaxKeyValueModifiedKeysPlusValuesBytes)
+ // note: no need to prune consensus events, since already limited what we collected
+
+ writer := &stateWriter{kv: kvReaderWriter}
+ if err := state.writeTo(writer); err != nil {
+ return nil, err
+ }
+ c.recordTransition(ctx, &state, writer, admitted)
+
+ // no report to return, executions start when committed
+ return nil, nil
}
-func (c *consensusQueuePlugin) Committed(ctx context.Context, seqNr uint64, keyValueStateReader ocr3_1types.KeyValueStateReader) error {
- return nil
+// recordTransition records what a state transition did, once its state is written.
+func (c *consensusQueuePlugin) recordTransition(ctx context.Context, state *kvState, writer *stateWriter, admitted int) {
+ t := transition{
+ admitted: admitted,
+ consensus: len(state.consensusEvents),
+ stats: state.stats,
+ observed: len(state.observedEvents),
+ queuedByWF: make(map[string]int),
+ stateBytes: map[string]int{
+ stateObserved: writer.sizes[observedEventsKey],
+ stateQueued: writer.sizes[queuedEventsKey],
+ stateConsensus: writer.sizes[consensusEventsKey],
+ stateBlobs: writer.sizes[blobHandlesKey],
+ },
+ }
+ for _, event := range state.queuedEvents {
+ t.queuedByWF[event.WorkflowID]++
+ }
+ c.metrics.recordTransition(ctx, t, c.triggerCoordinator.WorkflowOrg)
+}
+
+type observations struct {
+ medianExpiration time.Time
+ fPlus1thCap uint32
+ fPlus1thCapPerWF map[string]uint32 // wf ID -> capacity
+ // kvDrain is whether the KV drain recovery mode is on: F+1 nodes say so, so at least one of them is honest. A faulty
+ // node alone can neither start it nor stop it. Near either end of the window nodes may disagree, and this decides.
+ kvDrain bool
+ newObservedEvents map[string]*pb.ConsensusQueueObservedEvent // key: timeless hash
+ observedBlobs voterBlobs
+
+ err error
+}
+
+func (res *observations) aggregate(ctx context.Context, f int, aos []ocrtypes.AttributedObservation) {
+ res.fPlus1thCapPerWF = make(map[string]uint32)
+ res.newObservedEvents = make(map[string]*pb.ConsensusQueueObservedEvent)
+ res.observedBlobs = make(voterBlobs)
+
+ // normalize the order, so that the outcome never depends on the order observations arrive in
+ if len(aos) <= f { // quorum guarantees more, but never index out of range
+ res.err = fmt.Errorf("need more than F=%d observations but got %d", f, len(aos))
+ return
+ }
+ aos = slices.SortedFunc(slices.Values(aos), func(a, b ocrtypes.AttributedObservation) int { return cmp.Compare(a.Observer, b.Observer) })
+
+ expirations := make([]*timestamppb.Timestamp, 0, len(aos))
+ drainVotes := 0
+ capacities := make([]uint32, 0, len(aos))
+ wfCapacities := make(map[string][]uint32)
+ for _, ao := range aos {
+ if err := ctx.Err(); err != nil { // a cancelled aggregation is partial, so it must never look successful
+ res.err = err
+ return
+ }
+ var obs pb.ConsensusQueueObservation
+ err := proto.Unmarshal(ao.Observation, &obs)
+ if err != nil {
+ res.err = fmt.Errorf("failed to unmarshal observation from oracle %d: %w", ao.Observer, err)
+ return
+ }
+ expirations = append(expirations, obs.Expiration)
+ if obs.KvDrainActive {
+ drainVotes++
+ }
+ capacities = append(capacities, obs.Capacity)
+ for wf, c := range obs.WorkflowCapacities {
+ wfCapacities[wf] = append(wfCapacities[wf], c)
+ }
+ for _, event := range obs.Events {
+ if err2 := ctx.Err(); err2 != nil {
+ res.err = err2
+ return
+ }
+ res.addEvent(ao.Observer, event, obs.BlobHandles)
+ }
+ }
+ res.medianExpiration = medianTimestamp(expirations).AsTime()
+ res.kvDrain = drainVotes > f
+
+ // If we used median, then honest nodes reporting reduced capacity would not be able to keep up.
+ // Instead, we use the F+1th lowest value - the least honest value.
+ res.fPlus1thCap = slices.Sorted(slices.Values(capacities))[f]
+ for wf, caps := range wfCapacities {
+ // A node that did not report a workflow counts as zero capacity. Otherwise up to F nodes (faulty, or just
+ // without the workflow) could omit it and leave too few reports to ever run it.
+ caps = append(caps, make([]uint32, len(aos)-len(caps))...)
+ res.fPlus1thCapPerWF[wf] = slices.Sorted(slices.Values(caps))[f]
+ }
+}
+
+// addEvent adds the observed event to the observation set, either merging it into an existing event or creating a new one.
+func (res *observations) addEvent(obs commontypes.OracleID, event *pb.ConsensusQueueEvent, blobHandles [][]byte) {
+ res.observedBlobs.add(string(event.TimelessHash), uint8(obs), string(blobHandles[event.Blobs[0].Blob]), event.Blobs[0].Element)
+ aggregated, ok := res.newObservedEvents[string(event.TimelessHash)]
+ if !ok {
+ res.newObservedEvents[string(event.TimelessHash)] = &pb.ConsensusQueueObservedEvent{
+ WorkflowID: event.WorkflowID,
+ ExecutionID: event.ExecutionID,
+ NodeIds: []uint8{uint8(obs)},
+ ObservedAts: []*timestamppb.Timestamp{event.ObservedAt},
+ Deadlines: []*timestamppb.Timestamp{event.Deadline},
+ Blobs: nil, // res.observedBlobs tracks these while in memory
+ }
+ } else {
+ // note: trigger event and workflow ID alignment is ensured by ValidateObservation
+ aggregated.NodeIds = append(aggregated.NodeIds, uint8(obs))
+ aggregated.ObservedAts = append(aggregated.ObservedAts, event.ObservedAt)
+ aggregated.Deadlines = append(aggregated.Deadlines, event.Deadline)
+ // note: res.observedBlobs tracks blobs while in memory
+ }
+}
+
+func (c *consensusQueuePlugin) Committed(ctx context.Context, _ uint64, kvReader ocr3_1types.KeyValueStateReader) error {
+ _, err := c.commitState(ctx, kvReader)
+ return err
+}
+
+// commitState executes the consensus events, and remove events from the trigger queue that have been queued or executed.
+// Starting an execution is best effort: once an event is in consensus, it leaves the local queue whether or not starting
+// it succeeds, and a failure is only logged. (Committed and the next Observation each try, as consensus events stay in
+// KV until the next StateTransition, but the queue never holds an event to retry it.)
+func (c *consensusQueuePlugin) commitState(ctx context.Context, kvReader ocr3_1types.KeyValueStateReader) ([]*pb.ConsensusQueueEvent, error) {
+ consensusEvents, blobHandles, err := readConsensusState(kvReader)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read consensus state: %w", err)
+ }
+
+ done := make(chan struct{})
+ defer func() { <-done }()
+ go c.tryStartExecutions(ctx, done, consensusEvents, blobHandles)
+
+ c.triggerQueue.Remove(ctx, func(yield func(string) bool) {
+ for _, e := range consensusEvents {
+ if !yield(e.ExecutionID) {
+ break
+ }
+ }
+ })
+ queuedEvents, err := readQueuedEvents(kvReader)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read queued events: %w", err)
+ }
+ c.triggerQueue.Remove(ctx, func(yield func(string) bool) {
+ for _, e := range queuedEvents {
+ if !yield(e.ExecutionID) {
+ break
+ }
+ }
+ })
+ return queuedEvents, nil
+}
+
+// tryStartExecutions calls StartExecution asynchronously on the corresponding engine for each trigger event.
+// 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))}
+ var wg sync.WaitGroup
+ for _, consensusEvent := range consensusEvents {
+ wg.Add(1)
+ // The commit's ctx is used throughout, not the one that the goroutine for the event is given, which ends with it.
+ // Attempts to read the event's blobs outlive it, and share the fetch of a blob with other events.
+ c.eng.GoCtx(ctx, func(context.Context) {
+ defer wg.Done()
+
+ if err2 := c.tryStartExecution(ctx, &fetcher, consensusEvent, blobHandles); err2 != nil {
+ c.lggr.Errorw("Failed to execute event", "executionID", consensusEvent.ExecutionID, "err", err2)
+ return
+ }
+ })
+ }
+
+ wg.Wait()
+}
+
+func (c *consensusQueuePlugin) tryStartExecution(ctx context.Context, fetcher *blobCache, consensusEvent *pb.ConsensusQueueEvent, blobHandles [][]byte) error {
+ pbEvent, err := c.fetchEvent(ctx, fetcher, consensusEvent, blobHandles)
+ if err != nil {
+ return err
+ }
+
+ // fill in medianized timestamps
+ pbEvent.ObservedAt = consensusEvent.ObservedAt
+ pbEvent.Deadline = consensusEvent.Deadline
+
+ var event triggers.CoordinatedEvent
+ if err := event.FromProto(pbEvent); err != nil {
+ return fmt.Errorf("failed to convert CoordinatedEvent from proto: %w", err)
+ }
+
+ // StartExecution returns once the execution has started, not when it finishes.
+ return c.triggerCoordinator.StartExecution(ctx, event)
+}
+
+// fetchEvent returns the event from the first of its blobs to provide it. Any blob will do, since each holds the same
+// event, but not every voter's blob is to be relied on: one may be slow, expired, or gone. So they are all tried at
+// once, which means that a bad one cannot hold up a good one, however it sorts.
+//
+// The attempts that are not needed are left to finish, not cancelled, because the cache shares one fetch of a blob
+// between every event that uses it. A cancellation is not kept as the result (see blobCache.fetchBlob), but cancelling
+// would still make the others sharing the fetch start it again. So ctx must outlive this event: it is the commit's,
+// which they end with.
+func (c *consensusQueuePlugin) fetchEvent(ctx context.Context, fetcher *blobCache, consensusEvent *pb.ConsensusQueueEvent, blobHandles [][]byte) (*pb.CoordinatedEvent, error) {
+ type result struct {
+ event *pb.CoordinatedEvent
+ err error
+ }
+ results := make(chan result, len(consensusEvent.Blobs)) // buffered, so that attempts that are late do not block
+
+ var attempts int
+ for _, blob := range consensusEvent.Blobs {
+ if int(blob.Blob) >= len(blobHandles) {
+ c.lggr.Errorw("Blob handle index out of bounds", "index", int(blob.Blob), "len", len(blobHandles))
+ continue
+ }
+
+ attempts++
+ handle, element := blobHandles[blob.Blob], int(blob.Element)
+ c.eng.GoCtx(ctx, func(ctx context.Context) {
+ event, _, err := fetchCoordinatedEventFromBlob(ctx, fetcher, handle, element)
+ if err != nil {
+ c.lggr.Debugw("Failed to fetch event from blob", "handle", handle, "index", element, "err", err)
+ }
+ results <- result{event, err}
+ })
+ }
+
+ var errs []error
+ for range attempts {
+ r := <-results
+ if r.err == nil {
+ return r.event, nil
+ }
+ errs = append(errs, r.err)
+ }
+ return nil, fmt.Errorf("failed to fetch blob from all %d handles: %w", len(consensusEvent.Blobs), errors.Join(errs...))
}
-func (c *consensusQueuePlugin) Reports(ctx context.Context, seqNr uint64, reportsPlusPrecursor ocr3_1types.ReportsPlusPrecursor) ([]ocr3types.ReportPlus[[]byte], error) {
+func (c *consensusQueuePlugin) Reports(ctx context.Context, _ uint64, _ ocr3_1types.ReportsPlusPrecursor) ([]ocr3types.ReportPlus[[]byte], error) {
return nil, nil
}
-func (c *consensusQueuePlugin) ShouldAcceptAttestedReport(ctx context.Context, seqNr uint64, reportWithInfo ocr3types.ReportWithInfo[[]byte]) (bool, error) {
- return true, nil
+func (c *consensusQueuePlugin) ShouldAcceptAttestedReport(ctx context.Context, _ uint64, _ ocr3types.ReportWithInfo[[]byte]) (bool, error) {
+ return false, nil
}
-func (c *consensusQueuePlugin) ShouldTransmitAcceptedReport(ctx context.Context, seqNr uint64, reportWithInfo ocr3types.ReportWithInfo[[]byte]) (bool, error) {
- return true, nil
+func (c *consensusQueuePlugin) ShouldTransmitAcceptedReport(ctx context.Context, _ uint64, _ ocr3types.ReportWithInfo[[]byte]) (bool, error) {
+ return false, nil
}
diff --git a/core/services/ocr3_1/plugins/queue/queue_test.go b/core/services/ocr3_1/plugins/queue/queue_test.go
index 6876ef15b17..e3f4df9a909 100644
--- a/core/services/ocr3_1/plugins/queue/queue_test.go
+++ b/core/services/ocr3_1/plugins/queue/queue_test.go
@@ -1,17 +1,44 @@
package queue
import (
+ "bytes"
+ "cmp"
+ "context"
+ "crypto/sha256"
+ "errors"
+ "fmt"
+ "iter"
+ "maps"
+ "math"
+ "math/rand"
+ "slices"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
"testing"
+ "time"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
+ "go.opentelemetry.io/otel/metric/noop"
+ "google.golang.org/protobuf/encoding/protowire"
"google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/types/known/timestamppb"
+ "github.com/smartcontractkit/libocr/commontypes"
"github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types"
"github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types"
+ ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types"
+ "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb"
"github.com/smartcontractkit/chainlink-common/pkg/logger"
+ "github.com/smartcontractkit/chainlink-common/pkg/settings"
"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/queuepb"
+ "github.com/smartcontractkit/chainlink/v2/core/services/workflows/v2/triggers"
)
// TestConsensusQueuePluginFactory_NewReportingPlugin asserts the plugin takes its limits from the OCR offchain config
@@ -31,7 +58,7 @@ func TestConsensusQueuePluginFactory_NewReportingPlugin(t *testing.T) {
t.Run("limits come from the OCR config", func(t *testing.T) {
t.Parallel()
- factory, err := NewConsensusQueuePluginFactory(logger.Test(t), limits.Factory{})
+ factory, err := NewConsensusQueuePluginFactory(logger.Test(t), limits.Factory{}, noopCoordinator{}, noopQueue{}, noop.NewMeterProvider().Meter("test"))
require.NoError(t, err)
plugin, info, err := factory.NewReportingPlugin(t.Context(), ocr3types.ReportingPluginConfig{N: 4, F: 1, OffchainConfig: validCfg}, nil)
@@ -60,7 +87,7 @@ func TestConsensusQueuePluginFactory_NewReportingPlugin(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
- factory, err := NewConsensusQueuePluginFactory(logger.Test(t), limits.Factory{})
+ 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: tt.got}, nil)
@@ -69,3 +96,2610 @@ func TestConsensusQueuePluginFactory_NewReportingPlugin(t *testing.T) {
})
}
}
+
+type noopCoordinator struct{}
+
+func (n noopCoordinator) Start(ctx context.Context) error {
+ return nil
+}
+
+func (n noopCoordinator) Close() error {
+ return nil
+}
+
+func (n noopCoordinator) Ready() error {
+ return nil
+}
+
+func (n noopCoordinator) HealthReport() map[string]error {
+ return map[string]error{}
+}
+
+func (n noopCoordinator) Name() string {
+ return "NoopTriggerCoordinator"
+}
+
+func (n noopCoordinator) Ack(ctx context.Context, triggerCapID, triggerRegistrationID, eventID string) error {
+ return nil
+}
+
+func (n noopCoordinator) RegisterTriggers(ctx context.Context, subscriber triggers.Subscriber, params triggers.RegistrationParams) ([]string, error) {
+ return nil, nil
+}
+
+func (n noopCoordinator) UnregisterTriggers(ctx context.Context, workflowID string) error {
+ return nil
+}
+
+func (n noopCoordinator) AvailableCapacity(ctx context.Context) (triggers.Capacity, error) {
+ return triggers.Capacity{}, nil
+}
+
+func (n noopCoordinator) StartExecution(ctx context.Context, event triggers.CoordinatedEvent) error {
+ return nil
+}
+
+func (n noopCoordinator) WorkflowOrg(string) (string, bool) { return "", false }
+
+type noopQueue struct{}
+
+func (n noopQueue) Put(ctx context.Context, event triggers.CoordinatedEvent) error {
+ return nil
+}
+
+func (n noopQueue) Drain(ctx context.Context) ([]triggers.CoordinatedEvent, error) {
+ return nil, nil
+}
+
+func (n noopQueue) Stats(ctx context.Context) (triggers.Stats, error) {
+ return triggers.Stats{}, nil
+}
+
+func (n noopQueue) Sorted(context.Context, int, int) iter.Seq2[[]byte, *pb.CoordinatedEvent] {
+ return nil
+}
+
+func (n noopQueue) Remove(ctx context.Context, execIDs iter.Seq[string]) {}
+
+func newCoordinatedEvent(t testing.TB, wf, eventID string) (hash []byte, event *pb.CoordinatedEvent) {
+ t.Helper()
+ event = &pb.CoordinatedEvent{
+ WorkflowID: wf, TriggerCapID: "trigger@1.0.0",
+ Event: &pb.TriggerResponse{Event: &pb.TriggerEvent{Id: eventID}},
+ }
+ b, err := event.MarshalTimeless() // hash is over the event without timestamps
+ require.NoError(t, err)
+ sum := sha256.Sum256(b)
+ hash = sum[:]
+ event = proto.CloneOf(event)
+ event.ObservedAt = ts(1000)
+ event.Deadline = ts(2000)
+ return hash, event
+}
+
+// testWF is a valid workflow ID (32 bytes of hex), as events must have.
+var testWF = hexID("wf", 0)
+
+type hashedEvent struct {
+ hash []byte
+ event *pb.CoordinatedEvent
+}
+
+// sliceQueue serves a fixed set of events from Sorted.
+type sliceQueue struct {
+ noopQueue
+ events []hashedEvent
+}
+
+func (q sliceQueue) Sorted(_ context.Context, limit, _ int) iter.Seq2[[]byte, *pb.CoordinatedEvent] {
+ sorted := slices.Clone(q.events)
+ slices.SortFunc(sorted, func(a, b hashedEvent) int { // same order as triggers.CentralQueue
+ return cmp.Or(a.event.Deadline.AsTime().Compare(b.event.Deadline.AsTime()), bytes.Compare(a.hash, b.hash))
+ })
+ return func(yield func([]byte, *pb.CoordinatedEvent) bool) {
+ for i, e := range sorted {
+ if i >= limit || !yield(e.hash, proto.CloneOf(e.event)) {
+ return
+ }
+ }
+ }
+}
+
+// testBlobHandle returns a valid handle (libocr offers no constructor) built from its wire encoding. i identifies it.
+func testBlobHandle(i int) ocr3_1types.BlobHandle {
+ var h ocr3_1types.BlobHandle
+ if err := h.UnmarshalBinary(handleBytes(byte(i))); err != nil { //nolint:gosec // G115: a small test value
+ panic(err)
+ }
+ return h
+}
+
+func marshalHandle(h ocr3_1types.BlobHandle) string {
+ b, err := h.MarshalBinary()
+ if err != nil {
+ panic(err)
+ }
+ return string(b)
+}
+
+// memBlobs is an in-memory blob store. Each broadcast gets a distinct handle (the first is handleBytes(1), the
+// second handleBytes(2), ...), and fetches are served by handle. payloads are in broadcast order.
+type memBlobs struct {
+ payloads [][]byte
+ byHandle map[string][]byte
+}
+
+// memBlobsMu guards every memBlobs, which are used concurrently when blobs are broadcast or fetched in parallel.
+var memBlobsMu sync.Mutex
+
+func (m *memBlobs) BroadcastBlob(_ context.Context, payload []byte, _ ocr3_1types.BlobExpirationHint) (ocr3_1types.BlobHandle, error) {
+ memBlobsMu.Lock()
+ defer memBlobsMu.Unlock()
+ m.payloads = append(m.payloads, payload)
+ h := testBlobHandle(len(m.payloads))
+ m.put(h, payload)
+ return h, nil
+}
+
+func (m *memBlobs) put(h ocr3_1types.BlobHandle, payload []byte) {
+ if m.byHandle == nil {
+ m.byHandle = make(map[string][]byte)
+ }
+ m.byHandle[marshalHandle(h)] = payload
+}
+
+// store registers a payload under a handle that was written to KV state rather than broadcast.
+func (m *memBlobs) store(handle []byte, payload []byte) {
+ memBlobsMu.Lock()
+ defer memBlobsMu.Unlock()
+ var h ocr3_1types.BlobHandle
+ if err := h.UnmarshalBinary(handle); err != nil {
+ panic(err)
+ }
+ m.payloads = append(m.payloads, payload)
+ m.put(h, payload)
+}
+
+func (m *memBlobs) FetchBlob(_ context.Context, h ocr3_1types.BlobHandle) ([]byte, error) {
+ memBlobsMu.Lock()
+ defer memBlobsMu.Unlock()
+ payload, ok := m.byHandle[marshalHandle(h)]
+ if !ok {
+ return nil, errors.New("unknown blob handle")
+ }
+ return payload, nil
+}
+
+func testPlugin(t testing.TB, q sliceQueue, blobs ocr3_1types.BlobBroadcastFetcher, maxObsBytes int) *consensusQueuePlugin {
+ t.Helper()
+ limits := ocr3_1types.ReportingPluginLimits{
+ MaxObservationBytes: maxObsBytes,
+ MaxBlobPayloadBytes: ocr3_1types.MaxMaxBlobPayloadBytes,
+ MaxKeyValueModifiedKeysPlusValuesBytes: ocr3_1types.MaxMaxKeyValueModifiedKeysPlusValuesBytes,
+ }
+ return newConsensusQueuePlugin(logger.Test(t),
+ ocr3types.ReportingPluginConfig{N: 4, F: 1, OracleID: 0, EstimatedRoundInterval: time.Second},
+ limits, noopCoordinator{}, q,
+ func(context.Context) (time.Duration, error) { return time.Minute, nil }, blobs, testMetrics(t))
+}
+
+// testMetrics returns metrics that record nowhere.
+func testMetrics(tb testing.TB) *pluginMetrics {
+ tb.Helper()
+ m, err := newPluginMetrics(noop.NewMeterProvider().Meter("test"), "digest")
+ require.NoError(tb, err)
+ return m
+}
+
+func TestObserveEvent(t *testing.T) {
+ t.Parallel()
+
+ hash, event := newCoordinatedEvent(t, "wf1", "evt-1")
+ obs := &pb.ConsensusQueueObservation{WorkflowCapacities: map[string]uint32{}}
+
+ newWF, err := observeEvent(obs, hash, event, map[string]int{"wf1": 3})
+ require.NoError(t, err)
+ assert.True(t, newWF)
+ assert.Equal(t, uint32(3), obs.WorkflowCapacities["wf1"])
+ require.Len(t, obs.Events, 1)
+
+ got := obs.Events[0]
+ wantExec, err := workflows.GenerateExecutionIDWithTriggerIndex("wf1", "evt-1", 0)
+ require.NoError(t, err)
+ assert.Equal(t, wantExec, got.ExecutionID)
+ assert.Equal(t, hash, got.TimelessHash)
+ assert.Equal(t, int64(1000), got.ObservedAt.Seconds)
+ assert.Equal(t, int64(2000), got.Deadline.Seconds)
+ assert.Nil(t, event.ObservedAt, "timestamps are stripped from the event so it hashes consistently")
+ assert.Nil(t, event.Deadline)
+
+ // second event in the same workflow doesn't re-add capacity
+ hash2, event2 := newCoordinatedEvent(t, "wf1", "evt-2")
+ newWF, err = observeEvent(obs, hash2, event2, map[string]int{"wf1": 99})
+ require.NoError(t, err)
+ assert.False(t, newWF)
+ assert.Equal(t, uint32(3), obs.WorkflowCapacities["wf1"])
+ assert.Equal(t, uint32(1), obs.Events[1].Blobs[0].Element, "element index follows position")
+}
+
+func TestObservationsAggregate(t *testing.T) {
+ t.Parallel()
+ const f = 1
+
+ mkAO := func(id commontypes.OracleID, obs *pb.ConsensusQueueObservation) ocrtypes.AttributedObservation {
+ b, err := proto.Marshal(obs)
+ require.NoError(t, err)
+ return ocrtypes.AttributedObservation{Observer: id, Observation: b}
+ }
+ base := func(capacity uint32, wfCaps map[string]uint32) *pb.ConsensusQueueObservation {
+ return &pb.ConsensusQueueObservation{Expiration: ts(100), Capacity: capacity, WorkflowCapacities: wfCaps}
+ }
+
+ t.Run("capacity and expiration without events", func(t *testing.T) {
+ t.Parallel()
+ var res observations
+ res.aggregate(t.Context(), f, []ocrtypes.AttributedObservation{
+ mkAO(0, base(10, map[string]uint32{testWF: 5})),
+ mkAO(1, base(1, map[string]uint32{testWF: 1})),
+ mkAO(2, base(7, map[string]uint32{testWF: 9})),
+ })
+ require.NoError(t, res.err)
+ assert.Equal(t, uint32(7), res.fPlus1thCap, "F+1th lowest of 1,7,10")
+ assert.Equal(t, uint32(5), res.fPlus1thCapPerWF[testWF], "F+1th lowest of 1,5,9")
+ assert.Equal(t, time.Unix(100, 0).UTC(), res.medianExpiration.UTC())
+ })
+
+ t.Run("a byzantine low or high capacity cannot move the result outside the honest range", func(t *testing.T) {
+ t.Parallel()
+ var res observations
+ res.aggregate(t.Context(), f, []ocrtypes.AttributedObservation{
+ mkAO(0, base(0, nil)), // byzantine low
+ mkAO(1, base(5, nil)), // honest
+ mkAO(2, base(6, nil)), // honest
+ mkAO(3, base(1<<31, nil)), // byzantine high
+ })
+ assert.Equal(t, uint32(5), res.fPlus1thCap)
+ })
+
+ t.Run("garbage observation errors", func(t *testing.T) {
+ t.Parallel()
+ var res observations
+ res.aggregate(t.Context(), f, []ocrtypes.AttributedObservation{{Observer: 0, Observation: []byte{0xff, 0xff}}})
+ require.Error(t, res.err)
+ })
+
+ t.Run("events are merged by hash across observers", func(t *testing.T) {
+ t.Parallel()
+ hash, event := newCoordinatedEvent(t, testWF, "evt")
+ mkObs := func() *pb.ConsensusQueueObservation {
+ o := base(5, map[string]uint32{testWF: 5})
+ o.BlobHandles = [][]byte{[]byte("handle")}
+ _, err := observeEvent(o, hash, proto.CloneOf(event), map[string]int{testWF: 5})
+ require.NoError(t, err)
+ return o
+ }
+ var res observations
+ require.NotPanics(t, func() {
+ res.aggregate(t.Context(), f, []ocrtypes.AttributedObservation{mkAO(0, mkObs()), mkAO(1, mkObs()), mkAO(3, mkObs())})
+ })
+ require.NoError(t, res.err)
+ require.Len(t, res.newObservedEvents, 1)
+ got := res.newObservedEvents[string(hash)]
+ require.NotNil(t, got)
+ assert.Equal(t, []byte{0, 1, 3}, got.NodeIds)
+ assert.Len(t, got.Deadlines, 3)
+ assert.Equal(t, map[uint8]blobRef{0: {"handle", 0}, 1: {"handle", 0}, 3: {"handle", 0}}, res.observedBlobs[string(hash)], "each voter's blob")
+ })
+}
+
+func TestBroadcastObservationBlobs(t *testing.T) {
+ t.Parallel()
+
+ t.Run("no events", func(t *testing.T) {
+ t.Parallel()
+ c := testPlugin(t, sliceQueue{}, &memBlobs{}, ocr3_1types.MaxMaxObservationBytes)
+ ok, err := c.broadcastObservationBlobs(t.Context(), &pb.ConsensusQueueObservation{}, &memBlobs{}, nil, 1)
+ require.NoError(t, err)
+ assert.True(t, ok)
+ })
+
+ t.Run("single blob holds all events", func(t *testing.T) {
+ t.Parallel()
+ blobs := &memBlobs{}
+ c := testPlugin(t, sliceQueue{}, blobs, ocr3_1types.MaxMaxObservationBytes)
+ obs := &pb.ConsensusQueueObservation{WorkflowCapacities: map[string]uint32{}}
+ events := make([]*pb.CoordinatedEvent, 0, 3)
+ for _, id := range []string{"a", "b", "c"} {
+ h, e := newCoordinatedEvent(t, testWF, id)
+ events = append(events, e)
+ _, err := observeEvent(obs, h, e, nil)
+ require.NoError(t, err)
+ }
+ ok, err := c.broadcastObservationBlobs(t.Context(), obs, blobs, events, 1)
+ require.NoError(t, err)
+ assert.True(t, ok)
+ assert.Len(t, blobs.payloads, 1)
+ assert.Len(t, obs.BlobHandles, 1)
+ assert.Len(t, obs.Events, 3)
+ })
+
+ t.Run("event and observation counts must match", func(t *testing.T) {
+ t.Parallel()
+ blobs := &memBlobs{}
+ c := testPlugin(t, sliceQueue{}, blobs, ocr3_1types.MaxMaxObservationBytes)
+ _, e := newCoordinatedEvent(t, testWF, "a")
+ _, err := c.broadcastObservationBlobs(t.Context(), &pb.ConsensusQueueObservation{}, blobs, []*pb.CoordinatedEvent{e}, 1)
+ require.Error(t, err)
+ })
+}
+
+// Observation output must pass ValidateObservation on a peer.
+func TestObservation_PassesValidateObservation(t *testing.T) {
+ t.Parallel()
+
+ events := make([]hashedEvent, 0, 2)
+ for _, id := range []string{"a", "b"} {
+ h, e := newCoordinatedEvent(t, testWF, id)
+ events = append(events, hashedEvent{h, e})
+ }
+ blobs := &memBlobs{}
+ c := testPlugin(t, sliceQueue{events: events}, blobs, ocr3_1types.MaxMaxObservationBytes)
+
+ raw, err := c.Observation(t.Context(), 1, ocrtypes.AttributedQuery{}, memKV{}, blobs)
+ require.NoError(t, err)
+
+ var obs pb.ConsensusQueueObservation
+ require.NoError(t, proto.Unmarshal(raw, &obs))
+ assert.Len(t, obs.Events, 2)
+ assert.Len(t, obs.BlobHandles, 1, "only real blob handles, no size-estimation placeholders")
+ for _, e := range obs.Events {
+ assert.Less(t, int(e.Blobs[0].Blob), len(obs.BlobHandles))
+ }
+
+ err = c.ValidateObservation(t.Context(), 1, ocrtypes.AttributedQuery{}, ocrtypes.AttributedObservation{Observer: 0, Observation: raw}, memKV{}, blobs)
+ require.NoError(t, err)
+}
+
+func TestObservation_NoEvents(t *testing.T) {
+ t.Parallel()
+
+ c := testPlugin(t, sliceQueue{}, &memBlobs{}, ocr3_1types.MaxMaxObservationBytes)
+ raw, err := c.Observation(t.Context(), 1, ocrtypes.AttributedQuery{}, memKV{}, &memBlobs{})
+ require.NoError(t, err)
+
+ var obs pb.ConsensusQueueObservation
+ require.NoError(t, proto.Unmarshal(raw, &obs))
+ assert.Empty(t, obs.Events)
+ assert.Empty(t, obs.BlobHandles, "size-estimation placeholders must not be sent")
+ require.NoError(t, c.ValidateObservation(t.Context(), 1, ocrtypes.AttributedQuery{}, ocrtypes.AttributedObservation{Observation: raw}, memKV{}, &memBlobs{}))
+}
+
+// When the observation is size-limited, Observation must still succeed with the events that fit.
+func TestObservation_SizeLimited(t *testing.T) {
+ t.Parallel()
+
+ events := make([]hashedEvent, 0, 3)
+ for _, id := range []string{"a", "b", "c"} {
+ h, e := newCoordinatedEvent(t, testWF, id)
+ events = append(events, hashedEvent{h, e})
+ }
+
+ // Find the observation size with only the first event and placeholders, then allow just that much (plus a little slack).
+ probe := &pb.ConsensusQueueObservation{
+ BlobHandles: make([][]byte, maxObservedBlobHandles),
+ Expiration: timestamppb.New(time.Now()),
+ WorkflowCapacities: map[string]uint32{},
+ }
+ c0 := testPlugin(t, sliceQueue{}, &memBlobs{}, ocr3_1types.MaxMaxObservationBytes)
+ for i := range probe.BlobHandles {
+ probe.BlobHandles[i] = make([]byte, c0.blobHandleMarshalledBytesUpperBound)
+ }
+ _, e0 := newCoordinatedEvent(t, testWF, "a")
+ _, err := observeEvent(probe, events[0].hash, e0, nil)
+ require.NoError(t, err)
+ limit := proto.Size(probe) + 8
+
+ blobs := &memBlobs{}
+ c := testPlugin(t, sliceQueue{events: events}, blobs, limit)
+ raw, err := c.Observation(t.Context(), 1, ocrtypes.AttributedQuery{}, memKV{}, blobs)
+ require.NoError(t, err, "hitting the size limit must not fail the observation")
+
+ var obs pb.ConsensusQueueObservation
+ require.NoError(t, proto.Unmarshal(raw, &obs))
+ assert.Len(t, obs.Events, 1)
+}
+
+// blobEvent is a coordinated event as it appears in a blob (no timestamps), plus its observation form.
+func blobEvent(t testing.TB, wf, id string) (ce *pb.CoordinatedEvent, qe *pb.ConsensusQueueEvent) {
+ t.Helper()
+ ce = &pb.CoordinatedEvent{
+ WorkflowID: wf, TriggerCapID: "trigger@1.0.0",
+ Event: &pb.TriggerResponse{Event: &pb.TriggerEvent{Id: id}},
+ }
+ b, err := proto.MarshalOptions{Deterministic: true}.Marshal(ce)
+ require.NoError(t, err)
+ hash := sha256.Sum256(b)
+ execID, err := workflows.GenerateExecutionIDWithTriggerIndex(wf, id, 0)
+ require.NoError(t, err)
+ qe = &pb.ConsensusQueueEvent{
+ WorkflowID: wf, ExecutionID: execID, TimelessHash: hash[:],
+ ObservedAt: ts(1), Deadline: ts(2),
+ Blobs: []*pb.CoordinatedEventBlobHandle{{Blob: 0, Element: 0}},
+ }
+ return ce, qe
+}
+
+func TestValidateObservedEvent(t *testing.T) {
+ t.Parallel()
+
+ handles := [][]byte{handleBytes(1)}
+
+ tests := []struct {
+ name string
+ // mutate may change the observed event, and/or the blob contents (returned payload replaces the default one)
+ mutate func(ce *pb.CoordinatedEvent, qe *pb.ConsensusQueueEvent)
+ fetch error
+ wantErr string // empty means valid
+ }{
+ {name: "valid"},
+ {name: "missing workflow id", mutate: func(_ *pb.CoordinatedEvent, qe *pb.ConsensusQueueEvent) { qe.WorkflowID = "" }, wantErr: "workflow id is missing"},
+ {name: "workflow id not hex", mutate: func(_ *pb.CoordinatedEvent, qe *pb.ConsensusQueueEvent) { qe.WorkflowID = "not-a-workflow-id" }, wantErr: "invalid event workflow id"},
+ {name: "workflow id too short", mutate: func(_ *pb.CoordinatedEvent, qe *pb.ConsensusQueueEvent) { qe.WorkflowID = "abcd" }, wantErr: "invalid event workflow id"},
+ {name: "workflow id too long", mutate: func(_ *pb.CoordinatedEvent, qe *pb.ConsensusQueueEvent) { qe.WorkflowID = hexID("a", 0) + "00" }, wantErr: "invalid event workflow id"},
+ {name: "missing execution id", mutate: func(_ *pb.CoordinatedEvent, qe *pb.ConsensusQueueEvent) { qe.ExecutionID = "" }, wantErr: "execution id is missing"},
+ {name: "missing observed at", mutate: func(_ *pb.CoordinatedEvent, qe *pb.ConsensusQueueEvent) { qe.ObservedAt = nil }, wantErr: "observation ts is missing"},
+ {name: "missing deadline", mutate: func(_ *pb.CoordinatedEvent, qe *pb.ConsensusQueueEvent) { qe.Deadline = nil }, wantErr: "deadline is missing"},
+ {name: "missing hash", mutate: func(_ *pb.CoordinatedEvent, qe *pb.ConsensusQueueEvent) { qe.TimelessHash = nil }, wantErr: "hash is missing"},
+ {name: "no blob ref", mutate: func(_ *pb.CoordinatedEvent, qe *pb.ConsensusQueueEvent) { qe.Blobs = nil }, wantErr: "blob is missing"},
+ {name: "two blob refs", mutate: func(_ *pb.CoordinatedEvent, qe *pb.ConsensusQueueEvent) { qe.Blobs = append(qe.Blobs, qe.Blobs[0]) }, wantErr: "more than one blob"},
+ {name: "blob index out of range", mutate: func(_ *pb.CoordinatedEvent, qe *pb.ConsensusQueueEvent) { qe.Blobs[0].Blob = uint32(len(handles)) }, wantErr: "out of range"}, //nolint:gosec // G115: a small test value
+ {name: "element out of range", mutate: func(_ *pb.CoordinatedEvent, qe *pb.ConsensusQueueEvent) { qe.Blobs[0].Element = 5 }, wantErr: "failed to fetch event"},
+ {name: "blob fetch fails", fetch: errBoom, wantErr: "boom"},
+ {name: "workflow id differs from blob", mutate: func(_ *pb.CoordinatedEvent, qe *pb.ConsensusQueueEvent) { qe.WorkflowID = hexID("other", 0) }, wantErr: "does not match event workflow ID"},
+ {name: "execution id differs from blob", mutate: func(_ *pb.CoordinatedEvent, qe *pb.ConsensusQueueEvent) { qe.ExecutionID = "forged" }, wantErr: "does not match event execution ID"},
+ {name: "blob carries observed at", mutate: func(ce *pb.CoordinatedEvent, _ *pb.ConsensusQueueEvent) { ce.ObservedAt = ts(1) }, wantErr: "observation timestamp is not nil"},
+ {name: "blob carries deadline", mutate: func(ce *pb.CoordinatedEvent, _ *pb.ConsensusQueueEvent) { ce.Deadline = ts(1) }, wantErr: "deadline timestamp is not nil"},
+ {name: "hash differs from blob", mutate: func(_ *pb.CoordinatedEvent, qe *pb.ConsensusQueueEvent) { qe.TimelessHash = make([]byte, sha256.Size) }, wantErr: "does not match observation hash"},
+ {name: "wrong length hash", mutate: func(_ *pb.CoordinatedEvent, qe *pb.ConsensusQueueEvent) { qe.TimelessHash = []byte{1} }, wantErr: "must be 32 bytes"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ ce, qe := blobEvent(t, testWF, "evt")
+ if tt.mutate != nil {
+ tt.mutate(ce, qe)
+ }
+ f := &countingFetcher{payload: marshalEvents(t, ce), err: tt.fetch}
+
+ err := validateObservedEvent(t.Context(), newBlobCache(f), qe, handles)
+ if tt.wantErr == "" {
+ require.NoError(t, err)
+ return
+ }
+ require.ErrorContains(t, err, tt.wantErr)
+ })
+ }
+
+ // A peer controls the blob contents, so a malformed event must be rejected, never panic.
+ t.Run("blob event without trigger event does not panic", func(t *testing.T) {
+ t.Parallel()
+ _, qe := blobEvent(t, testWF, "evt")
+ for _, ce := range []*pb.CoordinatedEvent{
+ {WorkflowID: testWF}, // no Event
+ {WorkflowID: testWF, Event: &pb.TriggerResponse{}}, // no inner Event
+ } {
+ f := &countingFetcher{payload: marshalEvents(t, ce)}
+ require.NotPanics(t, func() {
+ require.Error(t, validateObservedEvent(t.Context(), newBlobCache(f), qe, handles))
+ })
+ }
+ })
+}
+
+// observeN builds a valid observation from a plugin with n queued events with ascending deadlines.
+func observeN(t *testing.T, n int) (*consensusQueuePlugin, *memBlobs, *pb.ConsensusQueueObservation) {
+ t.Helper()
+ events := make([]hashedEvent, 0, n)
+ for i := range n {
+ h, e := newCoordinatedEvent(t, testWF, fmt.Sprintf("evt-%d", i))
+ e.Deadline = ts(int64(2000 + 10*i))
+ events = append(events, hashedEvent{h, e})
+ }
+ blobs := &memBlobs{}
+ c := testPlugin(t, sliceQueue{events: events}, blobs, ocr3_1types.MaxMaxObservationBytes)
+ raw, err := c.Observation(t.Context(), 1, ocrtypes.AttributedQuery{}, memKV{}, blobs)
+ require.NoError(t, err)
+ var obs pb.ConsensusQueueObservation
+ require.NoError(t, proto.Unmarshal(raw, &obs))
+ require.Len(t, obs.Events, n)
+ return c, blobs, &obs
+}
+
+func validate(t *testing.T, c *consensusQueuePlugin, blobs *memBlobs, obs *pb.ConsensusQueueObservation) error {
+ t.Helper()
+ raw, err := proto.Marshal(obs)
+ require.NoError(t, err)
+ return c.ValidateObservation(t.Context(), 1, ocrtypes.AttributedQuery{}, ocrtypes.AttributedObservation{Observation: raw}, memKV{}, blobs)
+}
+
+func TestValidateObservation(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ mutate func(obs *pb.ConsensusQueueObservation)
+ wantErr string
+ }{
+ {name: "valid"},
+ {name: "too many blob handles", mutate: func(o *pb.ConsensusQueueObservation) {
+ for len(o.BlobHandles) <= maxObservedBlobHandles {
+ o.BlobHandles = append(o.BlobHandles, o.BlobHandles[0])
+ }
+ }, wantErr: "blob handles are limited"},
+ {name: "missing expiration", mutate: func(o *pb.ConsensusQueueObservation) { o.Expiration = nil }, wantErr: "expiration is missing"},
+ {name: "too many events", mutate: func(o *pb.ConsensusQueueObservation) {
+ o.Events = make([]*pb.ConsensusQueueEvent, maxObservedEvents+1)
+ }, wantErr: "events are limited"},
+ {name: "invalid event reports its index", mutate: func(o *pb.ConsensusQueueObservation) { o.Events[1].WorkflowID = "" }, wantErr: "event 1 failed validation"},
+ {name: "event with nil entry does not panic", mutate: func(o *pb.ConsensusQueueObservation) { o.Events[1] = nil }, wantErr: "event 1 failed validation"},
+ {name: "missing workflow capacity", mutate: func(o *pb.ConsensusQueueObservation) { delete(o.WorkflowCapacities, testWF) }, wantErr: "missing capacity"},
+ {name: "duplicate event", mutate: func(o *pb.ConsensusQueueObservation) { o.Events[2] = proto.CloneOf(o.Events[1]) }, wantErr: "duplicate workflow execution ID"},
+ {name: "unsorted", mutate: func(o *pb.ConsensusQueueObservation) { o.Events[0], o.Events[1] = o.Events[1], o.Events[0] }, wantErr: "must be sorted"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ c, blobs, obs := observeN(t, 3)
+ if tt.mutate != nil {
+ tt.mutate(obs)
+ }
+ err := validate(t, c, blobs, obs)
+ if tt.wantErr == "" {
+ require.NoError(t, err)
+ return
+ }
+ require.ErrorContains(t, err, tt.wantErr)
+ })
+ }
+
+ t.Run("garbage", func(t *testing.T) {
+ t.Parallel()
+ c, blobs, _ := observeN(t, 1)
+ err := c.ValidateObservation(t.Context(), 1, ocrtypes.AttributedQuery{}, ocrtypes.AttributedObservation{Observation: []byte{0xff, 0xff}}, memKV{}, blobs)
+ require.ErrorContains(t, err, "unmarshal")
+ })
+
+ t.Run("empty observation is valid", func(t *testing.T) {
+ t.Parallel()
+ c, blobs, obs := observeN(t, 0)
+ require.NoError(t, validate(t, c, blobs, obs))
+ })
+
+ // Completeness (C4): fields that feed StateTransition must be bound to what an honest node reports.
+ t.Run("workflow capacities for workflows without events are bounded", func(t *testing.T) {
+ t.Parallel()
+ c, blobs, obs := observeN(t, 1)
+ for i := range 10_000 {
+ obs.WorkflowCapacities[fmt.Sprintf("junk-%d", i)] = 1
+ }
+ assert.Error(t, validate(t, c, blobs, obs), "unbounded junk workflow IDs must be rejected")
+ })
+}
+
+func TestObservationQuorum(t *testing.T) {
+ t.Parallel()
+
+ c := testPlugin(t, sliceQueue{}, &memBlobs{}, ocr3_1types.MaxMaxObservationBytes) // N=4, F=1
+ aos := func(n int) (out []ocrtypes.AttributedObservation) {
+ for i := range n {
+ out = append(out, ocrtypes.AttributedObservation{Observer: commontypes.OracleID(i)})
+ }
+ return
+ }
+ for n, want := range map[int]bool{0: false, 1: false, 2: false, 3: true, 4: true} {
+ got, err := c.ObservationQuorum(t.Context(), 1, ocrtypes.AttributedQuery{}, aos(n), memKV{}, nil)
+ require.NoError(t, err)
+ assert.Equal(t, want, got, "%d of N=4,F=1 observations (quorum is 2F+1=3)", n)
+ }
+}
+
+func TestReportlessPluginMethods(t *testing.T) {
+ t.Parallel()
+
+ c := testPlugin(t, sliceQueue{}, &memBlobs{}, ocr3_1types.MaxMaxObservationBytes)
+
+ q, err := c.Query(t.Context(), 1, memKV{}, nil)
+ require.NoError(t, err)
+ assert.Nil(t, q)
+
+ reports, err := c.Reports(t.Context(), 1, nil)
+ require.NoError(t, err)
+ assert.Empty(t, reports)
+
+ ok, err := c.ShouldAcceptAttestedReport(t.Context(), 1, ocr3types.ReportWithInfo[[]byte]{})
+ require.NoError(t, err)
+ assert.False(t, ok)
+ ok, err = c.ShouldTransmitAcceptedReport(t.Context(), 1, ocr3types.ReportWithInfo[[]byte]{})
+ require.NoError(t, err)
+ assert.False(t, ok)
+}
+
+// nodeOpts are the non-event fields of a node's observation.
+type nodeOpts struct {
+ capacity uint32
+ wfCaps map[string]uint32
+ expiration int64 // seconds
+ drain bool // reports KV drain mode
+}
+
+var stdNode = nodeOpts{capacity: 10, wfCaps: map[string]uint32{testWF: 10}, expiration: 100}
+
+// nodeObs builds a node's observation of the events, referencing a single (shared) blob.
+func nodeObs(t testing.TB, o nodeOpts, events ...hashedEvent) *pb.ConsensusQueueObservation {
+ t.Helper()
+ obs := &pb.ConsensusQueueObservation{
+ BlobHandles: [][]byte{handleBytes(1)},
+ Expiration: ts(o.expiration),
+ Capacity: o.capacity,
+ WorkflowCapacities: maps.Clone(o.wfCaps),
+ KvDrainActive: o.drain,
+ }
+ if obs.WorkflowCapacities == nil {
+ obs.WorkflowCapacities = map[string]uint32{}
+ }
+ for _, e := range events {
+ _, err := observeEvent(obs, e.hash, proto.CloneOf(e.event), nil)
+ require.NoError(t, err)
+ }
+ return obs
+}
+
+func ao(t testing.TB, id int, obs *pb.ConsensusQueueObservation) ocrtypes.AttributedObservation {
+ t.Helper()
+ b, err := proto.Marshal(obs)
+ require.NoError(t, err)
+ return ocrtypes.AttributedObservation{Observer: commontypes.OracleID(id), Observation: b} //nolint:gosec // G115: a small test value
+}
+
+// mkEvents makes n events for workflow testWF with deadlines base, base+1, ...
+func mkEvents(t testing.TB, n int, base int64) []hashedEvent {
+ t.Helper()
+ out := make([]hashedEvent, 0, n)
+ for i := range n {
+ h, e := newCoordinatedEvent(t, testWF, fmt.Sprintf("evt-%02d", i))
+ e.Deadline = ts(base + int64(i))
+ out = append(out, hashedEvent{h, e})
+ }
+ return out
+}
+
+func execIDOf(t testing.TB, id string) string {
+ t.Helper()
+ v, err := workflows.GenerateExecutionIDWithTriggerIndex(testWF, id, 0)
+ require.NoError(t, err)
+ return v
+}
+
+func stateTransition(t testing.TB, c *consensusQueuePlugin, kv ocr3_1types.KeyValueStateReadWriter, aos ...ocrtypes.AttributedObservation) error {
+ t.Helper()
+ _, err := c.StateTransition(t.Context(), 1, ocrtypes.AttributedQuery{}, aos, kv, nil)
+ return err
+}
+
+func loadState(t testing.TB, kv memKV) *kvState {
+ t.Helper()
+ var s kvState
+ require.NoError(t, s.loadFrom(kv))
+ return &s
+}
+
+// consensusIDs returns the execution IDs of the events committed to execute, and checks every blob ref resolves to the shared blob.
+func consensusIDs(t *testing.T, kv memKV) []string {
+ t.Helper()
+ events, handles, err := readConsensusState(kv)
+ require.NoError(t, err)
+ ids := make([]string, 0, len(events))
+ for _, e := range events {
+ require.NotEmpty(t, e.Blobs, "consensus event %s must reference a blob", e.ExecutionID)
+ for _, b := range e.Blobs {
+ require.Less(t, int(b.Blob), len(handles))
+ assert.Equal(t, handleBytes(1), handles[b.Blob])
+ }
+ ids = append(ids, e.ExecutionID)
+ }
+ return ids
+}
+
+func queuedIDs(t *testing.T, kv memKV) []string {
+ t.Helper()
+ s := loadState(t, kv)
+ ids := make([]string, 0, len(s.queuedEvents))
+ for _, e := range s.queuedEvents {
+ assert.Contains(t, s.queuedBlobs, string(e.TimelessHash), "queued event %s must keep its blob ref", e.ExecutionID)
+ ids = append(ids, e.ExecutionID)
+ }
+ slices.Sort(ids)
+ return ids
+}
+
+func kvTotal(kv memKV) (n int) {
+ for k, v := range kv {
+ n += len(k) + len(v)
+ }
+ return
+}
+
+func newSTPlugin(t testing.TB) *consensusQueuePlugin {
+ t.Helper()
+ return testPlugin(t, sliceQueue{}, &memBlobs{}, ocr3_1types.MaxMaxObservationBytes) // N=4, F=1
+}
+
+func TestStateTransition_Lifecycle(t *testing.T) {
+ t.Parallel()
+
+ c := newSTPlugin(t)
+ kv := memKV{}
+ e := mkEvents(t, 1, 2000)
+
+ // round 1: f+1 nodes observe: tracked, not queued
+ require.NoError(t, stateTransition(t, c, kv,
+ ao(t, 0, nodeObs(t, stdNode, e...)), ao(t, 1, nodeObs(t, stdNode, e...)), ao(t, 2, nodeObs(t, stdNode))))
+ st := loadState(t, kv)
+ require.Contains(t, st.observedEvents, string(e[0].hash), "observed events must be persisted")
+ assert.Equal(t, []byte{0, 1}, st.observedEvents[string(e[0].hash)].NodeIds)
+ assert.Equal(t, map[uint8]blobRef{0: {string(handleBytes(1)), 0}, 1: {string(handleBytes(1)), 0}}, st.observedBlobs[string(e[0].hash)])
+ assert.Empty(t, st.queuedEvents)
+ assert.Empty(t, consensusIDs(t, kv))
+
+ // round 2: a third node observes: promoted, and executed in the same round
+ require.NoError(t, stateTransition(t, c, kv,
+ ao(t, 1, nodeObs(t, stdNode)), ao(t, 2, nodeObs(t, stdNode, e...)), ao(t, 3, nodeObs(t, stdNode))))
+ st = loadState(t, kv)
+ assert.Empty(t, st.observedEvents)
+ assert.Empty(t, st.queuedEvents)
+ assert.Equal(t, []string{execIDOf(t, "evt-00")}, consensusIDs(t, kv))
+
+ // round 3: consensus events are only for one round
+ require.NoError(t, stateTransition(t, c, kv, ao(t, 0, nodeObs(t, stdNode)), ao(t, 1, nodeObs(t, stdNode)), ao(t, 2, nodeObs(t, stdNode))))
+ assert.Empty(t, consensusIDs(t, kv))
+}
+
+func TestStateTransition_QuorumInOneRound(t *testing.T) {
+ t.Parallel()
+
+ c := newSTPlugin(t)
+ kv := memKV{}
+ e := mkEvents(t, 1, 2000)
+ require.NoError(t, stateTransition(t, c, kv,
+ ao(t, 0, nodeObs(t, stdNode, e...)), ao(t, 1, nodeObs(t, stdNode, e...)), ao(t, 3, nodeObs(t, stdNode, e...))))
+
+ assert.Equal(t, []string{execIDOf(t, "evt-00")}, consensusIDs(t, kv))
+ assert.Empty(t, loadState(t, kv).observedEvents)
+}
+
+func TestStateTransition_SingleObserverIsIgnored(t *testing.T) {
+ t.Parallel()
+
+ c := newSTPlugin(t)
+ kv := memKV{}
+ e := mkEvents(t, 1, 2000)
+ require.NoError(t, stateTransition(t, c, kv,
+ ao(t, 0, nodeObs(t, stdNode, e...)), ao(t, 1, nodeObs(t, stdNode)), ao(t, 2, nodeObs(t, stdNode))))
+
+ assert.Empty(t, loadState(t, kv).observedEvents, "a lone (possibly byzantine) observer cannot introduce an event")
+ assert.Empty(t, queuedIDs(t, kv))
+ assert.Empty(t, consensusIDs(t, kv))
+}
+
+func TestStateTransition_Capacity(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ global [3]uint32 // each node's reported global capacity
+ wfCap uint32
+ events int
+ wantConsensus int
+ }{
+ {"plenty", [3]uint32{9, 9, 9}, 9, 3, 3},
+ {"global F+1th lowest is zero", [3]uint32{0, 0, 9}, 9, 2, 0},
+ {"global F+1th lowest is one", [3]uint32{9, 1, 1}, 9, 2, 1},
+ {"byzantine high capacity cannot raise it", [3]uint32{1, 1, 1 << 31}, 9, 3, 1},
+ {"workflow capacity zero", [3]uint32{9, 9, 9}, 0, 2, 0},
+ {"workflow capacity one", [3]uint32{9, 9, 9}, 1, 3, 1},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ c := newSTPlugin(t)
+ kv := memKV{}
+ e := mkEvents(t, tt.events, 2000)
+ var aos []ocrtypes.AttributedObservation
+ for i, g := range tt.global {
+ aos = append(aos, ao(t, i, nodeObs(t, nodeOpts{capacity: g, wfCaps: map[string]uint32{testWF: tt.wfCap}, expiration: 100}, e...)))
+ }
+ require.NoError(t, stateTransition(t, c, kv, aos...))
+
+ got := consensusIDs(t, kv)
+ require.Len(t, got, tt.wantConsensus)
+ for i := range got { // earliest deadlines go first
+ assert.Equal(t, execIDOf(t, fmt.Sprintf("evt-%02d", i)), got[i])
+ }
+ assert.Len(t, queuedIDs(t, kv), tt.events-tt.wantConsensus, "events without capacity stay queued, with their blob refs")
+ })
+ }
+
+ t.Run("queued events run when capacity returns", func(t *testing.T) {
+ t.Parallel()
+ c := newSTPlugin(t)
+ kv := memKV{}
+ e := mkEvents(t, 2, 2000)
+ none := nodeOpts{capacity: 0, wfCaps: map[string]uint32{testWF: 0}, expiration: 100}
+ require.NoError(t, stateTransition(t, c, kv, ao(t, 0, nodeObs(t, none, e...)), ao(t, 1, nodeObs(t, none, e...)), ao(t, 2, nodeObs(t, none, e...))))
+ require.Empty(t, consensusIDs(t, kv))
+ require.Len(t, queuedIDs(t, kv), 2)
+
+ require.NoError(t, stateTransition(t, c, kv, ao(t, 0, nodeObs(t, stdNode)), ao(t, 1, nodeObs(t, stdNode)), ao(t, 2, nodeObs(t, stdNode))))
+ assert.Equal(t, []string{execIDOf(t, "evt-00"), execIDOf(t, "evt-01")}, consensusIDs(t, kv))
+ assert.Empty(t, queuedIDs(t, kv))
+ })
+}
+
+func TestStateTransition_Expiration(t *testing.T) {
+ t.Parallel()
+
+ late := nodeOpts{capacity: 10, wfCaps: map[string]uint32{testWF: 10}, expiration: 3000}
+
+ t.Run("expired events are dropped instead of executed", func(t *testing.T) {
+ t.Parallel()
+ c := newSTPlugin(t)
+ kv := memKV{}
+ e := mkEvents(t, 2, 2000) // deadlines before the 3000 expiration
+ require.NoError(t, stateTransition(t, c, kv, ao(t, 0, nodeObs(t, late, e...)), ao(t, 1, nodeObs(t, late, e...)), ao(t, 2, nodeObs(t, late, e...))))
+ assert.Empty(t, consensusIDs(t, kv))
+ assert.Empty(t, queuedIDs(t, kv))
+ })
+
+ t.Run("expired observations are pruned", func(t *testing.T) {
+ t.Parallel()
+ c := newSTPlugin(t)
+ kv := memKV{}
+ e := mkEvents(t, 1, 2000)
+ require.NoError(t, stateTransition(t, c, kv, ao(t, 0, nodeObs(t, stdNode, e...)), ao(t, 1, nodeObs(t, stdNode, e...)), ao(t, 2, nodeObs(t, stdNode))))
+ require.NotEmpty(t, loadState(t, kv).observedEvents)
+
+ require.NoError(t, stateTransition(t, c, kv, ao(t, 0, nodeObs(t, late)), ao(t, 1, nodeObs(t, late)), ao(t, 2, nodeObs(t, late))))
+ assert.Empty(t, loadState(t, kv).observedEvents)
+ })
+}
+
+// deterministicScenario runs two rounds over a mixed set of events, optionally shuffling the second round's observations.
+func deterministicScenario(t *testing.T, shuffleSeed int64) memKV {
+ t.Helper()
+ e := mkEvents(t, 7, 2000)
+ pick := func(idx ...int) (out []hashedEvent) {
+ for _, i := range idx {
+ out = append(out, e[i])
+ }
+ return
+ }
+ c := newSTPlugin(t)
+ kv := memKV{}
+ // round 1: e5, e6 observed by two nodes
+ require.NoError(t, stateTransition(t, c, kv,
+ ao(t, 0, nodeObs(t, stdNode, pick(5, 6)...)), ao(t, 1, nodeObs(t, stdNode, pick(5, 6)...)), ao(t, 2, nodeObs(t, stdNode))))
+ // round 2 votes: e0:3 e1:3 e2:2 e3:2 e4:2 (+ e5 gains a vote and is promoted)
+ aos := []ocrtypes.AttributedObservation{
+ ao(t, 0, nodeObs(t, nodeOpts{capacity: 3, wfCaps: map[string]uint32{testWF: 2}, expiration: 90}, pick(0, 1, 2)...)),
+ ao(t, 1, nodeObs(t, nodeOpts{capacity: 5, wfCaps: map[string]uint32{testWF: 3}, expiration: 95}, pick(0, 1, 3)...)),
+ ao(t, 2, nodeObs(t, nodeOpts{capacity: 4, wfCaps: map[string]uint32{testWF: 9}, expiration: 99}, pick(0, 2, 3, 4, 5)...)),
+ ao(t, 3, nodeObs(t, nodeOpts{capacity: 9, wfCaps: map[string]uint32{testWF: 1}, expiration: 80}, pick(1, 4)...)),
+ }
+ if shuffleSeed >= 0 {
+ rand.New(rand.NewSource(shuffleSeed)).Shuffle(len(aos), func(i, j int) { aos[i], aos[j] = aos[j], aos[i] })
+ }
+ require.NoError(t, stateTransition(t, c, kv, aos...))
+ return kv
+}
+
+// Same inputs must always produce identical KV bytes (guards against map iteration order leaking into state).
+func TestStateTransition_Deterministic(t *testing.T) {
+ t.Parallel()
+
+ want := deterministicScenario(t, -1)
+ require.NotEmpty(t, consensusIDs(t, want), "scenario should exercise the consensus path")
+ for i := range 40 {
+ require.True(t, maps.EqualFunc(want, deterministicScenario(t, -1), slices.Equal[[]byte]), "run %d differs", i)
+ }
+}
+
+// Hardening: the output also does not depend on the order observations arrive in. libocr hands every oracle the same
+// list in the same order, so this is not strictly required, but sorting by observer would make it so cheaply.
+func TestStateTransition_ObservationOrderIndependent(t *testing.T) {
+ t.Parallel()
+
+ want := deterministicScenario(t, -1)
+ for seed := range int64(40) {
+ got := deterministicScenario(t, seed)
+ require.True(t, maps.EqualFunc(want, got, slices.Equal[[]byte]), "seed %d: observation order changed the KV bytes", seed)
+ }
+}
+
+func TestStateTransition_Errors(t *testing.T) {
+ t.Parallel()
+
+ good := func(t *testing.T) []ocrtypes.AttributedObservation {
+ return []ocrtypes.AttributedObservation{ao(t, 0, nodeObs(t, stdNode)), ao(t, 1, nodeObs(t, stdNode)), ao(t, 2, nodeObs(t, stdNode))}
+ }
+
+ t.Run("garbage observation", func(t *testing.T) {
+ t.Parallel()
+ kv := memKV{}
+ aos := append(good(t), ocrtypes.AttributedObservation{Observer: 3, Observation: []byte{0xff, 0xff}})
+ require.Error(t, stateTransition(t, newSTPlugin(t), kv, aos...))
+ assert.Empty(t, kv, "nothing may be written on error")
+ })
+
+ t.Run("cancelled context", func(t *testing.T) {
+ t.Parallel()
+ ctx, cancel := context.WithCancel(t.Context())
+ cancel()
+ _, err := newSTPlugin(t).StateTransition(ctx, 1, ocrtypes.AttributedQuery{}, good(t), memKV{}, nil)
+ require.ErrorIs(t, err, context.Canceled)
+ })
+
+ t.Run("read error", func(t *testing.T) {
+ t.Parallel()
+ require.ErrorIs(t, stateTransition(t, newSTPlugin(t), &errKV{memKV: memKV{}, readErrKey: queuedEventsKey}, good(t)...), errBoom)
+ })
+
+ for _, key := range allKeys {
+ t.Run("write error "+key, func(t *testing.T) {
+ t.Parallel()
+ require.ErrorIs(t, stateTransition(t, newSTPlugin(t), &errKV{memKV: memKV{}, writeErrKey: key}, good(t)...), errBoom)
+ })
+ }
+}
+
+// within runs fn, failing the test if it does not return in time (e.g. an unbounded pruning loop).
+func within(t *testing.T, d time.Duration, fn func()) {
+ t.Helper()
+ done := make(chan struct{})
+ go func() { defer close(done); fn() }()
+ select {
+ case <-done:
+ case <-time.After(d):
+ t.Fatalf("did not complete within %s", d)
+ }
+}
+
+func TestStateTransition_SizeLimits(t *testing.T) {
+ t.Parallel()
+
+ t.Run("observed events are pruned to fit, least endorsed first", func(t *testing.T) {
+ t.Parallel()
+ c := newSTPlugin(t)
+ const limit = 2000
+ c.limits.MaxKeyValueModifiedKeysPlusValuesBytes = limit
+ kv := memKV{}
+ e := mkEvents(t, 30, 2000)
+
+ within(t, 10*time.Second, func() {
+ require.NoError(t, stateTransition(t, c, kv,
+ ao(t, 0, nodeObs(t, stdNode, e...)), ao(t, 1, nodeObs(t, stdNode, e...)), ao(t, 2, nodeObs(t, stdNode))))
+ })
+
+ assert.LessOrEqual(t, kvTotal(kv), limit)
+ st := loadState(t, kv)
+ require.NotEmpty(t, st.observedEvents)
+ require.Less(t, len(st.observedEvents), 30)
+ // equal votes: ties break on hash ascending, so the retained are the k smallest hashes
+ all := make([]string, 0, len(e))
+ for _, ev := range e {
+ all = append(all, string(ev.hash))
+ }
+ slices.Sort(all)
+ kept := make([]string, 0, len(st.observedEvents))
+ for h := range st.observedEvents {
+ kept = append(kept, h)
+ }
+ assert.ElementsMatch(t, all[:len(kept)], kept)
+ })
+
+ t.Run("newly queued events are pruned to fit, latest deadline first", func(t *testing.T) {
+ t.Parallel()
+ c := newSTPlugin(t)
+ const limit = 3000
+ c.limits.MaxKeyValueModifiedKeysPlusValuesBytes = limit
+ kv := memKV{}
+ e := mkEvents(t, 30, 2000)
+ none := nodeOpts{capacity: 0, wfCaps: map[string]uint32{testWF: 0}, expiration: 100} // nothing executes
+
+ within(t, 10*time.Second, func() {
+ require.NoError(t, stateTransition(t, c, kv,
+ ao(t, 0, nodeObs(t, none, e...)), ao(t, 1, nodeObs(t, none, e...)), ao(t, 2, nodeObs(t, none, e...))))
+ })
+
+ assert.LessOrEqual(t, kvTotal(kv), limit)
+ got := queuedIDs(t, kv)
+ require.NotEmpty(t, got)
+ require.Less(t, len(got), 30)
+ want := make([]string, 0, len(got))
+ for i := range got { // the earliest deadlines survive
+ want = append(want, execIDOf(t, fmt.Sprintf("evt-%02d", i)))
+ }
+ assert.ElementsMatch(t, want, got)
+ })
+
+ t.Run("events that do not fit in the consensus set go back to the queue, none are lost", func(t *testing.T) {
+ t.Parallel()
+ const n = 20
+ e := mkEvents(t, n, 2000)
+ aos := func() []ocrtypes.AttributedObservation {
+ big := nodeOpts{capacity: 100, wfCaps: map[string]uint32{testWF: 100}, expiration: 100}
+ return []ocrtypes.AttributedObservation{ao(t, 0, nodeObs(t, big, e...)), ao(t, 1, nodeObs(t, big, e...)), ao(t, 2, nodeObs(t, big, e...))}
+ }
+
+ // unconstrained: everything executes
+ full := memKV{}
+ require.NoError(t, stateTransition(t, newSTPlugin(t), full, aos()...))
+ require.Len(t, consensusIDs(t, full), n)
+
+ // limit leaves room for the whole state but not for all of it in the consensus set (capped at half the limit)
+ c := newSTPlugin(t)
+ c.limits.MaxKeyValueModifiedKeysPlusValuesBytes = kvTotal(full) + 100
+ kv := memKV{}
+ require.NoError(t, stateTransition(t, c, kv, aos()...))
+
+ executing, queued := consensusIDs(t, kv), queuedIDs(t, kv)
+ assert.NotEmpty(t, executing)
+ assert.Less(t, len(executing), n)
+ assert.ElementsMatch(t, slices.Concat(executing, queued), func() (all []string) {
+ for i := range n {
+ all = append(all, execIDOf(t, fmt.Sprintf("evt-%02d", i)))
+ }
+ return
+ }(), "every event is either executing or still queued, exactly once")
+ })
+}
+
+// recCoordinator records StartExecution calls.
+type recCoordinator struct {
+ noopCoordinator
+ mu sync.Mutex
+ started []triggers.CoordinatedEvent
+ startErr error
+ capacity triggers.Capacity
+ capErr error
+}
+
+func (r *recCoordinator) AvailableCapacity(context.Context) (triggers.Capacity, error) {
+ return r.capacity, r.capErr
+}
+
+func (r *recCoordinator) StartExecution(_ context.Context, e triggers.CoordinatedEvent) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.started = append(r.started, e)
+ return r.startErr
+}
+
+func (r *recCoordinator) startedEvents() []triggers.CoordinatedEvent {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return append([]triggers.CoordinatedEvent(nil), r.started...)
+}
+
+// recQueue records removals from the local queue.
+type recQueue struct {
+ sliceQueue
+ mu sync.Mutex
+ removed []string
+ sortedLimit, sortedSize int // arguments of the last Sorted call
+}
+
+func (q *recQueue) Sorted(ctx context.Context, limit, maxEventBytes int) iter.Seq2[[]byte, *pb.CoordinatedEvent] {
+ q.mu.Lock()
+ q.sortedLimit, q.sortedSize = limit, maxEventBytes
+ q.mu.Unlock()
+ return q.sliceQueue.Sorted(ctx, limit, maxEventBytes)
+}
+
+func (q *recQueue) Remove(_ context.Context, ids iter.Seq[string]) {
+ q.mu.Lock()
+ defer q.mu.Unlock()
+ for id := range ids {
+ q.removed = append(q.removed, id)
+ }
+}
+
+func (q *recQueue) removedIDs() []string {
+ q.mu.Lock()
+ defer q.mu.Unlock()
+ return append([]string(nil), q.removed...)
+}
+
+// errFetchBlobs fails every fetch.
+type errFetchBlobs struct{ memBlobs }
+
+func (errFetchBlobs) FetchBlob(context.Context, ocr3_1types.BlobHandle) ([]byte, error) {
+ return nil, errBoom
+}
+
+func newCommitPlugin(t testing.TB, coord triggers.Coordinator, q triggers.Queue, blobs ocr3_1types.BlobBroadcastFetcher) *consensusQueuePlugin {
+ t.Helper()
+ limits := ocr3_1types.ReportingPluginLimits{
+ MaxObservationBytes: ocr3_1types.MaxMaxObservationBytes,
+ MaxBlobPayloadBytes: ocr3_1types.MaxMaxBlobPayloadBytes,
+ MaxKeyValueModifiedKeysPlusValuesBytes: ocr3_1types.MaxMaxKeyValueModifiedKeysPlusValuesBytes,
+ }
+ c := newConsensusQueuePlugin(logger.Test(t),
+ ocr3types.ReportingPluginConfig{N: 4, F: 1, OracleID: 0, EstimatedRoundInterval: time.Second},
+ limits, coord, q, func(context.Context) (time.Duration, error) { return time.Minute, nil }, blobs, testMetrics(t))
+ require.NoError(t, c.Start(t.Context()))
+ t.Cleanup(func() { require.NoError(t, c.Close()) })
+ return c
+}
+
+// seedKV writes consensus (executing) and queued events to kv, all backed by one blob. Event i has medianized
+// timestamps ObservedAt=4000+i and Deadline=5000+i. It returns the execution IDs in order consensus then queued.
+func seedKV(t testing.TB, kv memKV, blobs *memBlobs, consensus, queued []string) (execIDs []string) {
+ t.Helper()
+ s := newKVState()
+ ces := make([]*pb.CoordinatedEvent, 0, len(consensus)+len(queued))
+ for i, id := range append(append([]string(nil), consensus...), queued...) {
+ ce, qe := blobEvent(t, testWF, id)
+ qe.ObservedAt, qe.Deadline = ts(int64(4000+i)), ts(int64(5000+i))
+ qe.Blobs = nil
+ ces = append(ces, ce)
+ execIDs = append(execIDs, qe.ExecutionID)
+ s.queuedBlobs.add(string(qe.TimelessHash), string(handleBytes(1)), uint32(i))
+ if i < len(consensus) {
+ s.consensusEvents = append(s.consensusEvents, qe)
+ } else {
+ s.queuedEvents.push(qe)
+ }
+ }
+ blobs.store(handleBytes(1), marshalEvents(t, ces...))
+ s.sizeOf() // prepares blob refs
+ require.NoError(t, s.writeTo(&stateWriter{kv: kv}))
+ return execIDs
+}
+
+func TestCommitted(t *testing.T) {
+ t.Parallel()
+
+ t.Run("starts every consensus event with the agreed timestamps and clears the local queue", func(t *testing.T) {
+ t.Parallel()
+ coord, q, blobs, kv := &recCoordinator{}, &recQueue{}, &memBlobs{}, memKV{}
+ c := newCommitPlugin(t, coord, q, blobs)
+ ids := seedKV(t, kv, blobs, []string{"a", "b"}, []string{"c"})
+
+ require.NoError(t, c.Committed(t.Context(), 1, kv))
+
+ started := coord.startedEvents()
+ require.Len(t, started, 2)
+ byTrigger := map[string]triggers.CoordinatedEvent{}
+ for _, e := range started {
+ byTrigger[e.Event.Event.ID] = e
+ }
+ for i, id := range []string{"a", "b"} {
+ e, ok := byTrigger[id]
+ require.True(t, ok, "event %s not started", id)
+ assert.Equal(t, testWF, e.WorkflowID)
+ assert.True(t, time.Unix(int64(4000+i), 0).Equal(e.ObservedAt), "agreed observedAt")
+ assert.True(t, time.Unix(int64(5000+i), 0).Equal(e.Deadline), "agreed deadline")
+ }
+ assert.ElementsMatch(t, ids, q.removedIDs(), "both executing and queued events leave the local queue")
+ })
+
+ t.Run("nothing to do", func(t *testing.T) {
+ t.Parallel()
+ coord, q := &recCoordinator{}, &recQueue{}
+ c := newCommitPlugin(t, coord, q, &memBlobs{})
+ require.NoError(t, c.Committed(t.Context(), 1, memKV{}))
+ assert.Empty(t, coord.startedEvents())
+ assert.Empty(t, q.removedIDs())
+ })
+
+ t.Run("corrupt state is an error and starts nothing", func(t *testing.T) {
+ t.Parallel()
+ for _, key := range []string{consensusEventsKey, queuedEventsKey, blobHandlesKey} {
+ coord := &recCoordinator{}
+ c := newCommitPlugin(t, coord, &recQueue{}, &memBlobs{})
+ require.Error(t, c.Committed(t.Context(), 1, memKV{key: {0xff, 0xff, 0xff}}), key)
+ }
+ })
+
+ t.Run("a failing start does not fail the commit or block the others", func(t *testing.T) {
+ t.Parallel()
+ coord, q, blobs, kv := &recCoordinator{startErr: errBoom}, &recQueue{}, &memBlobs{}, memKV{}
+ c := newCommitPlugin(t, coord, q, blobs)
+ seedKV(t, kv, blobs, []string{"a", "b", "c"}, nil)
+
+ require.NoError(t, c.Committed(t.Context(), 1, kv))
+ assert.Len(t, coord.startedEvents(), 3)
+ })
+
+ t.Run("blob fetch failure is logged, not returned", func(t *testing.T) {
+ t.Parallel()
+ coord, q, kv := &recCoordinator{}, &recQueue{}, memKV{}
+ blobs := &errFetchBlobs{}
+ c := newCommitPlugin(t, coord, q, blobs)
+ seedKV(t, kv, &blobs.memBlobs, []string{"a"}, nil)
+
+ require.NoError(t, c.Committed(t.Context(), 1, kv))
+ assert.Empty(t, coord.startedEvents())
+ })
+
+ t.Run("out of range blob ref does not panic", func(t *testing.T) {
+ t.Parallel()
+ coord, blobs, kv := &recCoordinator{}, &memBlobs{}, memKV{}
+ c := newCommitPlugin(t, coord, &recQueue{}, blobs)
+ _, qe := blobEvent(t, testWF, "a")
+ qe.Blobs = []*pb.CoordinatedEventBlobHandle{{Blob: 9, Element: 0}}
+ b, err := proto.Marshal(&pb.ConsensusQueueEventList{Events: []*pb.ConsensusQueueEvent{qe}})
+ require.NoError(t, err)
+ kv[consensusEventsKey] = b
+
+ require.NotPanics(t, func() { require.NoError(t, c.Committed(t.Context(), 1, kv)) })
+ assert.Empty(t, coord.startedEvents())
+ })
+
+ t.Run("event without a usable blob is skipped but later ones still start", func(t *testing.T) {
+ t.Parallel()
+ coord, blobs, kv := &recCoordinator{}, &memBlobs{}, memKV{}
+ c := newCommitPlugin(t, coord, &recQueue{}, blobs)
+ seedKV(t, kv, blobs, []string{"a", "b"}, nil)
+
+ // first event points past the end of the blob
+ events, handles, err := readConsensusState(kv)
+ require.NoError(t, err)
+ events[0].Blobs[0].Element = 99
+ l, err := proto.Marshal(&pb.ConsensusQueueEventList{Events: events})
+ require.NoError(t, err)
+ kv[consensusEventsKey] = l
+ _ = handles
+
+ require.NoError(t, c.Committed(t.Context(), 1, kv))
+ started := coord.startedEvents()
+ require.Len(t, started, 1)
+ assert.Equal(t, "b", started[0].Event.Event.ID)
+ })
+}
+
+func TestObservation_StartsExecutionsFromState(t *testing.T) {
+ t.Parallel()
+
+ coord, q, blobs, kv := &recCoordinator{}, &recQueue{}, &memBlobs{}, memKV{}
+ c := newCommitPlugin(t, coord, q, blobs)
+ seedKV(t, kv, blobs, []string{"a"}, []string{"b"})
+
+ _, err := c.Observation(t.Context(), 1, ocrtypes.AttributedQuery{}, kv, blobs)
+ require.NoError(t, err)
+
+ started := coord.startedEvents()
+ require.Len(t, started, 1, "Committed may not have been called, so Observation starts executions too")
+ assert.Equal(t, "a", started[0].Event.Event.ID)
+ assert.Len(t, q.removedIDs(), 2)
+}
+
+func observe(t testing.TB, c *consensusQueuePlugin, kv ocr3_1types.KeyValueStateReader, blobs ocr3_1types.BlobBroadcastFetcher) (*pb.ConsensusQueueObservation, error) {
+ t.Helper()
+ raw, err := c.Observation(t.Context(), 1, ocrtypes.AttributedQuery{}, kv, blobs)
+ if err != nil {
+ return nil, err
+ }
+ var obs pb.ConsensusQueueObservation
+ require.NoError(t, proto.Unmarshal(raw, &obs))
+ return &obs, nil
+}
+
+func TestObservation_Fields(t *testing.T) {
+ t.Parallel()
+
+ t.Run("capacity errors fail the observation", func(t *testing.T) {
+ t.Parallel()
+ c := newCommitPlugin(t, &recCoordinator{capErr: errBoom}, &recQueue{}, &memBlobs{})
+ _, err := observe(t, c, memKV{}, &memBlobs{})
+ require.ErrorIs(t, err, errBoom)
+ })
+
+ t.Run("corrupt state fails the observation", func(t *testing.T) {
+ t.Parallel()
+ for _, key := range []string{observedEventsKey, queuedEventsKey, consensusEventsKey} {
+ c := newCommitPlugin(t, &recCoordinator{}, &recQueue{}, &memBlobs{})
+ _, err := observe(t, c, memKV{key: {0xff, 0xff, 0xff}}, &memBlobs{})
+ require.Error(t, err, key)
+ }
+ })
+
+ t.Run("expiration grace errors are tolerated", func(t *testing.T) {
+ t.Parallel()
+ c := newCommitPlugin(t, &recCoordinator{}, &recQueue{}, &memBlobs{})
+ c.expirationDur = func(context.Context) (time.Duration, error) { return 0, errBoom }
+ before := time.Now()
+ obs, err := observe(t, c, memKV{}, &memBlobs{})
+ require.NoError(t, err)
+ assert.False(t, obs.Expiration.AsTime().Before(before.Add(-time.Second)), "falls back to no grace period")
+ })
+
+ t.Run("expiration is observation time minus grace", func(t *testing.T) {
+ t.Parallel()
+ c := newCommitPlugin(t, &recCoordinator{}, &recQueue{}, &memBlobs{}) // 1 minute grace
+ before := time.Now()
+ obs, err := observe(t, c, memKV{}, &memBlobs{})
+ require.NoError(t, err)
+ assert.WithinDuration(t, before.Add(-time.Minute), obs.Expiration.AsTime(), 5*time.Second)
+ })
+
+ t.Run("global capacity is clamped to uint32", func(t *testing.T) {
+ t.Parallel()
+ c := newCommitPlugin(t, &recCoordinator{capacity: triggers.Capacity{Global: math.MaxInt}}, &recQueue{}, &memBlobs{})
+ obs, err := observe(t, c, memKV{}, &memBlobs{})
+ require.NoError(t, err)
+ assert.Equal(t, uint32(math.MaxUint32), obs.Capacity)
+ })
+
+ t.Run("workflow capacities cover workflows with events in state or locally, and nothing else", func(t *testing.T) {
+ t.Parallel()
+ blobs, kv := &memBlobs{}, memKV{}
+ h, e := newCoordinatedEvent(t, "local-wf", "local")
+ coord := &recCoordinator{capacity: triggers.Capacity{Global: 5, PerWorkflow: map[string]int{"local-wf": 3, "queued-wf": 7, "observed-wf": 8, "unrelated": 9}}}
+ c := newCommitPlugin(t, coord, &recQueue{sliceQueue: sliceQueue{events: []hashedEvent{{h, e}}}}, blobs)
+
+ // state: a queued event for queued-wf, an observed event for observed-wf
+ s := newKVState()
+ s.queuedEvents.push(&pb.ConsensusQueueEvent{WorkflowID: "queued-wf", ExecutionID: "x", TimelessHash: []byte("q"), ObservedAt: ts(1), Deadline: ts(2)})
+ s.observedEvents["o"] = obsEvent("observed-wf", "y", 100, 5, 6)
+ s.sizeOf()
+ require.NoError(t, s.writeTo(&stateWriter{kv: kv}))
+
+ obs, err := observe(t, c, kv, blobs)
+ require.NoError(t, err)
+ assert.Equal(t, map[string]uint32{"local-wf": 3, "queued-wf": 7, "observed-wf": 8}, obs.WorkflowCapacities)
+ })
+
+ t.Run("events this node already observed in state are not re-observed", func(t *testing.T) {
+ t.Parallel()
+ blobs, kv := &memBlobs{}, memKV{}
+ mine, theirs := mkEvents(t, 2, 2000), mkEvents(t, 4, 2000)[2:]
+ c := newCommitPlugin(t, &recCoordinator{}, &recQueue{sliceQueue: sliceQueue{events: append(append([]hashedEvent{}, mine...), theirs...)}}, blobs)
+
+ s := newKVState()
+ s.observedEvents[string(mine[0].hash)] = obsEvent(testWF, "m0", 100, 0, 1) // includes OracleID 0 (this node)
+ s.observedEvents[string(mine[1].hash)] = obsEvent(testWF, "m1", 100, 2, 3) // does not
+ s.sizeOf()
+ require.NoError(t, s.writeTo(&stateWriter{kv: kv}))
+
+ obs, err := observe(t, c, kv, blobs)
+ require.NoError(t, err)
+ got := make([][]byte, 0, len(obs.Events))
+ for _, e := range obs.Events {
+ got = append(got, e.TimelessHash)
+ }
+ assert.NotContains(t, got, mine[0].hash, "already observed by this node")
+ assert.Contains(t, got, mine[1].hash, "observed by others only, so this node adds its vote")
+ assert.Contains(t, got, theirs[0].hash)
+ assert.Contains(t, got, theirs[1].hash)
+ })
+}
+
+func TestObservation_BlobBatching(t *testing.T) {
+ t.Parallel()
+
+ // checkRefs verifies every observed event's blob ref resolves to that event in a broadcast blob.
+ checkRefs := func(t *testing.T, obs *pb.ConsensusQueueObservation, blobs *memBlobs) {
+ t.Helper()
+ for i, e := range obs.Events {
+ require.Less(t, int(e.Blobs[0].Blob), len(obs.BlobHandles), "event %d", i)
+ payload, ok := blobs.byHandle[string(obs.BlobHandles[e.Blobs[0].Blob])] // broadcast order is not defined, so go by handle
+ require.True(t, ok, "event %d", i)
+ _, raw, err := extractEvent(payload, int(e.Blobs[0].Element))
+ require.NoError(t, err, "event %d", i)
+ sum := sha256.Sum256(raw)
+ assert.Equal(t, e.TimelessHash, sum[:], "event %d resolves to its own blob element", i)
+ }
+ }
+ events := func(t *testing.T, n int) []hashedEvent {
+ return mkEvents(t, n, time.Now().Add(time.Hour).Unix())
+ }
+
+ t.Run("events spread over several blobs keep correct refs", func(t *testing.T) {
+ t.Parallel()
+ blobs := &memBlobs{}
+ ev := events(t, 6)
+ c := testPlugin(t, sliceQueue{events: ev}, blobs, ocr3_1types.MaxMaxObservationBytes)
+ c.limits.MaxBlobPayloadBytes = proto.Size(&pb.CoordinatedEventList{Events: []*pb.CoordinatedEvent{ev[0].event, ev[1].event}}) // two per blob
+
+ obs, err := observe(t, c, memKV{}, blobs)
+ require.NoError(t, err)
+ require.Len(t, obs.Events, 6)
+ assert.Len(t, obs.BlobHandles, 3)
+ assert.Len(t, blobs.payloads, 3)
+ checkRefs(t, obs, blobs)
+ })
+
+ t.Run("more events than blob handles are truncated", func(t *testing.T) {
+ t.Parallel()
+ blobs := &memBlobs{}
+ ev := events(t, 15)
+ c := testPlugin(t, sliceQueue{events: ev}, blobs, ocr3_1types.MaxMaxObservationBytes)
+ c.limits.MaxBlobPayloadBytes = proto.Size(&pb.CoordinatedEventList{Events: []*pb.CoordinatedEvent{ev[0].event}}) // one per blob
+
+ obs, err := observe(t, c, memKV{}, blobs)
+ require.NoError(t, err)
+ require.Len(t, obs.BlobHandles, maxObservedBlobHandles)
+ require.Len(t, obs.Events, maxObservedBlobHandles, "events beyond the last blob are dropped")
+ checkRefs(t, obs, blobs)
+ for i, e := range obs.Events { // earliest first
+ assert.Equal(t, ev[i].hash, e.TimelessHash)
+ }
+ assert.Contains(t, obs.WorkflowCapacities, testWF)
+ })
+
+ t.Run("size limited observations keep only the events that fit", func(t *testing.T) {
+ t.Parallel()
+ blobs := &memBlobs{}
+ ev := events(t, 10)
+ c := testPlugin(t, sliceQueue{events: ev}, blobs, ocr3_1types.MaxMaxObservationBytes)
+
+ // Observation reserves space for maxObservedBlobHandles handles up front, so size a probe the same way for 5 events.
+ probe := &pb.ConsensusQueueObservation{Expiration: ts(time.Now().Unix()), WorkflowCapacities: map[string]uint32{}}
+ for range maxObservedBlobHandles {
+ probe.BlobHandles = append(probe.BlobHandles, make([]byte, c.blobHandleMarshalledBytesUpperBound))
+ }
+ for _, e := range ev[:5] {
+ _, err := observeEvent(probe, e.hash, proto.CloneOf(e.event), nil)
+ require.NoError(t, err)
+ }
+ c.limits.MaxObservationBytes = proto.Size(probe) + 16 // slack for timestamp nanos; a 6th event needs far more
+
+ obs, err := observe(t, c, memKV{}, blobs)
+ require.NoError(t, err)
+ require.Len(t, obs.Events, 5)
+ assert.LessOrEqual(t, proto.Size(obs), c.limits.MaxObservationBytes)
+ checkRefs(t, obs, blobs)
+ for i, e := range obs.Events {
+ assert.Equal(t, ev[i].hash, e.TimelessHash, "the earliest events are kept")
+ }
+ })
+}
+
+// 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) {
+ t.Parallel()
+
+ t.Run("broadcast error", func(t *testing.T) {
+ t.Parallel()
+ blobs := &hintBlobs{err: errBoom}
+ c := testPlugin(t, sliceQueue{events: mkEvents(t, 2, time.Now().Add(time.Hour).Unix())}, blobs, ocr3_1types.MaxMaxObservationBytes)
+ obs, err := observe(t, c, memKV{}, blobs)
+ require.NoError(t, err, "a failed broadcast should degrade to an observation without those events")
+ assert.Empty(t, obs.Events)
+ })
+
+ t.Run("event larger than a blob", func(t *testing.T) {
+ t.Parallel()
+ blobs := &memBlobs{}
+ c := testPlugin(t, sliceQueue{events: mkEvents(t, 2, time.Now().Add(time.Hour).Unix())}, blobs, ocr3_1types.MaxMaxObservationBytes)
+ c.limits.MaxBlobPayloadBytes = 1
+ obs, err := observe(t, c, memKV{}, blobs)
+ require.NoError(t, err, "an unbroadcastable event should be dropped, not fail every observation")
+ assert.Empty(t, obs.Events)
+ })
+}
+
+// The queue drops events that can never be observed, so the plugin must pass it the largest event that fits in a blob.
+func TestObservation_PassesMaxEventBytesToQueue(t *testing.T) {
+ t.Parallel()
+
+ q := &recQueue{}
+ c := newCommitPlugin(t, &recCoordinator{}, q, &memBlobs{})
+ c.limits.MaxBlobPayloadBytes = 1000
+ _, err := observe(t, c, memKV{}, &memBlobs{})
+ require.NoError(t, err)
+
+ assert.Equal(t, maxObservedEvents, q.sortedLimit)
+ assert.Equal(t, 1000-maxEventFramingOverhead, q.sortedSize)
+
+ t.Run("limits too small to hold any event disable filtering rather than dropping everything", func(t *testing.T) {
+ c.limits.MaxBlobPayloadBytes = 0
+ _, err := observe(t, c, memKV{}, &memBlobs{})
+ require.NoError(t, err)
+ assert.Zero(t, q.sortedSize)
+ })
+}
+
+// An event of exactly maxEventBytes must fit alone in a blob of the configured size, for any limit libocr allows.
+func TestMaxEventBytes(t *testing.T) {
+ t.Parallel()
+
+ eventOfSize := func(k int) *pb.CoordinatedEvent { // event whose encoded size grows with k
+ e, _ := blobEvent(t, testWF, "evt")
+ e.Event.Event.TriggerType = strings.Repeat("x", k)
+ return e
+ }
+ for _, limit := range []int{6, 127, 128, 129, 1 << 14, 1<<21 - 1, 1 << 21, ocr3_1types.MaxMaxBlobPayloadBytes} {
+ t.Run(strconv.Itoa(limit), func(t *testing.T) {
+ t.Parallel()
+ c := testPlugin(t, sliceQueue{}, &memBlobs{}, ocr3_1types.MaxMaxObservationBytes)
+ c.limits.MaxBlobPayloadBytes = limit
+ maxSize := c.maxEventBytes()
+ require.GreaterOrEqual(t, maxSize, 0)
+ require.LessOrEqual(t, maxSize, limit)
+
+ // largest event that passes the filter
+ if proto.Size(eventOfSize(0)) > maxSize {
+ return // nothing fits at this limit
+ }
+ k := sort.Search(limit, func(k int) bool { return proto.Size(eventOfSize(k)) > maxSize }) - 1
+ e := eventOfSize(k)
+ require.LessOrEqual(t, proto.Size(e), maxSize)
+ assert.LessOrEqual(t, proto.Size(&pb.CoordinatedEventList{Events: []*pb.CoordinatedEvent{e}}), limit,
+ "an event passing the filter must fit alone in a blob")
+ })
+ }
+}
+
+func TestValidateObservation_Fields(t *testing.T) {
+ t.Parallel()
+
+ badTS := ×tamppb.Timestamp{Seconds: 1, Nanos: 2_000_000_000}
+ tests := []struct {
+ name string
+ mutate func(c *consensusQueuePlugin, o *pb.ConsensusQueueObservation)
+ wantErr string
+ }{
+ {"invalid expiration", func(_ *consensusQueuePlugin, o *pb.ConsensusQueueObservation) { o.Expiration = badTS }, "invalid expiration"},
+ {"invalid event observed at", func(_ *consensusQueuePlugin, o *pb.ConsensusQueueObservation) { o.Events[0].ObservedAt = badTS }, "invalid event observation ts"},
+ {"invalid event deadline", func(_ *consensusQueuePlugin, o *pb.ConsensusQueueObservation) { o.Events[0].Deadline = badTS }, "invalid event deadline"},
+ {"blob handle longer than any real handle", func(c *consensusQueuePlugin, o *pb.ConsensusQueueObservation) {
+ o.BlobHandles = append(o.BlobHandles, make([]byte, c.blobHandleMarshalledBytesUpperBound+1))
+ }, "more than the maximum"},
+ {"empty hash", func(_ *consensusQueuePlugin, o *pb.ConsensusQueueObservation) { o.Events[0].TimelessHash = []byte{} }, "hash is missing"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ c, blobs, obs := observeN(t, 2)
+ tt.mutate(c, obs)
+ require.ErrorContains(t, validate(t, c, blobs, obs), tt.wantErr)
+ })
+ }
+}
+
+func TestObservationsAggregate_Omissions(t *testing.T) {
+ t.Parallel()
+ const f = 1
+
+ mk := func(wfCaps map[string]uint32) *pb.ConsensusQueueObservation {
+ return &pb.ConsensusQueueObservation{Expiration: ts(100), Capacity: 5, WorkflowCapacities: wfCaps}
+ }
+ aoOf := func(t *testing.T, obs ...*pb.ConsensusQueueObservation) (out []ocrtypes.AttributedObservation) {
+ for i, o := range obs {
+ out = append(out, ao(t, i, o))
+ }
+ return
+ }
+
+ t.Run("a workflow one node omits still gets the capacity the others report", func(t *testing.T) {
+ t.Parallel()
+ var res observations
+ res.aggregate(t.Context(), f, aoOf(t, mk(map[string]uint32{testWF: 9}), mk(map[string]uint32{testWF: 9}), mk(nil)))
+ require.NoError(t, res.err)
+ assert.Equal(t, uint32(9), res.fPlus1thCapPerWF[testWF], "F omissions count as zero, which sorted[F] tolerates")
+ })
+
+ t.Run("a workflow most nodes omit gets zero", func(t *testing.T) {
+ t.Parallel()
+ var res observations
+ res.aggregate(t.Context(), f, aoOf(t, mk(map[string]uint32{testWF: 9}), mk(nil), mk(nil)))
+ require.NoError(t, res.err)
+ assert.Contains(t, res.fPlus1thCapPerWF, testWF)
+ assert.Zero(t, res.fPlus1thCapPerWF[testWF])
+ })
+
+ t.Run("too few observations is an error, not a panic", func(t *testing.T) {
+ t.Parallel()
+ var res observations
+ require.NotPanics(t, func() { res.aggregate(t.Context(), f, aoOf(t, mk(nil))) })
+ require.Error(t, res.err)
+ require.NotPanics(t, func() { res.aggregate(t.Context(), f, nil) })
+ require.Error(t, res.err)
+
+ kv := memKV{}
+ require.Error(t, stateTransition(t, newSTPlugin(t), kv, aoOf(t, mk(nil))...))
+ assert.Empty(t, kv)
+ })
+}
+
+func TestNewConsensusQueuePluginFactory_Validation(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ coord triggers.Coordinator
+ queue triggers.Queue
+ }{
+ {"nil coordinator", nil, noopQueue{}},
+ {"nil queue", noopCoordinator{}, nil},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ f, err := NewConsensusQueuePluginFactory(logger.Test(t), limits.Factory{}, tt.coord, tt.queue, noop.NewMeterProvider().Meter("test"))
+ require.Error(t, err)
+ assert.Nil(t, f)
+ })
+ }
+}
+
+func TestNewConsensusQueuePluginFactory_NilMeter(t *testing.T) {
+ t.Parallel()
+ f, err := NewConsensusQueuePluginFactory(logger.Test(t), limits.Factory{}, noopCoordinator{}, noopQueue{}, nil)
+ require.ErrorContains(t, err, "meter")
+ assert.Nil(t, f)
+}
+
+func TestBroadcastAsBlob_LargestFit(t *testing.T) {
+ t.Parallel()
+
+ blobs := &hintBlobs{}
+ c := testPlugin(t, sliceQueue{}, blobs, ocr3_1types.MaxMaxObservationBytes)
+ events := eventsWithDeadline(t, 50, time.Now().Add(time.Hour))
+ sizeOf := func(n int) int { return proto.Size(&pb.CoordinatedEventList{Events: events[:n]}) }
+
+ for _, want := range []int{1, 2, 17, 36, 49, 50} {
+ c.limits.MaxBlobPayloadBytes = sizeOf(want) // exactly fits want events
+ _, n, err := c.broadcastAsBlob(t.Context(), blobs, events, 1)
+ require.NoError(t, err)
+ assert.Equal(t, want, n, "limit == size of %d events", want)
+
+ if want > 1 {
+ c.limits.MaxBlobPayloadBytes = sizeOf(want) - 1 // one byte short
+ _, n, err = c.broadcastAsBlob(t.Context(), blobs, events, 1)
+ require.NoError(t, err)
+ assert.Equal(t, want-1, n, "one byte short of %d events", want)
+ }
+ }
+}
+
+// multiBlobObservation builds an observation of 6 events spread over 3 blobs (two per blob).
+func multiBlobObservation(t *testing.T) (*consensusQueuePlugin, *memBlobs, *pb.ConsensusQueueObservation) {
+ t.Helper()
+ ev := mkEvents(t, 6, time.Now().Add(time.Hour).Unix())
+ blobs := &memBlobs{}
+ c := testPlugin(t, sliceQueue{events: ev}, blobs, ocr3_1types.MaxMaxObservationBytes)
+ c.limits.MaxBlobPayloadBytes = proto.Size(&pb.CoordinatedEventList{Events: []*pb.CoordinatedEvent{ev[0].event, ev[1].event}})
+ obs, err := observe(t, c, memKV{}, blobs)
+ require.NoError(t, err)
+ require.Len(t, obs.Events, 6)
+ require.Len(t, obs.BlobHandles, 3)
+ return c, blobs, obs
+}
+
+func TestValidateObservation_MultipleBlobs(t *testing.T) {
+ t.Parallel()
+
+ t.Run("an observation spanning several blobs is valid", func(t *testing.T) {
+ t.Parallel()
+ c, blobs, obs := multiBlobObservation(t)
+ require.NoError(t, validate(t, c, blobs, obs))
+ })
+
+ t.Run("an event pointing at another blob is rejected", func(t *testing.T) {
+ t.Parallel()
+ c, blobs, obs := multiBlobObservation(t)
+ obs.Events[0].Blobs[0].Blob = 2 // blob 2 holds different events
+ require.Error(t, validate(t, c, blobs, obs))
+ })
+
+ t.Run("an element past the end of its blob is rejected", func(t *testing.T) {
+ t.Parallel()
+ c, blobs, obs := multiBlobObservation(t)
+ obs.Events[5].Blobs[0].Element = 2 // blobs hold two events
+ require.Error(t, validate(t, c, blobs, obs))
+ })
+
+ t.Run("a blob that cannot be fetched is rejected", func(t *testing.T) {
+ t.Parallel()
+ c, blobs, obs := multiBlobObservation(t)
+ delete(blobs.byHandle, marshalHandle(testBlobHandle(2))) // the second blob is unavailable
+ require.ErrorContains(t, validate(t, c, blobs, obs), "unknown blob handle")
+ })
+
+ t.Run("the same blob is fetched once however many events it holds", func(t *testing.T) {
+ t.Parallel()
+ c, blobs, obs := multiBlobObservation(t)
+ counting := &fetchCountingBlobs{memBlobs: blobs}
+ raw, err := proto.Marshal(obs)
+ require.NoError(t, err)
+ require.NoError(t, c.ValidateObservation(t.Context(), 1, ocrtypes.AttributedQuery{}, ocrtypes.AttributedObservation{Observation: raw}, memKV{}, counting))
+ assert.Equal(t, 3, int(counting.fetches.Load()), "6 events over 3 blobs")
+ })
+}
+
+type fetchCountingBlobs struct {
+ *memBlobs
+ fetches atomic.Int32
+}
+
+func (f *fetchCountingBlobs) FetchBlob(ctx context.Context, h ocr3_1types.BlobHandle) ([]byte, error) {
+ f.fetches.Add(1)
+ return f.memBlobs.FetchBlob(ctx, h)
+}
+
+// ctxBlobs fails like libocr does when its context is done.
+type ctxBlobs struct{}
+
+func (ctxBlobs) BroadcastBlob(ctx context.Context, _ []byte, _ ocr3_1types.BlobExpirationHint) (ocr3_1types.BlobHandle, error) {
+ return ocr3_1types.BlobHandle{}, ctx.Err()
+}
+
+func (ctxBlobs) FetchBlob(ctx context.Context, _ ocr3_1types.BlobHandle) ([]byte, error) {
+ return nil, ctx.Err()
+}
+
+func cancelledCtx(t *testing.T) context.Context {
+ t.Helper()
+ ctx, cancel := context.WithCancel(t.Context())
+ cancel()
+ return ctx
+}
+
+// A cancelled context may never turn into a successful but different result: determinism requires that a function
+// that returns without an error behaves the same however its context behaves. Each path must fail instead.
+func TestContextCancellation(t *testing.T) {
+ t.Parallel()
+
+ t.Run("aggregate reports cancellation as an error instead of returning a partial result", func(t *testing.T) {
+ t.Parallel()
+ e := mkEvents(t, 2, 2000)
+ withEvents := []ocrtypes.AttributedObservation{
+ ao(t, 0, nodeObs(t, stdNode, e...)), ao(t, 1, nodeObs(t, stdNode, e...)), ao(t, 2, nodeObs(t, stdNode, e...)),
+ }
+ withoutEvents := []ocrtypes.AttributedObservation{ao(t, 0, nodeObs(t, stdNode)), ao(t, 1, nodeObs(t, stdNode)), ao(t, 2, nodeObs(t, stdNode))}
+ for name, aos := range map[string][]ocrtypes.AttributedObservation{"with events": withEvents, "without events": withoutEvents} {
+ var res observations
+ res.aggregate(cancelledCtx(t), 1, aos)
+ require.ErrorIs(t, res.err, context.Canceled, name)
+ }
+ })
+
+ t.Run("StateTransition fails and writes nothing", func(t *testing.T) {
+ t.Parallel()
+ e := mkEvents(t, 1, 2000)
+ kv := memKV{}
+ _, err := newSTPlugin(t).StateTransition(cancelledCtx(t), 1, ocrtypes.AttributedQuery{},
+ []ocrtypes.AttributedObservation{ao(t, 0, nodeObs(t, stdNode, e...)), ao(t, 1, nodeObs(t, stdNode, e...)), ao(t, 2, nodeObs(t, stdNode, e...))}, kv, nil)
+ require.ErrorIs(t, err, context.Canceled)
+ assert.Empty(t, kv)
+ })
+
+ t.Run("ValidateObservation does not accept events it could not fetch", func(t *testing.T) {
+ t.Parallel()
+ c, _, obs := observeN(t, 2)
+ raw, err := proto.Marshal(obs)
+ require.NoError(t, err)
+ err = c.ValidateObservation(cancelledCtx(t), 1, ocrtypes.AttributedQuery{}, ocrtypes.AttributedObservation{Observation: raw}, memKV{}, ctxBlobs{})
+ require.ErrorIs(t, err, context.Canceled)
+ })
+
+ t.Run("Observation fails instead of degrading to an observation without events", func(t *testing.T) {
+ t.Parallel()
+ ev := mkEvents(t, 2, time.Now().Add(time.Hour).Unix())
+ c := testPlugin(t, sliceQueue{events: ev}, ctxBlobs{}, ocr3_1types.MaxMaxObservationBytes)
+ _, err := c.Observation(cancelledCtx(t), 1, ocrtypes.AttributedQuery{}, memKV{}, ctxBlobs{})
+ require.ErrorIs(t, err, context.Canceled)
+ })
+
+ t.Run("Observation fails if one of several blob broadcasts is cancelled", func(t *testing.T) {
+ t.Parallel()
+ ev := mkEvents(t, 4, time.Now().Add(time.Hour).Unix())
+ ctx, cancel := context.WithCancel(t.Context())
+ blobs := &cancelOnSecondBroadcast{cancel: cancel}
+ c := testPlugin(t, sliceQueue{events: ev}, blobs, ocr3_1types.MaxMaxObservationBytes)
+ c.limits.MaxBlobPayloadBytes = proto.Size(&pb.CoordinatedEventList{Events: []*pb.CoordinatedEvent{ev[0].event, ev[1].event}})
+ _, err := c.Observation(ctx, 1, ocrtypes.AttributedQuery{}, memKV{}, blobs)
+ require.ErrorIs(t, err, context.Canceled, "must fail, not return an observation with only the blob that succeeded")
+ })
+
+ t.Run("Committed returns promptly and does not panic", func(t *testing.T) {
+ t.Parallel()
+ coord, blobs, kv := &recCoordinator{}, &memBlobs{}, memKV{}
+ c := newCommitPlugin(t, coord, &recQueue{}, blobs)
+ seedKV(t, kv, blobs, []string{"a", "b"}, []string{"c"})
+ within(t, 5*time.Second, func() {
+ require.NoError(t, c.Committed(cancelledCtx(t), 1, kv))
+ })
+ })
+}
+
+// cancelOnSecondBroadcast succeeds once, then cancels the context and fails like libocr would. Calls may be concurrent.
+type cancelOnSecondBroadcast struct {
+ memBlobs
+ cancel context.CancelFunc
+ calls atomic.Int32
+}
+
+func (c *cancelOnSecondBroadcast) BroadcastBlob(ctx context.Context, payload []byte, hint ocr3_1types.BlobExpirationHint) (ocr3_1types.BlobHandle, error) {
+ if c.calls.Add(1) > 1 {
+ c.cancel()
+ return ocr3_1types.BlobHandle{}, ctx.Err()
+ }
+ return c.memBlobs.BroadcastBlob(ctx, payload, hint)
+}
+
+// failBlobsWith fails to broadcast the blob that starts with the given event, and broadcasts the others.
+type failBlobsWith struct {
+ memBlobs
+ firstID string
+}
+
+func (f *failBlobsWith) BroadcastBlob(ctx context.Context, payload []byte, hint ocr3_1types.BlobExpirationHint) (ocr3_1types.BlobHandle, error) {
+ if first, _, err := extractEvent(payload, 0); err == nil && first.Event.Event.Id == f.firstID {
+ return ocr3_1types.BlobHandle{}, errBoom
+ }
+ return f.memBlobs.BroadcastBlob(ctx, payload, hint)
+}
+
+func TestObservation_PartialBlobFailure(t *testing.T) {
+ t.Parallel()
+
+ ev := mkEvents(t, 6, time.Now().Add(time.Hour).Unix()) // two events per blob
+ perBlob := proto.Size(&pb.CoordinatedEventList{Events: []*pb.CoordinatedEvent{ev[0].event, ev[1].event}})
+
+ for _, tt := range []struct {
+ name string
+ failBlobAt int // index of the first event of the blob that fails
+ wantEvents int
+ }{
+ {"first", 0, 4},
+ {"middle", 2, 4},
+ {"last", 4, 4},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ blobs := &failBlobsWith{firstID: ev[tt.failBlobAt].event.Event.Event.Id}
+ c := testPlugin(t, sliceQueue{events: ev}, blobs, ocr3_1types.MaxMaxObservationBytes)
+ c.limits.MaxBlobPayloadBytes = perBlob
+
+ obs, err := observe(t, c, memKV{}, blobs)
+ require.NoError(t, err)
+ require.Len(t, obs.Events, tt.wantEvents)
+ assert.Len(t, obs.BlobHandles, tt.wantEvents/2)
+ var i, oi int
+ for _, e := range obs.Events {
+ for tt.failBlobAt == oi {
+ oi += 2
+ }
+ assert.Equal(t, ev[oi].hash, e.TimelessHash, "events stay in order")
+ assert.Equal(t, uint32(i/2), e.Blobs[0].Blob)
+ assert.Equal(t, uint32(i%2), e.Blobs[0].Element)
+ i++
+ oi++
+ }
+ if tt.wantEvents > 0 {
+ assert.Contains(t, obs.WorkflowCapacities, testWF, "capacities cover the events kept")
+ require.NoError(t, validate(t, c, &blobs.memBlobs, obs), "what remains is a valid observation")
+ }
+ })
+ }
+}
+
+// ---- Benchmarks of full (packed to the limit) rounds ----
+//
+// Run with: go test -run '^$' -bench Full -benchtime 3x ./core/services/ocr3_1/plugins/queue/
+//
+// KV and blob calls sleep, to model what the plugin waits on in a real round. The durations are ASSUMPTIONS, not
+// measurements from a running DON: libocr's KV is a local embedded database (sub-millisecond), while a blob broadcast
+// waits for availability signatures from peers over p2p (tens of milliseconds, growing with size) and a fetch pulls the
+// blob from a peer. Replace the numbers with measured ones to re-calibrate. The "avg" profile makes every call take
+// the average, and "max" makes every call take the maximum, so together they bound the round.
+
+// ioProfile is how long each KV and blob operation takes: a fixed part plus a part per MiB moved.
+type ioProfile struct {
+ name string
+ kvRead, kvWrite, kvPerMiB time.Duration
+ blobBroadcast, blobBroadcastPerMiB time.Duration
+ blobFetch, blobFetchPerMiB time.Duration
+}
+
+var ioProfiles = []ioProfile{
+ {name: "noIO"},
+ {
+ name: "avgIO",
+ kvRead: 200 * time.Microsecond, kvWrite: 300 * time.Microsecond, kvPerMiB: time.Millisecond,
+ blobBroadcast: 30 * time.Millisecond, blobBroadcastPerMiB: 10 * time.Millisecond,
+ blobFetch: 10 * time.Millisecond, blobFetchPerMiB: 5 * time.Millisecond,
+ },
+ {
+ name: "maxIO",
+ kvRead: 2 * time.Millisecond, kvWrite: 3 * time.Millisecond, kvPerMiB: 3 * time.Millisecond,
+ blobBroadcast: 450 * time.Millisecond, blobBroadcastPerMiB: 60 * time.Millisecond, // 750ms for a 5MiB blob: observed worst case is 600-800ms
+ blobFetch: 100 * time.Millisecond, blobFetchPerMiB: 15 * time.Millisecond,
+ },
+}
+
+func perMiB(d time.Duration, n int) time.Duration { return d * time.Duration(n) / (1 << 20) }
+
+// delayKV adds the profile's latency to KV reads and writes.
+type delayKV struct {
+ ocr3_1types.KeyValueStateReadWriter
+ p ioProfile
+}
+
+func (d delayKV) Read(k []byte) ([]byte, error) {
+ v, err := d.KeyValueStateReadWriter.Read(k)
+ time.Sleep(d.p.kvRead + perMiB(d.p.kvPerMiB, len(v)))
+ return v, err
+}
+
+func (d delayKV) Write(k, v []byte) error {
+ time.Sleep(d.p.kvWrite + perMiB(d.p.kvPerMiB, len(v)))
+ return d.KeyValueStateReadWriter.Write(k, v)
+}
+
+// delayBlobs adds the profile's latency to blob broadcasts and fetches.
+type delayBlobs struct {
+ *memBlobs
+ p ioProfile
+}
+
+func (d delayBlobs) BroadcastBlob(ctx context.Context, payload []byte, hint ocr3_1types.BlobExpirationHint) (ocr3_1types.BlobHandle, error) {
+ time.Sleep(d.p.blobBroadcast + perMiB(d.p.blobBroadcastPerMiB, len(payload)))
+ return d.memBlobs.BroadcastBlob(ctx, payload, hint)
+}
+
+func (d delayBlobs) FetchBlob(ctx context.Context, h ocr3_1types.BlobHandle) ([]byte, error) {
+ v, err := d.memBlobs.FetchBlob(ctx, h)
+ time.Sleep(d.p.blobFetch + perMiB(d.p.blobFetchPerMiB, len(v)))
+ return v, err
+}
+
+// packedEvents makes n events across 50 workflows, each with a trigger payload of the given size, in deadline order.
+func packedEvents(tb testing.TB, n, payload int) []hashedEvent {
+ tb.Helper()
+ out := make([]hashedEvent, 0, n)
+ for i := range n {
+ e := eventOfPayload(i, payload)
+ e.WorkflowID = hexID(testWF, i%50)
+ b, err := e.MarshalTimeless()
+ require.NoError(tb, err)
+ sum := sha256.Sum256(b)
+ e.ObservedAt = ts(1_800_000_000 + int64(i))
+ e.Deadline = ts(4_000_000_000 + int64(i))
+ out = append(out, hashedEvent{sum[:], e})
+ }
+ return out
+}
+
+// packShape is a full observation: maxObservedEvents events of one payload size.
+type packShape struct {
+ name string
+ payload int
+}
+
+func packShapes() []packShape {
+ // the largest payload that still lets maxObservedEvents events fill maxObservedBlobHandles blobs
+ maxPayload := sort.Search(ocr3_1types.MaxMaxBlobPayloadBytes, func(p int) bool {
+ blobs, _, _ := blobsNeeded(p, ocr3_1types.MaxMaxBlobPayloadBytes)
+ return blobs == 0 || blobs > maxObservedBlobHandles
+ }) - 1
+ return []packShape{
+ {"1000xCron128B", 128},
+ {"1000xEVM8KB", 8 << 10},
+ {fmt.Sprintf("1000xMaxPacked%dKB", maxPayload>>10), maxPayload},
+ }
+}
+
+func fullLimitsPlugin(b *testing.B, events []hashedEvent, blobs ocr3_1types.BlobBroadcastFetcher) *consensusQueuePlugin {
+ b.Helper()
+ c := testPlugin(b, sliceQueue{events: events}, blobs, ocr3_1types.MaxMaxObservationBytes)
+ c.limits.MaxBlobPayloadBytes = ocr3_1types.MaxMaxBlobPayloadBytes
+ c.limits.MaxKeyValueModifiedKeysPlusValuesBytes = ocr3_1types.MaxMaxKeyValueModifiedKeysPlusValuesBytes
+ return c
+}
+
+// BenchmarkFullObservation measures building and broadcasting an observation packed to maxObservedEvents.
+func BenchmarkFullObservation(b *testing.B) {
+ for _, shape := range packShapes() {
+ for _, io := range ioProfiles {
+ b.Run(shape.name+"/"+io.name, func(b *testing.B) {
+ events := packedEvents(b, maxObservedEvents, shape.payload)
+ store := &memBlobs{}
+ blobs := delayBlobs{store, io}
+ c := fullLimitsPlugin(b, events, blobs)
+ kv := delayKV{memKV{}, io}
+
+ var raw []byte
+ b.ResetTimer()
+ for i := range b.N {
+ store.payloads, store.byHandle = nil, nil
+ var err error
+ raw, err = c.Observation(b.Context(), uint64(i+1), ocrtypes.AttributedQuery{}, kv, blobs)
+ require.NoError(b, err)
+ }
+ b.StopTimer()
+
+ var obs pb.ConsensusQueueObservation
+ require.NoError(b, proto.Unmarshal(raw, &obs))
+ b.ReportMetric(float64(len(obs.Events)), "events/op")
+ b.ReportMetric(float64(len(obs.BlobHandles)), "blobs/op")
+ b.ReportMetric(float64(len(raw))/1024, "obsKiB/op")
+ })
+ }
+ }
+}
+
+// BenchmarkFullValidateObservation measures validating a peer's packed observation: fetching its blobs and checking every event.
+func BenchmarkFullValidateObservation(b *testing.B) {
+ for _, shape := range packShapes() {
+ for _, io := range ioProfiles {
+ b.Run(shape.name+"/"+io.name, func(b *testing.B) {
+ events := packedEvents(b, maxObservedEvents, shape.payload)
+ store := &memBlobs{}
+ c := fullLimitsPlugin(b, events, store)
+ raw, err := c.Observation(b.Context(), 1, ocrtypes.AttributedQuery{}, memKV{}, store) // built without delays
+ require.NoError(b, err)
+
+ blobs, kv := delayBlobs{store, io}, delayKV{memKV{}, io}
+ b.ResetTimer()
+ for range b.N {
+ require.NoError(b, c.ValidateObservation(b.Context(), 1, ocrtypes.AttributedQuery{}, ocrtypes.AttributedObservation{Observation: raw}, kv, blobs))
+ }
+ })
+ }
+ }
+}
+
+// BenchmarkFullStateTransition measures a round where every node observes maxObservedEvents events against a populated KV state.
+func BenchmarkFullStateTransition(b *testing.B) {
+ for _, n := range []int{4, 31} {
+ for _, io := range ioProfiles {
+ b.Run(fmt.Sprintf("N=%d/%s", n, io.name), func(b *testing.B) {
+ f := (n - 1) / 3
+ c := newSTPlugin(b)
+ c.onchainCfg.N, c.onchainCfg.F = n, f
+ c.limits.MaxKeyValueModifiedKeysPlusValuesBytes = ocr3_1types.MaxMaxKeyValueModifiedKeysPlusValuesBytes
+ open := nodeOpts{capacity: 1 << 20, wfCaps: map[string]uint32{}, expiration: 100}
+ all := packedEvents(b, 2500, 0)
+ for _, e := range all {
+ open.wfCaps[e.event.WorkflowID] = 1 << 20
+ }
+ quorum := func(events []hashedEvent, nodes int) (aos []ocrtypes.AttributedObservation) {
+ for node := range n {
+ var seen []hashedEvent
+ if node < nodes {
+ seen = events
+ }
+ aos = append(aos, ao(b, node, nodeObs(b, open, seen...)))
+ }
+ return aos
+ }
+
+ // prior state: 1000 events queued, 500 waiting at f+1 votes. Capacity 0 so that nothing executed yet.
+ none := open
+ none.capacity = 0
+ seed := memKV{}
+ setup := func(events []hashedEvent, nodes int) []ocrtypes.AttributedObservation {
+ var aos []ocrtypes.AttributedObservation
+ for node := range n {
+ var seen []hashedEvent
+ if node < nodes {
+ seen = events
+ }
+ aos = append(aos, ao(b, node, nodeObs(b, none, seen...)))
+ }
+ return aos
+ }
+ require.NoError(b, stateTransition(b, c, seed, setup(all[:1000], n)...))
+ require.NoError(b, stateTransition(b, c, seed, setup(all[1000:1500], f+1)...))
+
+ // this round: 500 new events from everyone, the 500 waiting events gain votes, 1000 more are new
+ aos := quorum(all[1000:], n)
+ var written int
+ b.ResetTimer()
+ for range b.N {
+ b.StopTimer()
+ kv := &countingKV{memKV: maps.Clone(seed)}
+ b.StartTimer()
+ require.NoError(b, stateTransition(b, c, delayKV{kv, io}, aos...))
+ written = kv.written
+ }
+ b.StopTimer()
+ b.ReportMetric(float64(written)/1024, "kvWrittenKiB/op")
+ b.ReportMetric(float64(len(aos[0].Observation))/1024, "obsKiB/node")
+ })
+ }
+ }
+}
+
+type countingKV struct {
+ memKV
+ written int
+}
+
+func (c *countingKV) Write(k, v []byte) error {
+ c.written += len(k) + len(v)
+ return c.memKV.Write(k, v)
+}
+
+// BenchmarkFullCommit measures starting a full consensus set, which fetches its blobs (concurrently) and starts each event.
+func BenchmarkFullCommit(b *testing.B) {
+ for _, shape := range packShapes() {
+ for _, io := range ioProfiles {
+ b.Run(shape.name+"/"+io.name, func(b *testing.B) {
+ events := packedEvents(b, maxObservedEvents, shape.payload)
+ store := &memBlobs{}
+ coord := &recCoordinator{}
+ c := newCommitPlugin(b, coord, &recQueue{}, delayBlobs{store, io})
+ c.limits.MaxBlobPayloadBytes = ocr3_1types.MaxMaxBlobPayloadBytes
+
+ // the consensus set references blobs the way a StateTransition would have written it
+ s := newKVState()
+ stripped := make([]*pb.CoordinatedEvent, len(events))
+ for i, e := range events {
+ stripped[i] = proto.CloneOf(e.event)
+ stripped[i].ObservedAt, stripped[i].Deadline = nil, nil
+ }
+ rest := stripped
+ for len(rest) > 0 {
+ handle, n, err := c.broadcastAsBlob(b.Context(), store, rest, 1)
+ require.NoError(b, err)
+ for i := range n {
+ s.queuedBlobs.add(string(events[len(stripped)-len(rest)+i].hash), string(handle), uint32(i))
+ }
+ rest = rest[n:]
+ }
+ for _, e := range events {
+ s.consensusEvents = append(s.consensusEvents, &pb.ConsensusQueueEvent{
+ WorkflowID: e.event.WorkflowID, ExecutionID: hexID("exec", len(s.consensusEvents)),
+ ObservedAt: e.event.ObservedAt, Deadline: e.event.Deadline, TimelessHash: e.hash,
+ })
+ }
+ s.sizeOf()
+ kv := memKV{}
+ require.NoError(b, s.writeTo(&stateWriter{kv: kv}))
+
+ b.ResetTimer()
+ for range b.N {
+ coord.mu.Lock()
+ coord.started = nil
+ coord.mu.Unlock()
+ require.NoError(b, c.Committed(b.Context(), 1, kv))
+ }
+ b.StopTimer()
+ b.ReportMetric(float64(len(coord.startedEvents())), "started/op")
+ b.ReportMetric(float64(len(store.payloads)), "blobs/op")
+ })
+ }
+ }
+}
+
+// observationSize must equal the real size at every step, and must not be fooled by the cached size of the observation
+// itself, which goes stale as events are appended.
+func TestObservationSize(t *testing.T) {
+ t.Parallel()
+
+ obs := &pb.ConsensusQueueObservation{
+ BlobHandles: [][]byte{make([]byte, 300), make([]byte, 300)},
+ Expiration: randTS(rand.New(rand.NewSource(1))),
+ Capacity: 7,
+ WorkflowCapacities: map[string]uint32{},
+ }
+ rng := rand.New(rand.NewSource(2))
+ for i := range 200 {
+ e := observedEventFor(rng, i)
+ obs.Events = append(obs.Events, e)
+ if i%3 == 0 { // some events add a workflow, with capacities of all varint sizes
+ obs.WorkflowCapacities[e.WorkflowID] = uint32(rng.Int63n(1 << (1 + rng.Intn(31)))) //nolint:gosec // G115: bounded by 2^31
+ }
+ require.Equal(t, proto.MarshalOptions{Deterministic: true}.Size(obs), observationSize(obs), "after %d events", i+1)
+ }
+
+ t.Run("sizing the observation itself with cached sizes would be wrong", func(t *testing.T) {
+ before := proto.Size(obs) // stores obs's size
+ obs.Events = append(obs.Events, observedEventFor(rng, 1000))
+ actual := proto.Size(proto.Clone(obs)) // a fresh message has nothing cached
+ stale := proto.MarshalOptions{UseCachedSize: true}.Size(obs)
+ assert.Equal(t, before, stale, "the cached size of obs is that of before the event was added")
+ assert.NotEqual(t, actual, stale)
+ assert.Equal(t, actual, observationSize(obs), "but the shallow copy is exact")
+ })
+}
+
+// BenchmarkFullStateTransitionOverLimit measures rounds that must prune state to fit: a burst that overflows the
+// observed set, and a full queue that is sent 3000 more events.
+func BenchmarkFullStateTransitionOverLimit(b *testing.B) {
+ const n = 4
+ open := nodeOpts{capacity: 1 << 20, wfCaps: map[string]uint32{}, expiration: 100}
+ none := open
+ none.capacity = 0 // nothing executes, so events pile up in the queue
+ all := packedEvents(b, 12000, 0)
+ for _, e := range all {
+ open.wfCaps[e.event.WorkflowID] = 1 << 20
+ none.wfCaps[e.event.WorkflowID] = 1 << 20
+ }
+ round := func(b *testing.B, o nodeOpts, events []hashedEvent, nodes int) []ocrtypes.AttributedObservation {
+ aos := make([]ocrtypes.AttributedObservation, 0, n)
+ for node := range n {
+ var seen []hashedEvent
+ if node < nodes {
+ seen = events
+ }
+ aos = append(aos, ao(b, node, nodeObs(b, o, seen...)))
+ }
+ return aos
+ }
+
+ run := func(b *testing.B, c *consensusQueuePlugin, seed memKV, aos []ocrtypes.AttributedObservation, metric func(memKV) float64, unit string) {
+ var last memKV
+ b.ResetTimer()
+ for range b.N {
+ b.StopTimer()
+ kv := maps.Clone(seed)
+ b.StartTimer()
+ require.NoError(b, stateTransition(b, c, kv, aos...))
+ last = kv
+ }
+ b.StopTimer()
+ b.ReportMetric(metric(last), unit)
+ }
+
+ b.Run("observed set overflows", func(b *testing.B) {
+ c := newSTPlugin(b)
+ c.limits.MaxKeyValueModifiedKeysPlusValuesBytes = 100 << 10 // room for about 300 of the 1000 observed events
+ aos := round(b, open, all[:1000], 2) // f+1 votes: observed, not queued
+ run(b, c, memKV{}, aos, func(kv memKV) float64 { return float64(len(loadState(b, kv).observedEvents)) }, "kept/op")
+ })
+
+ b.Run("full queue receives 3000 more", func(b *testing.B) {
+ c := newSTPlugin(b)
+ seed := memKV{}
+ for i := range 9 { // fill the queue to just under its value limit
+ require.NoError(b, stateTransition(b, c, seed, round(b, none, all[i*1000:(i+1)*1000], n)...))
+ }
+ queued := func(kv memKV) float64 { return float64(len(loadState(b, kv).queuedEvents)) }
+ b.ReportMetric(queued(seed), "queuedBefore")
+ run(b, c, seed, round(b, none, all[9000:12000], n), queued, "queuedAfter/op")
+ })
+}
+
+// A peer can pad a blob with empty events, to make finding each of its real events by scanning from the start cost a
+// lot: validating 1000 events behind 2M empty ones took over half a second on 16 cores (seconds of CPU). Such a blob
+// has more events than any observation can use, so it is rejected, cheaply.
+func TestValidateObservation_RejectsBlobPaddedWithEmptyEvents(t *testing.T) {
+ t.Parallel()
+
+ blobs := &memBlobs{}
+ c := testPlugin(t, sliceQueue{}, blobs, ocr3_1types.MaxMaxObservationBytes)
+
+ padding := 2 * maxEventsPerBlob
+ var payload []byte
+ for range padding {
+ payload = protowire.AppendTag(payload, coordinatedEventsFieldNumber, protowire.BytesType)
+ payload = protowire.AppendBytes(payload, nil)
+ }
+ obs := &pb.ConsensusQueueObservation{BlobHandles: [][]byte{handleBytes(1)}, Expiration: ts(100), WorkflowCapacities: map[string]uint32{testWF: 1}}
+ for i := range 10 {
+ ce, qe := blobEvent(t, testWF, fmt.Sprintf("evt-%02d", i))
+ qe.Deadline = ts(int64(2000 + i))
+ qe.Blobs = []*pb.CoordinatedEventBlobHandle{{Blob: 0, Element: uint32(padding + i)}}
+ payload = append(payload, marshalEvents(t, ce)...)
+ obs.Events = append(obs.Events, qe)
+ }
+ blobs.store(handleBytes(1), payload)
+ raw, err := proto.Marshal(obs)
+ require.NoError(t, err)
+
+ err = c.ValidateObservation(t.Context(), 1, ocrtypes.AttributedQuery{}, ocrtypes.AttributedObservation{Observation: raw}, memKV{}, blobs)
+ require.ErrorContains(t, err, "more than")
+}
+
+// A node that votes for the same event round after round, with a new blob each time, must not make the stored state
+// grow. Each round adds one blob handle for it, until the event is pruned or promoted, which it need not be.
+func TestStateTransition_RepeatedVotesDoNotGrowState(t *testing.T) {
+ t.Parallel()
+
+ c := newSTPlugin(t) // N=4, F=1: two votes are tracked, and it takes three to promote
+ kv := memKV{}
+ e := mkEvents(t, 1, 2000)
+ vote := func(node int, round int) ocrtypes.AttributedObservation {
+ obs := nodeObs(t, stdNode, e...)
+ obs.BlobHandles[0] = handleBytes(byte(10 + round)) //nolint:gosec // G115: a small test value, and a new blob each round
+ return ao(t, node, obs)
+ }
+ none := func(node int) ocrtypes.AttributedObservation { return ao(t, node, nodeObs(t, stdNode)) }
+
+ require.NoError(t, stateTransition(t, c, kv, vote(0, 0), vote(1, 0), none(2)))
+
+ var sizeAfter10 int
+ for round := 1; round <= 100; round++ {
+ require.NoError(t, stateTransition(t, c, kv, vote(0, round), none(1), none(2)))
+ if round == 10 {
+ sizeAfter10 = kvTotal(kv)
+ }
+ }
+
+ st := loadState(t, kv)
+ require.Contains(t, st.observedEvents, string(e[0].hash), "still waiting for a third vote")
+ assert.Equal(t, []byte{0, 1}, st.observedEvents[string(e[0].hash)].NodeIds)
+ assert.Len(t, st.observedBlobs[string(e[0].hash)], 2, "one blob per voter")
+ assert.Equal(t, blobRef{string(handleBytes(110)), 0}, st.observedBlobs[string(e[0].hash)][0], "node 0's latest")
+ assert.Equal(t, sizeAfter10, kvTotal(kv), "90 more rounds of votes did not add a byte")
+
+ // and when a third node votes, the event is promoted with just those two nodes' blobs and the new one
+ require.NoError(t, stateTransition(t, c, kv, vote(2, 101), none(1), none(0)))
+ cons, handles, err := readConsensusState(kv)
+ require.NoError(t, err)
+ require.Len(t, cons, 1)
+ assert.Len(t, cons[0].Blobs, 3, "a blob for each of the three voters")
+ assert.Len(t, handles, 3)
+}
+
+// gatedBlobs holds back fetches of some blobs until their gate is closed (or the fetch is cancelled).
+type gatedBlobs struct {
+ memBlobs
+ gates map[string]chan struct{} // marshaled handle -> gate
+}
+
+func (g *gatedBlobs) FetchBlob(ctx context.Context, h ocr3_1types.BlobHandle) ([]byte, error) {
+ if gate, ok := g.gates[marshalHandle(h)]; ok {
+ select {
+ case <-gate:
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ }
+ return g.memBlobs.FetchBlob(ctx, h)
+}
+
+// Any one blob of an event will do, so they are tried together: a blob that is slow or unavailable cannot hold up the
+// event, however it sorts, and the attempts that are not needed must not be cancelled, as the fetch of a blob is shared
+// by every event that uses it.
+func TestCommitted_FetchesAnEventsBlobsConcurrently(t *testing.T) {
+ t.Parallel()
+
+ // two blobs with the same two events. X is the first of an event's blobs, and is held back.
+ ceA, qeA := blobEvent(t, testWF, "a")
+ ceB, qeB := blobEvent(t, testWF, "b")
+ payload := marshalEvents(t, ceA, ceB)
+ x, y := handleBytes(1), handleBytes(2)
+ // A has both blobs, X first. B has only X.
+ qeA.Blobs = []*pb.CoordinatedEventBlobHandle{{Blob: 0, Element: 0}, {Blob: 1, Element: 0}}
+ qeB.Blobs = []*pb.CoordinatedEventBlobHandle{{Blob: 0, Element: 1}}
+
+ gate := make(chan struct{})
+ var once sync.Once
+ release := func() { once.Do(func() { close(gate) }) }
+ t.Cleanup(release)
+ blobs := &gatedBlobs{}
+ blobs.store(x, payload)
+ blobs.store(y, payload)
+ var hx ocr3_1types.BlobHandle
+ require.NoError(t, hx.UnmarshalBinary(x))
+ blobs.gates = map[string]chan struct{}{marshalHandle(hx): gate}
+
+ events, err := proto.Marshal(&pb.ConsensusQueueEventList{Events: []*pb.ConsensusQueueEvent{qeA, qeB}})
+ require.NoError(t, err)
+ handles, err := proto.Marshal(&pb.ConsensusQueueBlobHandleList{BlobHandles: [][]byte{x, y}})
+ require.NoError(t, err)
+ kv := memKV{consensusEventsKey: events, blobHandlesKey: handles}
+
+ coord := &recCoordinator{}
+ c := newCommitPlugin(t, coord, &recQueue{}, blobs)
+ committed := make(chan error, 1)
+ go func() { committed <- c.Committed(t.Context(), 1, kv) }()
+
+ // A is started through Y, while X is still held back, and so is not waited for
+ require.Eventually(t, func() bool { return len(coord.startedEvents()) == 1 }, 5*time.Second, 5*time.Millisecond,
+ "an event is not held up by its other, unavailable blob")
+ assert.Equal(t, "a", coord.startedEvents()[0].Event.Event.ID)
+ select {
+ case err := <-committed:
+ t.Fatalf("B can only be read from X, so committing waits for it, but it returned %v (started %d)", err, len(coord.startedEvents()))
+ default:
+ }
+
+ // X was the loser for A, and must not have been cancelled for it: B needs it
+ release()
+ select {
+ case err := <-committed:
+ require.NoError(t, err)
+ case <-time.After(5 * time.Second):
+ t.Fatal("Committed did not finish")
+ }
+ started := coord.startedEvents()
+ require.Len(t, started, 2)
+ ids := []string{started[0].Event.Event.ID, started[1].Event.Event.ID}
+ assert.ElementsMatch(t, []string{"a", "b"}, ids, "B was started from X after it was released")
+}
+
+// removalQueue is a queue that serves events, and records those removed from it.
+type removalQueue struct {
+ sliceQueue
+ mu sync.Mutex
+ removed []string
+}
+
+func (q *removalQueue) Remove(_ context.Context, executionIDs iter.Seq[string]) {
+ q.mu.Lock()
+ defer q.mu.Unlock()
+ q.removed = slices.AppendSeq(q.removed, executionIDs)
+}
+
+func (q *removalQueue) removedIDs() []string {
+ q.mu.Lock()
+ defer q.mu.Unlock()
+ return slices.Clone(q.removed)
+}
+
+// drainSwitch is a KV drain mode that can be flipped while the plugin runs.
+type drainSwitch struct{ on atomic.Bool }
+
+func (d *drainSwitch) check(context.Context, time.Time) (bool, error) { return d.on.Load(), nil }
+
+func TestKVDrainActive(t *testing.T) {
+ t.Parallel()
+ active := func(settingsJSON string, at time.Time) (bool, error) {
+ var getter settings.Getter
+ if settingsJSON != "" {
+ var err error
+ getter, err = settings.NewJSONGetter([]byte(settingsJSON))
+ require.NoError(t, err)
+ }
+ return KVDrainActive(limits.Factory{Logger: logger.Test(t), Settings: getter})(t.Context(), at)
+ }
+ start := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
+ window := fmt.Sprintf(`{"global":{"FeatureConsensusQueueKVDrainActivePeriod":"[%d,%d]"}}`, start.Unix(), start.Add(time.Hour).Unix())
+
+ on, err := active("", start)
+ require.NoError(t, err)
+ assert.False(t, on, "off by default")
+
+ for at, want := range map[time.Time]bool{
+ start.Add(-time.Second): false, start: true, start.Add(time.Hour): true, start.Add(time.Hour + time.Second): false,
+ } {
+ on, err = active(window, at)
+ require.NoError(t, err)
+ assert.Equal(t, want, on, at.String())
+ }
+}
+
+func TestObservation_KVDrain(t *testing.T) {
+ t.Parallel()
+
+ events := mkEvents(t, 3, time.Now().Add(time.Hour).Unix())
+ q := &removalQueue{sliceQueue: sliceQueue{events: events}}
+ blobs := &memBlobs{}
+ c := testPlugin(t, q.sliceQueue, blobs, 1<<19)
+ c.triggerQueue = q
+ drain := &drainSwitch{}
+ c.kvDrain = drain.check
+ kv := memKV{}
+
+ drain.on.Store(true)
+ obs, err := observe(t, c, kv, blobs)
+ require.NoError(t, err)
+ assert.Empty(t, obs.Events, "no new events are reported")
+ assert.Empty(t, obs.BlobHandles, "so none are broadcast")
+ assert.True(t, obs.KvDrainActive, "and the mode is reported, for consensus")
+ assert.NotNil(t, obs.Expiration, "though what consensus needs is still reported")
+ assert.Len(t, q.removedIDs(), 3, "the local queue is emptied")
+ assert.Empty(t, blobs.payloads, "nothing was broadcast")
+
+ // a flip takes effect on the next round
+ drain.on.Store(false)
+ obs, err = observe(t, c, kv, blobs)
+ require.NoError(t, err)
+ assert.Len(t, obs.Events, 3, "events are observed again")
+ assert.False(t, obs.KvDrainActive)
+}
+
+func TestStateTransition_KVDrain(t *testing.T) {
+ t.Parallel()
+
+ c := newSTPlugin(t)
+ kv := memKV{}
+ events := mkEvents(t, 4, 2000)
+ all := func(o nodeOpts, ev ...hashedEvent) []ocrtypes.AttributedObservation {
+ return []ocrtypes.AttributedObservation{ao(t, 0, nodeObs(t, o, ev...)), ao(t, 1, nodeObs(t, o, ev...)), ao(t, 2, nodeObs(t, o, ev...))}
+ }
+
+ // no capacity: all four wait in the queue
+ noCapacity := nodeOpts{capacity: 0, wfCaps: map[string]uint32{testWF: 0}, expiration: 100}
+ require.NoError(t, stateTransition(t, c, kv, all(noCapacity, events...)...))
+ require.Len(t, loadState(t, kv).queuedEvents, 4)
+
+ // drain: still no capacity, and a faulty node still reports new events, but nothing is added and all queued are taken
+ late := mkEvents(t, 2, 3000)
+ for i := range late {
+ _, late[i].event = newCoordinatedEvent(t, testWF, fmt.Sprintf("late-%d", i))
+ late[i].event.Deadline = ts(3000 + int64(i))
+ }
+ draining := noCapacity
+ draining.drain = true
+ require.NoError(t, stateTransition(t, c, kv,
+ ao(t, 0, nodeObs(t, draining)), ao(t, 1, nodeObs(t, draining)), ao(t, 2, nodeObs(t, noCapacity, late...))))
+ state := loadState(t, kv)
+ assert.Empty(t, state.queuedEvents, "every queued event was taken")
+ assert.Empty(t, state.observedEvents, "and nothing new was added")
+ assert.Len(t, consensusIDs(t, kv), 4, "to execute")
+
+ // the next round without the flag adds events again
+ require.NoError(t, stateTransition(t, c, kv, all(noCapacity, late...)...))
+ assert.Len(t, loadState(t, kv).queuedEvents, 2)
+}
+
+// KV drain mode takes the votes of F+1 nodes: at least one honest. N=4, F=1.
+func TestStateTransition_KVDrainNeedsFPlusOneVotes(t *testing.T) {
+ t.Parallel()
+
+ for votes, wantDrain := range map[int]bool{0: false, 1: false, 2: true, 3: true} {
+ t.Run(fmt.Sprintf("%d of 3 vote", votes), func(t *testing.T) {
+ t.Parallel()
+ c := newSTPlugin(t)
+ kv := memKV{}
+ noCapacity := nodeOpts{capacity: 0, wfCaps: map[string]uint32{testWF: 0}, expiration: 100}
+ events := mkEvents(t, 2, 2000)
+ require.NoError(t, stateTransition(t, c, kv,
+ ao(t, 0, nodeObs(t, noCapacity, events...)), ao(t, 1, nodeObs(t, noCapacity, events...)), ao(t, 2, nodeObs(t, noCapacity, events...))))
+ require.Len(t, loadState(t, kv).queuedEvents, 2)
+
+ aos := make([]ocrtypes.AttributedObservation, 0, 3)
+ for i := range 3 {
+ o := noCapacity
+ o.drain = i < votes
+ aos = append(aos, ao(t, i, nodeObs(t, o)))
+ }
+ require.NoError(t, stateTransition(t, c, kv, aos...))
+ if wantDrain {
+ assert.Len(t, consensusIDs(t, kv), 2)
+ } else {
+ assert.Empty(t, consensusIDs(t, kv), "no capacity, so nothing is taken")
+ }
+ })
+ }
+}
+
+func TestStateTransition_KVDrainDropsExpired(t *testing.T) {
+ t.Parallel()
+
+ c := newSTPlugin(t)
+ kv := memKV{}
+ events := mkEvents(t, 3, 2000) // deadlines 2000, 2001, 2002
+ noCapacity := nodeOpts{capacity: 0, wfCaps: map[string]uint32{testWF: 0}, expiration: 100}
+ require.NoError(t, stateTransition(t, c, kv,
+ ao(t, 0, nodeObs(t, noCapacity, events...)), ao(t, 1, nodeObs(t, noCapacity, events...)), ao(t, 2, nodeObs(t, noCapacity, events...))))
+
+ expired := nodeOpts{capacity: 0, wfCaps: map[string]uint32{testWF: 0}, expiration: 2001, drain: true} // only the first has expired
+ require.NoError(t, stateTransition(t, c, kv,
+ ao(t, 0, nodeObs(t, expired)), ao(t, 1, nodeObs(t, expired)), ao(t, 2, nodeObs(t, expired))))
+ assert.Equal(t, []string{execIDOf(t, "evt-01"), execIDOf(t, "evt-02")}, consensusIDs(t, kv), "the expired event is dropped, not taken")
+ assert.Empty(t, loadState(t, kv).queuedEvents)
+}
+
+func TestValidateObservation_KVDrain(t *testing.T) {
+ t.Parallel()
+
+ c := newSTPlugin(t)
+ validate := func(obs *pb.ConsensusQueueObservation) error {
+ return c.ValidateObservation(t.Context(), 1, ocrtypes.AttributedQuery{}, ao(t, 1, obs), memKV{}, &memBlobs{})
+ }
+ drain := nodeOpts{capacity: 3, wfCaps: map[string]uint32{}, expiration: 100, drain: true}
+
+ empty := nodeObs(t, drain)
+ empty.BlobHandles = nil // as the helper always references a shared blob
+ require.NoError(t, validate(empty), "no events and no blob handles")
+
+ withEvents := nodeObs(t, drain, mkEvents(t, 1, 2000)...)
+ require.ErrorContains(t, validate(withEvents), "KV drain mode reports no new events")
+
+ withHandles := nodeObs(t, drain)
+ withHandles.Events = nil
+ withHandles.BlobHandles = [][]byte{handleBytes(1)}
+ assert.ErrorContains(t, validate(withHandles), "KV drain mode reports no new events")
+}
diff --git a/core/services/ocr3_1/plugins/queue/transmitter.go b/core/services/ocr3_1/plugins/queue/transmitter.go
index 4c9b94187c5..4c43d022f08 100644
--- a/core/services/ocr3_1/plugins/queue/transmitter.go
+++ b/core/services/ocr3_1/plugins/queue/transmitter.go
@@ -5,26 +5,20 @@ import (
"github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types"
ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types"
-
- "github.com/smartcontractkit/chainlink-common/pkg/logger"
)
-type contractTransmitter struct {
- lggr logger.Logger
+type noopTransmitter struct {
fromAccount ocrtypes.Account
}
-func NewTransmitter(lggr logger.Logger, fromAccount ocrtypes.Account) ocr3types.ContractTransmitter[[]byte] {
- return &contractTransmitter{
- lggr: lggr,
- fromAccount: fromAccount,
- }
+func NewTransmitter(fromAccount ocrtypes.Account) ocr3types.ContractTransmitter[[]byte] {
+ return &noopTransmitter{fromAccount: fromAccount}
}
-func (c *contractTransmitter) Transmit(ctx context.Context, digest ocrtypes.ConfigDigest, seqNum uint64, rpi ocr3types.ReportWithInfo[[]byte], signatures []ocrtypes.AttributedOnchainSignature) error {
+func (c *noopTransmitter) Transmit(ctx context.Context, digest ocrtypes.ConfigDigest, seqNum uint64, rpi ocr3types.ReportWithInfo[[]byte], signatures []ocrtypes.AttributedOnchainSignature) error {
return nil
}
-func (c *contractTransmitter) FromAccount(ctx context.Context) (ocrtypes.Account, error) {
+func (c *noopTransmitter) FromAccount(ctx context.Context) (ocrtypes.Account, error) {
return c.fromAccount, nil
}
diff --git a/core/services/ocr3_1/plugins/queue/transmitter_test.go b/core/services/ocr3_1/plugins/queue/transmitter_test.go
new file mode 100644
index 00000000000..049accc239b
--- /dev/null
+++ b/core/services/ocr3_1/plugins/queue/transmitter_test.go
@@ -0,0 +1,21 @@
+package queue
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types"
+ ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types"
+)
+
+func TestNoopTransmitter(t *testing.T) {
+ t.Parallel()
+
+ tr := NewTransmitter("account-1")
+ acct, err := tr.FromAccount(t.Context())
+ require.NoError(t, err)
+ assert.Equal(t, ocrtypes.Account("account-1"), acct)
+ require.NoError(t, tr.Transmit(t.Context(), ocrtypes.ConfigDigest{}, 1, ocr3types.ReportWithInfo[[]byte]{}, nil))
+}
diff --git a/core/services/workflows/monitoring/central_trigger_queue_metrics.go b/core/services/workflows/monitoring/central_trigger_queue_metrics.go
index 31d0083bb73..845ee59c6db 100644
--- a/core/services/workflows/monitoring/central_trigger_queue_metrics.go
+++ b/core/services/workflows/monitoring/central_trigger_queue_metrics.go
@@ -14,6 +14,11 @@ import (
// Drop reason values for platform_engine_central_trigger_queue_dropped_events_total (low cardinality).
const (
CentralTriggerQueueDropReasonQueueFull = "queue_full"
+ // CentralTriggerQueueDropReasonOversize is an event too large to ever be observed (it cannot fit in a consensus blob).
+ CentralTriggerQueueDropReasonOversize = "oversize"
+ // CentralTriggerQueueDropReasonExpired is an event past its deadline and the grace period that nothing took from the
+ // queue, swept by the drainer while the consensus queue plugin was consuming.
+ CentralTriggerQueueDropReasonExpired = "expired"
)
// CentralTriggerQueueMetrics are the central trigger queue's instruments. They are separate from
@@ -24,6 +29,7 @@ type CentralTriggerQueueMetrics struct {
drainedEventsCounter metric.Int64Counter
depthGauge metric.Int64Gauge
capacityGauge metric.Int64Gauge
+ eventAgeSeconds metric.Float64Histogram
}
// InitCentralTriggerQueueMetrics registers the central trigger queue instruments on the beholder meter.
@@ -76,6 +82,15 @@ func NewCentralTriggerQueueMetrics(meter metric.Meter) (*CentralTriggerQueueMetr
if err != nil {
return nil, fmt.Errorf("register central trigger queue capacity gauge: %w", err)
}
+
+ qm.eventAgeSeconds, err = meter.Float64Histogram(
+ "platform_engine_central_trigger_queue_event_age_seconds",
+ metric.WithDescription("Time from a trigger event being observed until it left the central trigger queue, as consensus took it"),
+ metric.WithUnit("s"),
+ )
+ if err != nil {
+ return nil, fmt.Errorf("register central trigger queue event age histogram: %w", err)
+ }
return &qm, nil
}
@@ -113,6 +128,11 @@ func (c CentralTriggerQueueMetricLabeler) IncrementDrainedEventsCounter(ctx cont
c.qm.drainedEventsCounter.Add(ctx, int64(n), c.attributes())
}
+// RecordEventAge records how long an event was in the queue, from when it was observed.
+func (c CentralTriggerQueueMetricLabeler) RecordEventAge(ctx context.Context, seconds float64) {
+ c.qm.eventAgeSeconds.Record(ctx, seconds, c.attributes())
+}
+
// RecordDepth records the number of queued events.
func (c CentralTriggerQueueMetricLabeler) RecordDepth(ctx context.Context, depth int) {
c.qm.depthGauge.Record(ctx, int64(depth), c.attributes())
diff --git a/core/services/workflows/monitoring/monitoring.go b/core/services/workflows/monitoring/monitoring.go
index 4e3c041a183..b5e6c4371ab 100644
--- a/core/services/workflows/monitoring/monitoring.go
+++ b/core/services/workflows/monitoring/monitoring.go
@@ -73,6 +73,7 @@ type EngineMetrics struct {
triggerEventEnqueuedCounter metric.Int64Counter
triggerEventShadowedCounter metric.Int64Counter
triggerEventShadowFailedCounter metric.Int64Counter
+ triggerEventShadowSkippedCounter metric.Int64Counter
triggerEventEnqueueDroppedCounter metric.Int64Counter
triggerEventDequeueDroppedCounter metric.Int64Counter
triggerEventDroppedTotal metric.Int64Counter
@@ -406,6 +407,14 @@ func InitMonitoringResourcesWithMeter(meter metric.Meter) (em *EngineMetrics, er
return nil, fmt.Errorf("failed to register trigger event shadow failed counter: %w", err)
}
+ em.triggerEventShadowSkippedCounter, err = meter.Int64Counter(
+ "platform_engine_trigger_event_shadow_skipped_total",
+ metric.WithDescription("Coordinated trigger events chosen by consensus that were not started because shadow mode was on for them"),
+ )
+ if err != nil {
+ return nil, fmt.Errorf("failed to register trigger event shadow skipped counter: %w", err)
+ }
+
em.triggerEventEnqueueDroppedCounter, err = meter.Int64Counter(
"platform_engine_trigger_event_enqueue_dropped_total",
metric.WithDescription("Trigger events dropped because enqueue to the engine's ingress queue failed"),
@@ -569,6 +578,12 @@ func InitMonitoringResourcesWithMeter(meter metric.Meter) (em *EngineMetrics, er
// Must be defined when the beholder client is created
func MetricViews() []sdkmetric.View {
return []sdkmetric.View{
+ sdkmetric.NewView(
+ sdkmetric.Instrument{Name: "platform_engine_central_trigger_queue_event_age_seconds"},
+ sdkmetric.Stream{Aggregation: sdkmetric.AggregationExplicitBucketHistogram{
+ Boundaries: []float64{0.01, 0.1, 0.5, 1, 2, 5, 10, 30, 60, 300, 600},
+ }},
+ ),
sdkmetric.NewView(
sdkmetric.Instrument{Name: "platform_engine_workflow_completed_time_seconds"},
sdkmetric.Stream{Aggregation: sdkmetric.AggregationExplicitBucketHistogram{
@@ -892,6 +907,13 @@ func (c WorkflowsMetricLabeler) IncrementTriggerEventShadowFailedCounter(ctx con
lc.em.triggerEventShadowFailedCounter.Add(ctx, 1, metric.WithAttributes(otelLabels...))
}
+// IncrementTriggerEventShadowSkippedCounter counts one event chosen by consensus that was not started, because shadow
+// mode was on for it. The event still executes from its workflow's own queue.
+func (c WorkflowsMetricLabeler) IncrementTriggerEventShadowSkippedCounter(ctx context.Context) {
+ otelLabels := beholder.OtelAttributes(c.Labels).AsStringAttributes()
+ c.em.triggerEventShadowSkippedCounter.Add(ctx, 1, metric.WithAttributes(otelLabels...))
+}
+
func (c WorkflowsMetricLabeler) IncrementTriggerEventEnqueueDroppedCounter(ctx context.Context) {
otelLabels := beholder.OtelAttributes(c.Labels).AsStringAttributes()
c.em.triggerEventEnqueueDroppedCounter.Add(ctx, 1, metric.WithAttributes(otelLabels...))
diff --git a/core/services/workflows/store/store_memory.go b/core/services/workflows/store/store_memory.go
index 76dba758f18..a3d973d9324 100644
--- a/core/services/workflows/store/store_memory.go
+++ b/core/services/workflows/store/store_memory.go
@@ -50,6 +50,16 @@ type InMemoryStore struct {
// maximumExecutionAge is the maximum age of a non-completed execution before it is
// considered expired and eligible for pruning regardless of its status
maximumExecutionAge time.Duration
+
+ // minimumCompletedRetention, if set, extends completedExecutionRetention when it is longer.
+ minimumCompletedRetention func() time.Duration
+}
+
+// SetMinimumCompletedRetention makes the store keep a completed execution for at least as long as retention returns, if that
+// is longer than the configured retention. This is for callers that can run an event again until it expires, whose
+// duplicate must be caught for as long as that is possible. retention is called on each sweep, and must be set before Start.
+func (s *InMemoryStore) SetMinimumCompletedRetention(retention func() time.Duration) {
+ s.minimumCompletedRetention = retention
}
func NewInMemoryStore(lggr logger.Logger, clock clockwork.Clock) *InMemoryStore {
@@ -210,7 +220,11 @@ func (s *InMemoryStore) pruneExpiredExecutionEntries() {
// See https://100go.co/28-maps-memory-leaks/
func (s *InMemoryStore) pruneCompletedAndExpiredExecutions() {
now := s.clock.Now()
- completedCutoff := now.Add(-s.completedExecutionRetention)
+ retention := s.completedExecutionRetention
+ if s.minimumCompletedRetention != nil {
+ retention = max(retention, s.minimumCompletedRetention())
+ }
+ completedCutoff := now.Add(-retention)
expirationTime := now.Add(-s.maximumExecutionAge)
s.mu.Lock()
diff --git a/core/services/workflows/store/store_memory_test.go b/core/services/workflows/store/store_memory_test.go
index 28154b49cd5..6e7bbb02695 100644
--- a/core/services/workflows/store/store_memory_test.go
+++ b/core/services/workflows/store/store_memory_test.go
@@ -2,6 +2,7 @@ package store
import (
"reflect"
+ "sync/atomic"
"testing"
"time"
@@ -226,3 +227,66 @@ func TestInMemoryStore_PruneRebuildsMapOnlyWhenPruning(t *testing.T) {
assert.Equal(t, mapAfterPrune, reflect.ValueOf(store.idToExecution).Pointer(),
"map should not be rebuilt when nothing is pruned")
}
+
+// A caller that can run an event again until it expires needs completed executions remembered for that long, which the
+// configured retention may not cover. The minimum is read on each sweep, so it follows a lifetime that grows.
+func TestInMemoryStore_MinimumCompletedRetention(t *testing.T) {
+ t.Parallel()
+
+ const configured = 20 * time.Minute
+ isPruned := func(store *InMemoryStore) func() bool {
+ return func() bool { _, err := store.Get(t.Context(), "test-id"); return err != nil }
+ }
+ newStore := func(t *testing.T, retention func() time.Duration) (*InMemoryStore, *clockwork.FakeClock) {
+ fakeClock := clockwork.NewFakeClock()
+ store := NewInMemoryStoreWithPruneConfiguration(logger.TestLogger(t), fakeClock, time.Millisecond, configured, 24*time.Hour)
+ store.SetMinimumCompletedRetention(retention)
+ servicetest.Run(t, store)
+ _, err := store.Add(t.Context(), nil, "test-id", "w1", StatusStarted)
+ require.NoError(t, err)
+ _, err = store.FinishExecution(t.Context(), "test-id", StatusCompleted)
+ require.NoError(t, err)
+ return store, fakeClock
+ }
+
+ for _, tt := range []struct {
+ name string
+ min time.Duration
+ retention time.Duration
+ }{
+ {"a longer minimum extends the retention", time.Hour, time.Hour},
+ {"a shorter minimum has no effect", time.Minute, configured},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ store, fakeClock := newStore(t, func() time.Duration { return tt.min })
+
+ fakeClock.Advance(tt.retention - time.Second)
+ require.Never(t, isPruned(store), 100*time.Millisecond, 10*time.Millisecond)
+ fakeClock.Advance(2 * time.Second)
+ require.Eventually(t, isPruned(store), 10*time.Second, 10*time.Millisecond)
+ })
+ }
+
+ t.Run("follows a minimum that grows after the execution completed", func(t *testing.T) {
+ t.Parallel()
+ var retention atomic.Int64
+ retention.Store(int64(time.Minute))
+ store, fakeClock := newStore(t, func() time.Duration { return time.Duration(retention.Load()) })
+
+ retention.Store(int64(3 * time.Hour)) // a workflow with a long timeout was seen
+ fakeClock.Advance(configured + time.Hour)
+ require.Never(t, isPruned(store), 100*time.Millisecond, 10*time.Millisecond)
+ fakeClock.Advance(2 * time.Hour)
+ require.Eventually(t, isPruned(store), 10*time.Second, 10*time.Millisecond)
+ })
+
+ t.Run("without a minimum the configured retention applies", func(t *testing.T) {
+ t.Parallel()
+ store, fakeClock := newStore(t, nil)
+ fakeClock.Advance(configured - time.Second)
+ require.Never(t, isPruned(store), 100*time.Millisecond, 10*time.Millisecond)
+ fakeClock.Advance(2 * time.Second)
+ require.Eventually(t, isPruned(store), 10*time.Second, 10*time.Millisecond)
+ })
+}
diff --git a/core/services/workflows/v2/base_engine.go b/core/services/workflows/v2/base_engine.go
index e30a929691a..f8de99e109e 100644
--- a/core/services/workflows/v2/base_engine.go
+++ b/core/services/workflows/v2/base_engine.go
@@ -559,25 +559,10 @@ func (e *baseEngine) startExecution(ctx context.Context, event triggers.Coordina
loggerLabels := e.eventLabels()
lggr := e.logger().With(platform.KeyOrganizationID, e.orgID)
- var executionTimestamp time.Time
- var executionDonTimeProvider TimeProvider
- if tsErr := e.cfg.LocalLimiters.ExecutionTimestampsEnabled.AllowErr(ctx); tsErr == nil {
- executionDonTimeProvider = NewDonTimeProvider(e.cfg.DonTimeStore, executionID, e.donTimeRequestTimeout(ctx, e.cfg.LocalLimiters.DONTimeRequestTimeout), lggr, e.metrics, e.cfg.Clock)
- donTime, dtErr := executionDonTimeProvider.GetDONTime()
- if dtErr != nil {
- executionTimestamp = e.cfg.Clock.Now()
- lggr.Warnw("Failed to get DON time for execution timestamp, falling back to local time", "err", dtErr, "executionTimestamp", executionTimestamp)
- e.metrics.IncrementExecutionTimestampFallbackCounter(ctx)
- } else {
- executionTimestamp = donTime
- lggr.Debugw("Execution timestamp assigned", "executionTimestamp", executionTimestamp)
- e.metrics.IncrementExecutionTimestampAssignedCounter(ctx)
- }
- }
-
triggerEvent := event.Event.Event
- // disallow duplicate executions
+ // Disallow duplicate executions. This comes first, before anything with a cost or a side effect (like requesting DON
+ // time), because events are started more than once on purpose by the consensus queue, and the repeats must be cheap.
_, addErr := e.cfg.ExecutionsStore.Add(ctx, nil, executionID, e.cfg.WorkflowID, store.StatusStarted)
if addErr != nil {
if errors.Is(addErr, store.ErrDuplicateExecution) {
@@ -596,6 +581,22 @@ func (e *baseEngine) startExecution(ctx context.Context, event triggers.Coordina
lggr.Errorw("Failed to register execution in store, proceeding anyway", "executionID", executionID, "err", addErr)
}
+ var executionTimestamp time.Time
+ var executionDonTimeProvider TimeProvider
+ if tsErr := e.cfg.LocalLimiters.ExecutionTimestampsEnabled.AllowErr(ctx); tsErr == nil {
+ executionDonTimeProvider = NewDonTimeProvider(e.cfg.DonTimeStore, executionID, e.donTimeRequestTimeout(ctx, e.cfg.LocalLimiters.DONTimeRequestTimeout), lggr, e.metrics, e.cfg.Clock)
+ donTime, dtErr := executionDonTimeProvider.GetDONTime()
+ if dtErr != nil {
+ executionTimestamp = e.cfg.Clock.Now()
+ lggr.Warnw("Failed to get DON time for execution timestamp, falling back to local time", "err", dtErr, "executionTimestamp", executionTimestamp)
+ e.metrics.IncrementExecutionTimestampFallbackCounter(ctx)
+ } else {
+ executionTimestamp = donTime
+ lggr.Debugw("Execution timestamp assigned", "executionTimestamp", executionTimestamp)
+ e.metrics.IncrementExecutionTimestampAssignedCounter(ctx)
+ }
+ }
+
var executionStatus string
defer func() {
if executionStatus == "" {
diff --git a/core/services/workflows/v2/triggers/coordinator.go b/core/services/workflows/v2/triggers/coordinator.go
index 4c21064afc7..f2ac7733ba7 100644
--- a/core/services/workflows/v2/triggers/coordinator.go
+++ b/core/services/workflows/v2/triggers/coordinator.go
@@ -84,6 +84,18 @@ type Coordinator interface {
// Returns ErrCapacityNotSupported if the shared ExecutionConcurrency
// limiter does not break down by scope.
AvailableCapacity(ctx context.Context) (Capacity, error)
+
+ // StartExecution starts execution of the triggered event, and returns without waiting for anything beyond finding the
+ // workflow's engine: not for an execution slot, and not for the execution to finish. In the background it takes an
+ // execution slot like any admitted event, and holds it until the execution finishes, so that AvailableCapacity
+ // reflects it. It returns an error if the workflow is not registered, or its engine is gone or not coordinated.
+ // How the execution itself ends, or that no slot could be taken, is logged and counted.
+ // Starting an event that is already executing is not an error, the engine ignores it, so it is safe to call repeatedly.
+ StartExecution(context.Context, CoordinatedEvent) error
+
+ // WorkflowOrg returns the org of a workflow that is registered with the coordinator, to label metrics with.
+ // ok is false if the workflow is not registered.
+ WorkflowOrg(workflowID string) (orgID string, ok bool)
}
// RegisteredEngine is what EngineRegistry.Get returns: a sink the coordinator
@@ -155,6 +167,12 @@ type coordinator struct {
drainTimeout time.Duration
+ // expirationGrace is how long past its deadline an event may still run. nil means none.
+ expirationGrace func(context.Context) (time.Duration, error)
+
+ // lifetime, if set, learns the timeout of every event.
+ lifetime *EventLifetime
+
// shadow is nil unless WithShadowMode is set.
shadow *shadowMode
// drainer is nil unless WithDrainer is set.
@@ -243,6 +261,69 @@ func NewCoordinator(
// CoordinatorOption configures optional coordinator behaviour.
type CoordinatorOption func(*coordinator)
+// ConsensusQueueExpirationGrace returns how long past its deadline an event is still kept, as configured by
+// ConsensusQueueExpirationGraceInterval. The consensus queue and the coordinator both honor it, so they agree on what has expired.
+// It is node-wide rather than per workflow: each event's deadline already reflects its workflow's timeout, and the grace
+// is slack for clock skew and consensus latency, which the consensus queue applies to every workflow at once.
+func ConsensusQueueExpirationGrace(lf limits.Factory) func(context.Context) (time.Duration, error) {
+ return func(ctx context.Context) (time.Duration, error) {
+ return cresettings.Default.ConsensusQueueExpirationGraceInterval.GetOrDefault(ctx, lf.Settings)
+ }
+}
+
+// EventLifetime tracks how long an event can be held for: the longest timeout that events have been given, plus the
+// grace period. The timeout is a per workflow setting, so there is no fixed maximum, only the longest seen so far.
+// It is for anything that has to remember an event for as long as it can be run, to tell a repeat from a new event.
+type EventLifetime struct {
+ grace func(context.Context) (time.Duration, error)
+
+ mu sync.Mutex
+ longest time.Duration
+}
+
+// NewEventLifetime returns a tracker that starts with the default timeout, and adds the grace period.
+func NewEventLifetime(grace func(context.Context) (time.Duration, error)) *EventLifetime {
+ return &EventLifetime{grace: grace, longest: cresettings.Default.PerWorkflow.TriggerEventQueueTimeout.DefaultValue}
+}
+
+func (l *EventLifetime) observeTimeout(timeout time.Duration) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ l.longest = max(l.longest, timeout)
+}
+
+// Longest returns the longest time an event can be held for, so far. If the grace period cannot be read, the value
+// that was returned with the error is used.
+func (l *EventLifetime) Longest(ctx context.Context) time.Duration {
+ grace, _ := l.grace(ctx)
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return l.longest + max(0, grace)
+}
+
+// WithEventLifetime records the timeout of every event that is given a deadline in lifetime.
+func WithEventLifetime(lifetime *EventLifetime) CoordinatorOption {
+ return func(c *coordinator) { c.lifetime = lifetime }
+}
+
+// WithExpirationGrace lets events run for up to grace past their deadline, instead of dropping them at the deadline.
+// If grace returns an error, its (default) value is still used.
+func WithExpirationGrace(grace func(context.Context) (time.Duration, error)) CoordinatorOption {
+ return func(c *coordinator) { c.expirationGrace = grace }
+}
+
+// expirationGraceDur returns the current grace period, which is zero if unset.
+func (c *coordinator) expirationGraceDur(ctx context.Context, lggr logger.Logger) time.Duration {
+ if c.expirationGrace == nil {
+ return 0
+ }
+ grace, err := c.expirationGrace(ctx)
+ if err != nil {
+ lggr.Warnw("Failed to get expiration grace duration - using default", "grace", grace, "err", err)
+ }
+ return max(0, grace)
+}
+
// WithShadowMode copies each event observed inside activePeriod to queue before the event enters its
// workflow's own queue. The copy is best-effort. A full queue never delays or drops the event.
//
@@ -490,6 +571,63 @@ func (c *coordinator) start(context.Context) error {
return nil
}
+func (c *coordinator) WorkflowOrg(workflowID string) (string, bool) {
+ cw, ok := c.workflows.get(workflowID)
+ if !ok {
+ return "", false
+ }
+ return cw.cre.Org, true
+}
+
+func (c *coordinator) StartExecution(ctx context.Context, event CoordinatedEvent) error {
+ cw, ok := c.workflows.get(event.WorkflowID)
+ if !ok {
+ return fmt.Errorf("workflow %s: not registered", event.WorkflowID)
+ }
+ engine, err := c.lookupEngine(cw.wid)
+ if err != nil {
+ return fmt.Errorf("workflow %s: %w", cw.wid, err)
+ }
+
+ tm := cw.metrics.With(platform.KeyTriggerID, event.TriggerCapID)
+ tm.RecordTriggerEventQueueWaitSeconds(ctx, c.clock.Since(event.ObservedAt).Seconds())
+
+ // In shadow mode the event is only logged. The plugin that calls this still treats it as started, so it is not
+ // started again, while the workflow runs the event from its own queue as usual.
+ if active, err := c.shadowActive(contexts.WithCRE(ctx, cw.cre), event); err != nil {
+ cw.lggr.Warnw("Failed to check shadow trigger mode, starting the event", "triggerID", event.TriggerCapID, "eventID", event.Event.Event.ID, "err", err)
+ } else if active {
+ tm.IncrementTriggerEventShadowSkippedCounter(ctx)
+ cw.lggr.Infow("Shadow mode: not starting the coordinated event", "triggerID", event.TriggerCapID, "eventID", event.Event.Event.ID,
+ "triggerIndex", event.TriggerIndex, "observedAt", event.ObservedAt)
+ return nil
+ }
+
+ // Everything else happens in the background, so that the caller never waits: not for the execution, and not for a
+ // slot either. Events are started more than once on purpose, and the engine ignores the repeats, but only after a
+ // slot has been taken. If the caller waited for it, a repeat would wait behind the slot held by the first run.
+ c.eng.Go(func(ctx context.Context) {
+ // Like the admitter, act for the workflow's tenant, so that the slot is taken from its scopes' pools.
+ ctx = contexts.WithCRE(ctx, cw.cre)
+
+ semWaitStart := c.clock.Now()
+ free, err := c.admission.ExecutionConcurrency.Wait(ctx, 1)
+ tm.RecordExecutionSemaphoreWaitSeconds(ctx, c.clock.Now().Sub(semWaitStart).Seconds())
+ if err != nil {
+ cw.lggr.Errorw("Failed to acquire executions semaphore", "triggerID", event.TriggerCapID, "eventID", event.Event.Event.ID, "err", err)
+ tm.IncrementTriggerEventDroppedTotal(ctx, monitoring.TriggerDropReasonExecutionSemaphoreWaitFailed)
+ return
+ }
+ defer free()
+
+ // WithoutCancel: as for the admitter, stopping must not kill an execution that is already running.
+ err = engine.ExecuteTrigger(context.WithoutCancel(ctx), event)
+ // Starting the same event again is routine here, so a duplicate is not worth more than a debug message.
+ logExecuteResult(cw.lggr, event, err, true)
+ })
+ return nil
+}
+
// close runs after the reader and release goroutines exit.
// It unregisters any triggers still in a pending state before returning.
func (c *coordinator) close() error {
@@ -545,6 +683,9 @@ func (c *coordinator) buildEnqueueFn(cw *coordinatedWorkflow) func(context.Conte
cw.metrics.IncrementLimitReadFallbackCounter(ctx, cresettings.Default.PerWorkflow.TriggerEventQueueTimeout.Key)
}
event.Deadline = event.ObservedAt.Add(queueTimeout)
+ if c.lifetime != nil {
+ c.lifetime.observeTimeout(queueTimeout)
+ }
// Events are copied to the central queue before being put to the workflow queue, so the central queue also
// sees events the engine path later drops.
@@ -568,22 +709,34 @@ func (c *coordinator) buildEnqueueFn(cw *coordinatedWorkflow) func(context.Conte
}
}
+// shadowActive reports whether shadow mode is on for the event: whether the second it was observed in is inside the
+// window. The window is read every time, never cached. Outside the window, or with shadow mode not configured, is
+// not an error. An error is a failed read of the window, which callers treat as off.
+func (c *coordinator) shadowActive(ctx context.Context, event CoordinatedEvent) (bool, error) {
+ if c.shadow == nil {
+ return false, nil
+ }
+ if err := c.shadow.activePeriod.Check(ctx, commonconfig.NewTimestamp(event.ObservedAt)); err != nil {
+ if _, outside := errors.AsType[limits.ErrorRangeLimited[commonconfig.Timestamp]](err); outside {
+ return false, nil
+ }
+ return false, err
+ }
+ return true, nil
+}
+
// putShadow copies event to the central queue when shadow mode is on for it. The window is checked for every
// event and never cached, so a settings change applies to the next event. A read error counts as off. A
// failed copy is never returned, because the event still runs on the engine path. Accepted and failed copies
// are counted on tm, which carries the workflow labels. An event outside the window is not a failure.
func (c *coordinator) putShadow(ctx context.Context, cw *coordinatedWorkflow, tm *monitoring.WorkflowsMetricLabeler, event CoordinatedEvent) {
- if c.shadow == nil {
+ if active, err := c.shadowActive(ctx, event); err != nil {
+ cw.lggr.Warnw("Failed to check shadow trigger mode, not copying the event to the central queue", "err", err)
+ tm.IncrementTriggerEventShadowFailedCounter(ctx, monitoring.ShadowFailReasonWindowCheckFailed)
return
- }
- if err := c.shadow.activePeriod.Check(ctx, commonconfig.NewTimestamp(event.ObservedAt)); err != nil {
- if _, outside := errors.AsType[limits.ErrorRangeLimited[commonconfig.Timestamp]](err); !outside {
- cw.lggr.Warnw("Failed to check shadow trigger mode, not copying the event to the central queue", "err", err)
- tm.IncrementTriggerEventShadowFailedCounter(ctx, monitoring.ShadowFailReasonWindowCheckFailed)
- }
+ } else if !active {
return
}
- // TODO(CRE-6181): stamp SequenceNumber before the put.
if err := c.shadow.queue.Put(ctx, event); err != nil {
cw.lggr.Debugw("Failed to copy trigger event to the central queue", "triggerID", event.TriggerCapID,
"eventID", event.Event.Event.ID, "err", err)
@@ -651,7 +804,7 @@ func (c *coordinator) admit(ctx context.Context, cw *coordinatedWorkflow) {
eventAge := now.Sub(event.ObservedAt)
cw.lggr.Debugw("Popped a trigger event from the queue", "eventID", event.Event.Event.ID, "eventAgeMs", eventAge.Milliseconds())
tm.RecordTriggerEventQueueWaitSeconds(ctx, eventAge.Seconds())
- if now.After(event.Deadline) {
+ if now.After(event.Deadline.Add(c.expirationGraceDur(ctx, cw.lggr))) {
cw.lggr.Warnw("Trigger event is too old, skipping execution", "triggerID", event.TriggerCapID, "eventID", event.Event.Event.ID, "eventAgeMs", eventAge.Milliseconds())
tm.IncrementTriggerEventExpiredCounter(ctx)
tm.IncrementTriggerEventDroppedTotal(ctx, monitoring.TriggerDropReasonExpired)
@@ -683,15 +836,7 @@ func (c *coordinator) admit(ctx context.Context, cw *coordinatedWorkflow) {
defer free()
// WithoutCancel: unregistering stops ingress, it must not kill an execution already running.
err := engine.ExecuteTrigger(context.WithoutCancel(ctx), event)
- switch {
- case err == nil:
- case errors.Is(err, ErrEngineDraining):
- cw.lggr.Infow("Engine is draining, dropping trigger event", "triggerID", event.TriggerCapID, "eventID", event.Event.Event.ID)
- case errors.Is(err, ErrDuplicateExecution), errors.Is(err, ErrEngineClosed):
- cw.lggr.Infow("Skipping trigger event execution", "triggerID", event.TriggerCapID, "eventID", event.Event.Event.ID, "err", err)
- default:
- cw.lggr.Errorw("Failed to execute trigger event", "triggerID", event.TriggerCapID, "eventID", event.Event.Event.ID, "err", err)
- }
+ logExecuteResult(cw.lggr, event, err, false)
})
}
}
@@ -700,19 +845,52 @@ func (c *coordinator) admit(ctx context.Context, cw *coordinatedWorkflow) {
// instead of caching it, since the engine for a workflow can change while the
// registration is running. It reports false, after logging why and counting
// the drop, if there is no engine to deliver to.
-func (c *coordinator) coordinatedEngine(ctx context.Context, cw *coordinatedWorkflow, tm *monitoring.WorkflowsMetricLabeler, event CoordinatedEvent) (RegisteredEngine, bool) {
- engine, found := c.engines.Get(cw.wid)
+var (
+ errEngineGone = errors.New("engine not found")
+ errEngineNotCoordinated = errors.New("engine not coordinated")
+)
+
+// lookupEngine returns the workflow's engine, if it exists and is coordinated.
+func (c *coordinator) lookupEngine(wid types.WorkflowID) (RegisteredEngine, error) {
+ engine, found := c.engines.Get(wid)
if !found {
- cw.lggr.Infow("Engine gone, dropping trigger event", "triggerID", event.TriggerCapID, "eventID", event.Event.Event.ID)
- tm.IncrementTriggerEventDroppedTotal(ctx, monitoring.TriggerDropReasonEngineGone)
- return nil, false
+ return nil, errEngineGone
}
if !engine.IsCoordinated() {
+ return nil, errEngineNotCoordinated
+ }
+ return engine, nil
+}
+
+func (c *coordinator) coordinatedEngine(ctx context.Context, cw *coordinatedWorkflow, tm *monitoring.WorkflowsMetricLabeler, event CoordinatedEvent) (RegisteredEngine, bool) {
+ engine, err := c.lookupEngine(cw.wid)
+ switch {
+ case err == nil:
+ return engine, true
+ case errors.Is(err, errEngineGone):
+ cw.lggr.Infow("Engine gone, dropping trigger event", "triggerID", event.TriggerCapID, "eventID", event.Event.Event.ID)
+ tm.IncrementTriggerEventDroppedTotal(ctx, monitoring.TriggerDropReasonEngineGone)
+ default:
cw.lggr.Errorw("Engine is not coordinated, dropping trigger event", "triggerID", event.TriggerCapID, "eventID", event.Event.Event.ID)
tm.IncrementTriggerEventDroppedTotal(ctx, monitoring.TriggerDropReasonEngineNotCoordinated)
- return nil, false
}
- return engine, true
+ return nil, false
+}
+
+// logExecuteResult logs how an execution ended, at a level that suits it. routineDuplicates is for callers that start an
+// event more than once on purpose, for which a duplicate is not worth more than a debug message.
+func logExecuteResult(lggr logger.Logger, event CoordinatedEvent, err error, routineDuplicates bool) {
+ switch {
+ case err == nil:
+ case errors.Is(err, ErrEngineDraining):
+ lggr.Infow("Engine is draining, dropping trigger event", "triggerID", event.TriggerCapID, "eventID", event.Event.Event.ID)
+ case errors.Is(err, ErrDuplicateExecution) && routineDuplicates:
+ lggr.Debugw("Trigger event is already executing", "triggerID", event.TriggerCapID, "eventID", event.Event.Event.ID)
+ case errors.Is(err, ErrDuplicateExecution), errors.Is(err, ErrEngineClosed):
+ lggr.Infow("Skipping trigger event execution", "triggerID", event.TriggerCapID, "eventID", event.Event.Event.ID, "err", err)
+ default:
+ lggr.Errorw("Failed to execute trigger event", "triggerID", event.TriggerCapID, "eventID", event.Event.Event.ID, "err", err)
+ }
}
// dropDeniedEvent handles an event the engine's admission check rejected with err. The event will never execute, so
diff --git a/core/services/workflows/v2/triggers/coordinator_helpers_test.go b/core/services/workflows/v2/triggers/coordinator_helpers_test.go
index ee13e980ee2..3af6c70f91b 100644
--- a/core/services/workflows/v2/triggers/coordinator_helpers_test.go
+++ b/core/services/workflows/v2/triggers/coordinator_helpers_test.go
@@ -494,3 +494,24 @@ func (m *mutableTimeoutLimiter) set(v time.Duration) {
defer m.mu.Unlock()
m.value = v
}
+
+// histogramSum returns the number of recorded values, and their sum, of a float64 histogram.
+func histogramSum(t *testing.T, reader *sdkmetric.ManualReader, name string) (count uint64, sum float64) {
+ t.Helper()
+ var rm metricdata.ResourceMetrics
+ require.NoError(t, reader.Collect(t.Context(), &rm))
+ for _, sm := range rm.ScopeMetrics {
+ for _, m := range sm.Metrics {
+ if m.Name != name {
+ continue
+ }
+ hist, ok := m.Data.(metricdata.Histogram[float64])
+ require.True(t, ok, "expected Histogram[float64] for %s, got %T", name, m.Data)
+ for _, dp := range hist.DataPoints {
+ count += dp.Count
+ sum += dp.Sum
+ }
+ }
+ }
+ return count, sum
+}
diff --git a/core/services/workflows/v2/triggers/coordinator_shadow_test.go b/core/services/workflows/v2/triggers/coordinator_shadow_test.go
index a05d1c804c7..aae934f035e 100644
--- a/core/services/workflows/v2/triggers/coordinator_shadow_test.go
+++ b/core/services/workflows/v2/triggers/coordinator_shadow_test.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
+ "iter"
"strings"
"sync"
"sync/atomic"
@@ -16,6 +17,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/smartcontractkit/chainlink-common/pkg/capabilities"
+ "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb"
commonconfig "github.com/smartcontractkit/chainlink-common/pkg/config"
"github.com/smartcontractkit/chainlink-common/pkg/contexts"
"github.com/smartcontractkit/chainlink-common/pkg/logger"
@@ -333,6 +335,12 @@ type failingQueue struct {
puts atomic.Int32
}
+func (q *failingQueue) Sorted(context.Context, int, int) iter.Seq2[[]byte, *pb.CoordinatedEvent] {
+ return func(yield func([]byte, *pb.CoordinatedEvent) bool) {}
+}
+
+func (q *failingQueue) Remove(ctx context.Context, execIDs iter.Seq[string]) {}
+
func (q *failingQueue) Put(context.Context, CoordinatedEvent) error {
q.puts.Add(1)
return errors.New("boom")
@@ -470,3 +478,28 @@ func TestCoordinator_DrainerLifecycle(t *testing.T) {
return err != nil || stats.Len != 1
}, 100*time.Millisecond, 5*time.Millisecond, "an event put after close was drained")
}
+
+// TestCoordinator_StartExecutionInShadowMode asserts an event chosen by consensus is not started while shadow mode
+// is on for it, though the caller is told it was, so the event is not offered again. Outside the window it starts.
+func TestCoordinator_StartExecutionInShadowMode(t *testing.T) {
+ t.Parallel()
+ q := newTestCentralQueue(t, &fakeLimit{limit: 10})
+ shadow := newShadowMode(t, globalWindow(shadowStart.Add(time.Minute), shadowStart.Add(2*time.Minute)))
+ wfMetrics, reader := newTestMeterMetrics(t)
+ f := newCoordinatorFixture(t, withClock(clockwork.NewFakeClockAt(shadowStart)), withMetrics(wfMetrics),
+ withCoordinatorOptions(WithShadowMode(q, shadow)))
+ registerWorkflow(t, f, newTestSubscriber())
+
+ event := func(id string, observed time.Time) CoordinatedEvent {
+ return CoordinatedEvent{
+ WorkflowID: validWorkflowID, TriggerCapID: testTriggerCapID, ObservedAt: observed, Deadline: observed.Add(time.Hour),
+ Event: capabilities.TriggerResponse{Event: capabilities.TriggerEvent{ID: id}},
+ }
+ }
+
+ require.NoError(t, f.c.StartExecution(t.Context(), event("shadowed", shadowStart.Add(90*time.Second))))
+ require.NoError(t, f.c.StartExecution(t.Context(), event("outside", shadowStart)))
+ require.Eventually(t, func() bool { return len(f.engine.executed()) == 1 }, 5*time.Second, 5*time.Millisecond)
+ assert.Equal(t, []string{"outside"}, f.engine.executedIDs(), "the shadowed event is logged, not started")
+ assert.Equal(t, int64(1), counterTotal(t, reader, "platform_engine_trigger_event_shadow_skipped_total", nil), "and counted")
+}
diff --git a/core/services/workflows/v2/triggers/coordinator_test.go b/core/services/workflows/v2/triggers/coordinator_test.go
index 4ddaeb197fd..7b56943d359 100644
--- a/core/services/workflows/v2/triggers/coordinator_test.go
+++ b/core/services/workflows/v2/triggers/coordinator_test.go
@@ -5,6 +5,8 @@ import (
"errors"
"fmt"
"maps"
+ "sync"
+ "sync/atomic"
"testing"
"time"
@@ -922,6 +924,56 @@ func TestCoordinator_Admission(t *testing.T) {
assert.Equal(t, []string{"evt-1", "evt-2"}, f.engine.executedIDs(), "evt-3 must never reach ExecuteTrigger")
})
+ t.Run("an event past its deadline but within the grace period still executes; past the grace it is dropped", func(t *testing.T) {
+ t.Parallel()
+ for _, tt := range []struct {
+ name string
+ grace func(context.Context) (time.Duration, error)
+ advance time.Duration
+ wantExecuted []string
+ wantExpired int64
+ }{
+ {"within grace", func(context.Context) (time.Duration, error) { return 5 * time.Minute, nil }, 2 * time.Minute, []string{"evt-1", "evt-2", "evt-3"}, 0},
+ {"past grace", func(context.Context) (time.Duration, error) { return time.Minute, nil }, 3 * time.Minute, []string{"evt-1", "evt-2"}, 1},
+ {"grace read error still uses the returned default", func(context.Context) (time.Duration, error) { return 5 * time.Minute, errors.New("boom") }, 2 * time.Minute, []string{"evt-1", "evt-2", "evt-3"}, 0},
+ {"negative grace is treated as none", func(context.Context) (time.Duration, error) { return -time.Hour, nil }, 2 * time.Minute, []string{"evt-1", "evt-2"}, 1},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ admission, pool := singleSlot(func(a *AdmissionLimiters) {
+ a.TriggerEventQueueTimeout = limits.NewUpperBoundLimiter(time.Minute)
+ })
+ wfMetrics, reader := newTestMeterMetrics(t)
+ f := newCoordinatorFixture(t, withAdmission(admission), withMetrics(wfMetrics), withCoordinatorOptions(WithExpirationGrace(tt.grace)))
+ trigger, eventCh := f.expectTrigger(t)
+ trigger.EXPECT().UnregisterTrigger(mock.Anything, mock.Anything).Return(nil).Maybe()
+ release := f.holdExecutions(t)
+ _, err := f.c.RegisterTriggers(t.Context(), newTestSubscriber(), testParams(t))
+ require.NoError(t, err)
+
+ eventCh <- triggerEvent("evt-1")
+ require.Eventually(t, func() bool { return len(f.engine.executed()) == 1 }, 5*time.Second, 5*time.Millisecond)
+ eventCh <- triggerEvent("evt-2")
+ require.Eventually(t, func() bool { return pool.waits.Load() == 2 }, 5*time.Second, 5*time.Millisecond)
+ eventCh <- triggerEvent("evt-3")
+ require.Eventually(t, func() bool { return queueLen(t, f) == 1 }, 5*time.Second, 5*time.Millisecond)
+
+ f.clock.Advance(tt.advance) // evt-3's 1-minute deadline passes while it is queued
+ release()
+
+ if tt.wantExpired == 0 {
+ require.Eventually(t, func() bool { return len(f.engine.executed()) == len(tt.wantExecuted) }, 5*time.Second, 5*time.Millisecond)
+ } else {
+ expired := map[string]string{platform.KeyTriggerDropReason: monitoring.TriggerDropReasonExpired}
+ require.Eventually(t, func() bool {
+ return counterTotal(t, reader, "platform_engine_trigger_event_dropped_total", expired) == tt.wantExpired
+ }, 5*time.Second, 5*time.Millisecond)
+ }
+ assert.Equal(t, tt.wantExecuted, f.engine.executedIDs())
+ })
+ }
+ })
+
t.Run("the deadline is stamped at dispatch, so a later timeout change does not move it", func(t *testing.T) {
t.Parallel()
timeout := &mutableTimeoutLimiter{value: time.Minute}
@@ -1183,3 +1235,269 @@ func TestCoordinator_DeliveryLogs(t *testing.T) {
})
}
}
+
+func TestCoordinator_StartExecution(t *testing.T) {
+ t.Parallel()
+
+ // register returns a fixture with the workflow's triggers registered, as StartExecution requires.
+ register := func(t *testing.T, opts ...fixtureOption) *coordinatorFixture {
+ t.Helper()
+ f := newCoordinatorFixture(t, opts...)
+ trigger, _ := f.expectTrigger(t)
+ trigger.EXPECT().UnregisterTrigger(mock.Anything, mock.Anything).Return(nil).Maybe()
+ _, err := f.c.RegisterTriggers(t.Context(), newTestSubscriber(), testParams(t))
+ require.NoError(t, err)
+ return f
+ }
+ oneSlot := func() (AdmissionLimiters, *countingPool) {
+ pool := &countingPool{ResourcePoolLimiter: limits.GlobalResourcePoolLimiter(1)}
+ admission := newTestAdmission()
+ admission.ExecutionConcurrency = pool
+ return admission, pool
+ }
+ newEvent := func(f *coordinatorFixture, id string, age time.Duration) CoordinatedEvent {
+ return CoordinatedEvent{
+ WorkflowID: validWorkflowID, TriggerCapID: testTriggerCapID,
+ ObservedAt: f.clock.Now().Add(-age), Deadline: f.clock.Now().Add(time.Minute),
+ Event: capabilities.TriggerResponse{Event: capabilities.TriggerEvent{ID: id}},
+ }
+ }
+ executed := func(f *coordinatorFixture, n int) func() bool {
+ return func() bool { return len(f.engine.executed()) == n }
+ }
+
+ t.Run("starts the event for the workflow's tenant, and records how long it was queued", func(t *testing.T) {
+ t.Parallel()
+ wfMetrics, reader := newTestMeterMetrics(t)
+ f := register(t, withMetrics(wfMetrics))
+
+ require.NoError(t, f.c.StartExecution(t.Context(), newEvent(f, "evt-1", 5*time.Second)))
+ require.Eventually(t, executed(f, 1), 5*time.Second, 5*time.Millisecond)
+
+ assert.Equal(t, []string{"evt-1"}, f.engine.executedIDs())
+ f.engine.mu.Lock()
+ assert.Equal(t, validWorkflowID, f.engine.tenants[0].Workflow, "the execution runs as the workflow's tenant, as an admitted one does")
+ f.engine.mu.Unlock()
+ count, sum := histogramSum(t, reader, "platform_engine_trigger_event_queue_wait_seconds")
+ assert.Equal(t, uint64(1), count)
+ assert.InDelta(t, 5.0, sum, 0.001, "measured against the coordinator's clock")
+ })
+
+ t.Run("returns once the execution has started, not when it finishes", func(t *testing.T) {
+ t.Parallel()
+ f := register(t)
+ release := f.holdExecutions(t)
+
+ done := make(chan error, 1)
+ go func() { done <- f.c.StartExecution(t.Context(), newEvent(f, "evt-1", 0)) }()
+ select {
+ case err := <-done:
+ require.NoError(t, err)
+ case <-time.After(5 * time.Second):
+ t.Fatal("StartExecution waited for the execution to finish")
+ }
+ require.Eventually(t, executed(f, 1), 5*time.Second, 5*time.Millisecond, "and the execution is running")
+ release()
+ })
+
+ t.Run("holds an execution slot until the execution finishes, without making the caller wait for one", func(t *testing.T) {
+ t.Parallel()
+ admission, pool := oneSlot()
+ f := register(t, withAdmission(admission))
+ release := f.holdExecutions(t)
+
+ require.NoError(t, f.c.StartExecution(t.Context(), newEvent(f, "evt-1", 0)))
+ require.Eventually(t, executed(f, 1), 5*time.Second, 5*time.Millisecond)
+
+ // the second has to wait for the slot, which capacity reflects, but the caller does not
+ second := make(chan error, 1)
+ go func() { second <- f.c.StartExecution(t.Context(), newEvent(f, "evt-2", 0)) }()
+ select {
+ case err := <-second:
+ require.NoError(t, err)
+ case <-time.After(5 * time.Second):
+ t.Fatal("StartExecution waited for a slot")
+ }
+ require.Eventually(t, func() bool { return pool.waits.Load() == 2 }, 5*time.Second, 5*time.Millisecond, "waiting for the slot")
+ assert.Len(t, f.engine.executed(), 1, "not started without a slot")
+
+ release()
+ require.Eventually(t, executed(f, 2), 5*time.Second, 5*time.Millisecond, "starts once the slot is free")
+ })
+
+ t.Run("a repeat of a running event does not make the caller wait behind its slot", func(t *testing.T) {
+ t.Parallel()
+ admission, _ := oneSlot()
+ f := register(t, withAdmission(admission))
+ release := f.holdExecutions(t)
+
+ for range 3 { // as when a set is started by Committed, and again by the next Observation
+ done := make(chan error, 1)
+ go func() { done <- f.c.StartExecution(t.Context(), newEvent(f, "evt-1", 0)) }()
+ select {
+ case err := <-done:
+ require.NoError(t, err)
+ case <-time.After(5 * time.Second):
+ t.Fatal("a repeat start waited behind the running execution's slot")
+ }
+ }
+ require.Eventually(t, executed(f, 1), 5*time.Second, 5*time.Millisecond)
+ release()
+ })
+
+ t.Run("a slot that cannot be taken drops the event and counts it", func(t *testing.T) {
+ t.Parallel()
+ admission, _ := oneSlot()
+ admission.ExecutionConcurrency = failingWaitPool{admission.ExecutionConcurrency}
+ wfMetrics, reader := newTestMeterMetrics(t)
+ f := register(t, withAdmission(admission), withMetrics(wfMetrics))
+
+ require.NoError(t, f.c.StartExecution(t.Context(), newEvent(f, "evt-1", 0)))
+ reason := map[string]string{platform.KeyTriggerDropReason: monitoring.TriggerDropReasonExecutionSemaphoreWaitFailed}
+ require.Eventually(t, func() bool {
+ return counterTotal(t, reader, "platform_engine_trigger_event_dropped_total", reason) == 1
+ }, 5*time.Second, 5*time.Millisecond)
+ assert.Empty(t, f.engine.executed())
+ })
+
+ t.Run("starting an event that is already executing is not an error", func(t *testing.T) {
+ t.Parallel()
+ f := register(t)
+ f.engine.err = ErrDuplicateExecution
+
+ require.NoError(t, f.c.StartExecution(t.Context(), newEvent(f, "evt-1", 0)))
+ require.Eventually(t, executed(f, 1), 5*time.Second, 5*time.Millisecond)
+ })
+
+ t.Run("the slot is released when the execution fails", func(t *testing.T) {
+ t.Parallel()
+ admission, pool := oneSlot()
+ f := register(t, withAdmission(admission))
+ f.engine.err = errors.New("boom")
+
+ for i := range 3 { // would block forever on the second if the slot leaked
+ require.NoError(t, f.c.StartExecution(t.Context(), newEvent(f, fmt.Sprint("evt-", i), 0)))
+ }
+ require.Eventually(t, executed(f, 3), 5*time.Second, 5*time.Millisecond)
+ assert.Equal(t, int32(3), pool.waits.Load())
+ })
+
+ t.Run("workflows that cannot run the event are errors", func(t *testing.T) {
+ t.Parallel()
+ unregistered := newCoordinatorFixture(t)
+ require.ErrorContains(t, unregistered.c.StartExecution(t.Context(), newEvent(unregistered, "evt-1", 0)), "not registered")
+ assert.Empty(t, unregistered.engine.executed())
+
+ notCoordinated := register(t)
+ notCoordinated.engine.coordinated = false
+ require.ErrorIs(t, notCoordinated.c.StartExecution(t.Context(), newEvent(notCoordinated, "evt-1", 0)), errEngineNotCoordinated)
+
+ invalid := register(t)
+ event := newEvent(invalid, "evt-1", 0)
+ event.WorkflowID = "not-hex"
+ require.Error(t, invalid.c.StartExecution(t.Context(), event))
+ assert.Empty(t, invalid.engine.executed())
+ })
+}
+
+// failingWaitPool cannot give out slots.
+type failingWaitPool struct {
+ limits.ResourcePoolLimiter[int]
+}
+
+func (failingWaitPool) Wait(context.Context, int) (func(), error) { return nil, errors.New("no slots") }
+
+func TestEventLifetime(t *testing.T) {
+ t.Parallel()
+
+ defaultTimeout := cresettings.Default.PerWorkflow.TriggerEventQueueTimeout.DefaultValue
+ graceOf := func(d time.Duration, err error) func(context.Context) (time.Duration, error) {
+ return func(context.Context) (time.Duration, error) { return d, err }
+ }
+
+ t.Run("starts at the default timeout plus the grace", func(t *testing.T) {
+ t.Parallel()
+ l := NewEventLifetime(graceOf(time.Minute, nil))
+ assert.Equal(t, defaultTimeout+time.Minute, l.Longest(t.Context()))
+ })
+
+ t.Run("follows the longest timeout seen, and never shrinks", func(t *testing.T) {
+ t.Parallel()
+ l := NewEventLifetime(graceOf(time.Minute, nil))
+ l.observeTimeout(time.Second)
+ assert.Equal(t, defaultTimeout+time.Minute, l.Longest(t.Context()), "a shorter timeout changes nothing")
+ l.observeTimeout(2 * time.Hour)
+ assert.Equal(t, 2*time.Hour+time.Minute, l.Longest(t.Context()))
+ l.observeTimeout(time.Hour)
+ assert.Equal(t, 2*time.Hour+time.Minute, l.Longest(t.Context()), "the longest is kept")
+ })
+
+ t.Run("reads the grace each time, so a change applies", func(t *testing.T) {
+ t.Parallel()
+ var grace atomic.Int64
+ grace.Store(int64(time.Minute))
+ l := NewEventLifetime(func(context.Context) (time.Duration, error) { return time.Duration(grace.Load()), nil })
+ grace.Store(int64(5 * time.Minute))
+ assert.Equal(t, defaultTimeout+5*time.Minute, l.Longest(t.Context()))
+ })
+
+ t.Run("a grace read error still uses the value returned with it, and a negative grace is none", func(t *testing.T) {
+ t.Parallel()
+ assert.Equal(t, defaultTimeout+30*time.Second, NewEventLifetime(graceOf(30*time.Second, errors.New("boom"))).Longest(t.Context()))
+ assert.Equal(t, defaultTimeout, NewEventLifetime(graceOf(-time.Hour, nil)).Longest(t.Context()))
+ })
+
+ t.Run("is safe for concurrent use", func(t *testing.T) {
+ t.Parallel()
+ l := NewEventLifetime(graceOf(0, nil))
+ var wg sync.WaitGroup
+ for i := range 50 {
+ wg.Go(func() {
+ l.observeTimeout(time.Duration(i) * time.Hour)
+ l.Longest(t.Context())
+ })
+ }
+ wg.Wait()
+ assert.Equal(t, 49*time.Hour, l.Longest(t.Context()))
+ })
+}
+
+// The coordinator stamps each event's deadline from its workflow's timeout, which is where the longest one is learned.
+func TestCoordinator_LearnsEventLifetime(t *testing.T) {
+ t.Parallel()
+
+ lifetime := NewEventLifetime(func(context.Context) (time.Duration, error) { return time.Minute, nil })
+ admission := newTestAdmission()
+ admission.TriggerEventQueueTimeout = limits.NewUpperBoundLimiter(3 * time.Hour)
+ f := newCoordinatorFixture(t, withAdmission(admission), withCoordinatorOptions(WithEventLifetime(lifetime)))
+ trigger, eventCh := f.expectTrigger(t)
+ trigger.EXPECT().UnregisterTrigger(mock.Anything, mock.Anything).Return(nil).Maybe()
+ _, err := f.c.RegisterTriggers(t.Context(), newTestSubscriber(), testParams(t))
+ require.NoError(t, err)
+
+ require.Equal(t, cresettings.Default.PerWorkflow.TriggerEventQueueTimeout.DefaultValue+time.Minute, lifetime.Longest(t.Context()))
+ eventCh <- triggerEvent("evt-1")
+ require.Eventually(t, func() bool { return len(f.engine.executed()) == 1 }, 5*time.Second, 5*time.Millisecond)
+
+ assert.Equal(t, 3*time.Hour+time.Minute, lifetime.Longest(t.Context()), "the workflow's 3h timeout, plus the grace")
+}
+
+func TestCoordinator_WorkflowOrg(t *testing.T) {
+ t.Parallel()
+
+ f := newCoordinatorFixture(t)
+ _, ok := f.c.WorkflowOrg(validWorkflowID)
+ assert.False(t, ok, "not registered yet")
+
+ trigger, _ := f.expectTrigger(t)
+ trigger.EXPECT().UnregisterTrigger(mock.Anything, mock.Anything).Return(nil).Maybe()
+ _, err := f.c.RegisterTriggers(t.Context(), newTestSubscriber(), testParams(t))
+ require.NoError(t, err)
+
+ org, ok := f.c.WorkflowOrg(validWorkflowID)
+ require.True(t, ok)
+ assert.Equal(t, testOrg, org)
+
+ _, ok = f.c.WorkflowOrg("some-other-workflow")
+ assert.False(t, ok)
+}
diff --git a/core/services/workflows/v2/triggers/drainer.go b/core/services/workflows/v2/triggers/drainer.go
index 21f13e1e0f7..6612c24cd9e 100644
--- a/core/services/workflows/v2/triggers/drainer.go
+++ b/core/services/workflows/v2/triggers/drainer.go
@@ -53,6 +53,10 @@ type drainer struct {
clock clockwork.Clock
hooks drainerHooks
+ // consumed and grace are set only for the central queue's drainer. See NewCentralQueueDrainer.
+ consumed ConsumedQueue
+ grace func(context.Context) (time.Duration, error)
+
// observed batches awaiting OnObservedEvents
batches chan []CoordinatedEvent
metrics *monitoring.TriggerDrainerMetricLabeler
@@ -80,14 +84,40 @@ func NewDrainer(queue Queue, interval limits.BoundLimiter[time.Duration], hooks
return d
}
+// ConsumedQueue is a Queue that reports when it was last read by a consumer other than the drainer, and can drop
+// the events that are past their deadline.
+type ConsumedQueue interface {
+ Queue
+ // LastConsumed is when the queue was last read for consensus, or the zero time if never.
+ LastConsumed() time.Time
+ // DropExpired removes the events with a deadline before cutoff, and returns how many.
+ DropExpired(ctx context.Context, cutoff time.Time) int
+}
+
+// minConsumerWindow is the least time since the queue was last consumed for a consumer to count as active.
+const minConsumerWindow = 30 * time.Second
+
+// consumerWindow is how recently the queue must have been read for a consumer to count as active: three drain
+// intervals, so that a missed round does not hand the events to the drainer, and at least minConsumerWindow.
+func consumerWindow(interval time.Duration) time.Duration {
+ return max(minConsumerWindow, 3*interval)
+}
+
// NewCentralQueueDrainer returns the temporary drainer of the central queue. Drained events are discarded after
// one debug line per workflow per batch, which lets smoke tests see that shadow mode reached the queue.
-func NewCentralQueueDrainer(queue Queue, interval limits.BoundLimiter[time.Duration], metrics *monitoring.TriggerDrainerMetricLabeler, clock clockwork.Clock, lggr logger.Logger) *drainer {
+//
+// While something else is consuming the queue (the consensus queue plugin reads it every round), the drainer leaves
+// the events alone, as draining them would race the consumer for each event. It then only drops those past their
+// deadline plus the grace period, which the consumer would never take. When the consumer goes quiet, it drains
+// everything again.
+func NewCentralQueueDrainer(queue ConsumedQueue, grace func(context.Context) (time.Duration, error), interval limits.BoundLimiter[time.Duration], metrics *monitoring.TriggerDrainerMetricLabeler, clock clockwork.Clock, lggr logger.Logger) *drainer {
hookLggr := logger.Named(lggr, "TriggerQueueDrainer")
hooks := drainerHooks{OnObservedEvents: func(_ context.Context, events []CoordinatedEvent) {
logDrainedEvents(hookLggr, events)
}}
- return NewDrainer(queue, interval, hooks, metrics, clock, lggr)
+ d := NewDrainer(queue, interval, hooks, metrics, clock, lggr)
+ d.consumed, d.grace = queue, grace
+ return d
}
// start launches the hook worker and the drain loop. Both run until the
@@ -143,6 +173,10 @@ func (d *drainer) runHooks(ctx context.Context) {
// worker without blocking. A Drain error is logged and does not stop the
// loop. The hook is not called for an empty batch.
func (d *drainer) drain(ctx context.Context) {
+ if d.consumerActive(ctx) {
+ d.dropExpired(ctx)
+ return
+ }
events, err := d.queue.Drain(ctx)
if err != nil {
d.lggr.Errorw("Failed to observe trigger queue", "err", err)
@@ -161,6 +195,26 @@ func (d *drainer) drain(ctx context.Context) {
}
}
+// consumerActive reports whether something else has read the queue recently enough to be taking its events.
+func (d *drainer) consumerActive(ctx context.Context) bool {
+ if d.consumed == nil {
+ return false
+ }
+ last := d.consumed.LastConsumed()
+ return !last.IsZero() && d.clock.Since(last) <= consumerWindow(d.nextInterval(ctx))
+}
+
+// dropExpired drops the events that are past their deadline and the grace period.
+func (d *drainer) dropExpired(ctx context.Context) {
+ grace, err := d.grace(ctx)
+ if err != nil {
+ d.lggr.Warnw("Failed to read the expiration grace period, using the default", "grace", grace, "err", err)
+ }
+ if n := d.consumed.DropExpired(ctx, d.clock.Now().Add(-max(0, grace))); n > 0 {
+ d.lggr.Debugw("Dropped expired trigger events nothing took", "count", n)
+ }
+}
+
// logDrainedEvents logs how many events each workflow had in one drained batch.
func logDrainedEvents(lggr logger.Logger, events []CoordinatedEvent) {
counts := map[string]int{}
diff --git a/core/services/workflows/v2/triggers/drainer_test.go b/core/services/workflows/v2/triggers/drainer_test.go
index c499af946b7..9784dfc3ec3 100644
--- a/core/services/workflows/v2/triggers/drainer_test.go
+++ b/core/services/workflows/v2/triggers/drainer_test.go
@@ -2,7 +2,10 @@ package triggers
import (
"context"
+ "crypto/sha256"
"errors"
+ "iter"
+ "slices"
"sync"
"sync/atomic"
"testing"
@@ -17,9 +20,11 @@ import (
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
+ "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb"
"github.com/smartcontractkit/chainlink-common/pkg/logger"
"github.com/smartcontractkit/chainlink-common/pkg/metrics"
"github.com/smartcontractkit/chainlink-common/pkg/settings/limits"
+ "github.com/smartcontractkit/chainlink-common/pkg/workflows"
"github.com/smartcontractkit/chainlink/v2/core/platform"
"github.com/smartcontractkit/chainlink/v2/core/services/workflows/monitoring"
)
@@ -53,13 +58,52 @@ func findMetric(t *testing.T, reader *sdkmetric.ManualReader, name string) *metr
// fakeQueue is a minimal Queue whose Observe pops a scripted sequence of
// results and counts calls. Once the script is exhausted it returns empty.
type fakeQueue struct {
- mu sync.Mutex
- results []observeResult
- calls int
+ mu sync.Mutex
+ results []*observeResult
+ drainCalls int
+}
+
+func (q *fakeQueue) Sorted(_ context.Context, limit, _ int) iter.Seq2[[]byte, *pb.CoordinatedEvent] {
+ q.mu.Lock()
+ events := slices.Clone(q.results[0].events)
+ q.mu.Unlock()
+ slices.SortFunc(events, func(a, b centralQueueEvent) int { return a.Compare(b) })
+ return func(yield func([]byte, *pb.CoordinatedEvent) bool) {
+ var count int
+ for _, cqe := range events[:min(limit, len(events))] {
+ if count++; count > limit {
+ return
+ }
+ if !yield(cqe.timelessHash, cqe.pb) {
+ return
+ }
+ }
+ }
+}
+
+// never consumed by anything else
+func (q *fakeQueue) LastConsumed() time.Time { return time.Time{} }
+
+func (q *fakeQueue) DropExpired(context.Context, time.Time) int { return 0 }
+
+func (q *fakeQueue) Remove(ctx context.Context, execIDs iter.Seq[string]) {
+ execIDSet := map[string]struct{}{}
+ for execID := range execIDs {
+ execIDSet[execID] = struct{}{}
+ }
+ q.mu.Lock()
+ defer q.mu.Unlock()
+ for _, r := range q.results {
+ r.events = slices.DeleteFunc(r.events, func(e centralQueueEvent) bool {
+ _, ok := execIDSet[e.executionID]
+ return ok
+ })
+ // note: empty results remain
+ }
}
type observeResult struct {
- events []CoordinatedEvent
+ events []centralQueueEvent
err error
}
@@ -70,19 +114,23 @@ func (q *fakeQueue) Stats(context.Context) (Stats, error) { return Stats{}, nil
func (q *fakeQueue) Drain(context.Context) ([]CoordinatedEvent, error) {
q.mu.Lock()
defer q.mu.Unlock()
- q.calls++
+ q.drainCalls++
if len(q.results) == 0 {
return nil, nil
}
r := q.results[0]
q.results = q.results[1:]
- return r.events, r.err
+ events := make([]CoordinatedEvent, len(r.events))
+ for i, e := range r.events {
+ events[i] = e.CoordinatedEvent
+ }
+ return events, r.err
}
-func (q *fakeQueue) observeCalls() int {
+func (q *fakeQueue) getDrainCalls() int {
q.mu.Lock()
defer q.mu.Unlock()
- return q.calls
+ return q.drainCalls
}
func (q *fakeQueue) remaining() int {
@@ -94,6 +142,29 @@ func (q *fakeQueue) remaining() int {
// batchOf returns a one-event batch tagged with id.
func batchOf(id string) []CoordinatedEvent { return []CoordinatedEvent{{WorkflowID: id}} }
+func centralQueueEvents(t *testing.T, events []CoordinatedEvent) []centralQueueEvent {
+ cqes := make([]centralQueueEvent, len(events))
+ for i, e := range events {
+ pbe := e.ToProto()
+ cqes[i] = centralQueueEvent{
+ CoordinatedEvent: e,
+ pb: pbe,
+ timelessHash: func() []byte {
+ b, err := pbe.MarshalTimeless()
+ require.NoError(t, err)
+ hash := sha256.Sum256(b)
+ return hash[:]
+ }(),
+ executionID: func() string {
+ execID, err := workflows.GenerateExecutionIDWithTriggerIndex(e.WorkflowID, e.Event.Event.ID, e.TriggerIndex)
+ require.NoError(t, err)
+ return execID
+ }(),
+ }
+ }
+ return cqes
+}
+
// TestDrainer_Drain calls drain directly (no worker running), so the batches
// it hands off stay in the channel for inspection.
func TestDrainer_Drain(t *testing.T) {
@@ -115,25 +186,25 @@ func TestDrainer_Drain(t *testing.T) {
tests := []struct {
name string
- results []observeResult // one per drain call
+ results []*observeResult // one per drain call
want [][]CoordinatedEvent
}{
{
name: "queues an observed batch",
- results: []observeResult{{events: batchOf("a")}},
+ results: []*observeResult{{events: centralQueueEvents(t, batchOf("a"))}},
want: [][]CoordinatedEvent{batchOf("a")},
},
{
name: "empty observe queues nothing",
- results: []observeResult{{}},
+ results: []*observeResult{{}},
},
{
name: "observe error queues nothing, even with events",
- results: []observeResult{{events: batchOf("ignored"), err: errors.New("boom")}},
+ results: []*observeResult{{events: centralQueueEvents(t, batchOf("ignored")), err: errors.New("boom")}},
},
{
name: "full buffer drops the overflow and keeps the oldest",
- results: []observeResult{{events: batchOf("a")}, {events: batchOf("b")}},
+ results: []*observeResult{{events: centralQueueEvents(t, batchOf("a"))}, {events: centralQueueEvents(t, batchOf("b"))}},
want: [][]CoordinatedEvent{batchOf("a")},
},
}
@@ -151,7 +222,7 @@ func TestDrainer_Drain(t *testing.T) {
d.drain(t.Context()) // must return even when the buffer is full
}
- assert.Equal(t, len(tt.results), q.observeCalls(), "one Observe per drain")
+ assert.Equal(t, len(tt.results), q.getDrainCalls(), "one Observe per drain")
assert.Equal(t, tt.want, queued(d))
assert.False(t, hookCalled.Load(), "drain never calls the hook itself; only the worker does")
})
@@ -164,9 +235,9 @@ func TestDrainer_DroppedEventsMetric(t *testing.T) {
t.Parallel()
dm, reader := testDrainerMetrics(t)
- q := &fakeQueue{results: []observeResult{
- {events: batchOf("a")},
- {events: append(batchOf("b"), batchOf("c")...)}, // dropped: the buffer holds "a"
+ q := &fakeQueue{results: []*observeResult{
+ {events: centralQueueEvents(t, batchOf("a"))},
+ {events: append(centralQueueEvents(t, batchOf("b")), centralQueueEvents(t, batchOf("c"))...)}, // dropped: the buffer holds "a"
}}
d := NewDrainer(q, limits.NewUpperBoundLimiter(time.Hour), drainerHooks{}, dm, clockwork.NewRealClock(), logger.Test(t))
d.drain(t.Context())
@@ -188,7 +259,7 @@ func TestDrainer_HookDurationMetric(t *testing.T) {
t.Parallel()
dm, reader := testDrainerMetrics(t)
- q := &fakeQueue{results: []observeResult{{events: batchOf("a")}}}
+ q := &fakeQueue{results: []*observeResult{{events: centralQueueEvents(t, batchOf("a"))}}}
d := NewDrainer(q, limits.NewUpperBoundLimiter(minDrainInterval), drainerHooks{}, dm, clockwork.NewRealClock(), logger.Test(t))
require.NoError(t, d.Start(t.Context()))
t.Cleanup(func() { assert.NoError(t, d.Close()) })
@@ -209,17 +280,17 @@ func TestDrainer_Running(t *testing.T) {
tests := []struct {
name string
- results []observeResult
+ results []*observeResult
want []string // workflow IDs the hook should see
}{
{
name: "hook receives an observed batch",
- results: []observeResult{{events: batchOf("a")}},
+ results: []*observeResult{{events: centralQueueEvents(t, batchOf("a"))}},
want: []string{"a"},
},
{
name: "loop survives an observe error",
- results: []observeResult{{err: errors.New("boom")}, {events: batchOf("a")}},
+ results: []*observeResult{{err: errors.New("boom")}, {events: centralQueueEvents(t, batchOf("a"))}},
want: []string{"a"},
},
}
@@ -269,9 +340,9 @@ func TestDrainer_BlockedHook(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
- results := make([]observeResult, tt.batches)
+ results := make([]*observeResult, tt.batches)
for i := range results {
- results[i] = observeResult{events: batchOf("x")}
+ results[i] = &observeResult{events: centralQueueEvents(t, batchOf("x"))}
}
q := &fakeQueue{results: results}
@@ -349,12 +420,12 @@ func TestDrainer_IntervalReRead(t *testing.T) {
drainsAfter := func(wait time.Duration) {
t.Helper()
waiting()
- before := q.observeCalls()
+ before := q.getDrainCalls()
clock.Advance(wait - time.Millisecond)
- assert.Never(t, func() bool { return q.observeCalls() > before }, 50*time.Millisecond, 5*time.Millisecond,
+ assert.Never(t, func() bool { return q.getDrainCalls() > before }, 50*time.Millisecond, 5*time.Millisecond,
"drained before %s", wait)
clock.Advance(time.Millisecond)
- require.Eventually(t, func() bool { return q.observeCalls() == before+1 }, 5*time.Second, 5*time.Millisecond,
+ require.Eventually(t, func() bool { return q.getDrainCalls() == before+1 }, 5*time.Second, 5*time.Millisecond,
"no drain at %s", wait)
}
@@ -390,10 +461,11 @@ func TestNewCentralQueueDrainer_LogsDrainedEvents(t *testing.T) {
t.Parallel()
clock := clockwork.NewFakeClock()
batch := append(append(batchOf("wf-a"), batchOf("wf-b")...), batchOf("wf-a")...)
- q := &fakeQueue{results: []observeResult{{events: batch}}}
+ q := &fakeQueue{results: []*observeResult{{events: centralQueueEvents(t, batch)}}}
dm, _ := testDrainerMetrics(t)
lggr, logs := logger.TestObserved(t, zapcore.DebugLevel)
- d := NewCentralQueueDrainer(q, limits.NewUpperBoundLimiter(minDrainInterval), dm, clock, lggr)
+ grace := func(context.Context) (time.Duration, error) { return time.Minute, nil }
+ d := NewCentralQueueDrainer(q, grace, limits.NewUpperBoundLimiter(minDrainInterval), dm, clock, lggr)
require.NoError(t, d.Start(t.Context()))
t.Cleanup(func() { assert.NoError(t, d.Close()) })
@@ -417,3 +489,67 @@ func TestNewCentralQueueDrainer_LogsDrainedEvents(t *testing.T) {
}
assert.Equal(t, map[string]int64{"wf-a": 2, "wf-b": 1}, got)
}
+
+// While something else is consuming the central queue, the drainer leaves live events to it and only drops those
+// that have expired. Once the consumer is quiet it drains everything again.
+func TestCentralQueueDrainer_YieldsToAConsumer(t *testing.T) {
+ t.Parallel()
+
+ q := newTestCentralQueue(t, &fakeLimit{limit: 10})
+ clock := clockwork.NewFakeClockAt(time.Now())
+ grace := func(context.Context) (time.Duration, error) { return time.Minute, nil }
+ dm, _ := testDrainerMetrics(t)
+ var mu sync.Mutex
+ var drained []string
+ d := NewCentralQueueDrainer(q, grace, limits.NewUpperBoundLimiter(time.Second), dm, clock, logger.Test(t))
+ d.hooks.OnObservedEvents = func(_ context.Context, events []CoordinatedEvent) {
+ mu.Lock()
+ defer mu.Unlock()
+ drained = append(drained, eventIDs(events)...)
+ }
+ require.NoError(t, d.Start(t.Context()))
+ t.Cleanup(func() { require.NoError(t, d.Close()) })
+
+ put := func(id string, deadline time.Time) {
+ e := centralEvent("wf-a", 0, id)
+ e.Deadline = deadline
+ require.NoError(t, q.Put(t.Context(), e))
+ }
+ depth := func() uint64 {
+ stats, err := q.Stats(t.Context())
+ require.NoError(t, err)
+ return stats.DepthByWorkflow["wf-a"]
+ }
+ now := clock.Now()
+ put("live", now.Add(time.Hour))
+ put("expired", now.Add(-2*time.Minute)) // past its deadline by more than the grace period
+ put("in-grace", now.Add(-30*time.Second))
+
+ // no consumer yet: everything is drained
+ d.drain(t.Context())
+ assert.Zero(t, depth())
+ handed := func() int { mu.Lock(); defer mu.Unlock(); return len(drained) }
+ require.Eventually(t, func() bool { return handed() == 3 }, 5*time.Second, 5*time.Millisecond, "the hook is called on its own goroutine")
+
+ // a consumer reads the queue
+ put("live", now.Add(time.Hour))
+ put("expired", now.Add(-2*time.Minute))
+ put("in-grace", now.Add(-30*time.Second))
+ for range q.Sorted(t.Context(), 10, 0) {
+ }
+ clock.Advance(0) // the consumer read at the real time of the test, which is the clock's start
+ d.drain(t.Context())
+ assert.Equal(t, uint64(2), depth(), "only the event past its deadline and the grace period was dropped, and the rest was not drained")
+
+ // the consumer goes quiet for longer than the window
+ clock.Advance(consumerWindow(time.Second) + time.Second)
+ d.drain(t.Context())
+ assert.Zero(t, depth(), "so the rest is drained")
+ require.Eventually(t, func() bool { return handed() == 5 }, 5*time.Second, 5*time.Millisecond)
+}
+
+func TestConsumerWindow(t *testing.T) {
+ t.Parallel()
+ assert.Equal(t, minConsumerWindow, consumerWindow(time.Second), "at least the minimum")
+ assert.Equal(t, 3*time.Minute, consumerWindow(time.Minute), "and otherwise three intervals")
+}
diff --git a/core/services/workflows/v2/triggers/queue.go b/core/services/workflows/v2/triggers/queue.go
index cfa3d0089cd..b0720d4825a 100644
--- a/core/services/workflows/v2/triggers/queue.go
+++ b/core/services/workflows/v2/triggers/queue.go
@@ -1,14 +1,27 @@
package triggers
import (
+ "bytes"
+ "cmp"
+ "container/heap"
"context"
+ "crypto/sha256"
"errors"
+ "fmt"
+ "iter"
"maps"
+ "slices"
"sync"
+ "sync/atomic"
+ "time"
+ "google.golang.org/protobuf/proto"
+
+ "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb"
"github.com/smartcontractkit/chainlink-common/pkg/logger"
"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/workflows/monitoring"
)
@@ -29,6 +42,15 @@ type Queue interface {
// Stats reports current length, capacity, and cumulative drops.
Stats(context.Context) (Stats, error)
+
+ // Sorted returns a sorted iterator over events, up to limit. Events remain but can be removed via Remove.
+ // Events are filtered as they are pulled: those whose encoded size (without timestamps, i.e. as an element of a
+ // blob) exceeds maxEventBytes can never be observed, so they are skipped (not counting toward limit), and dropped
+ // from the queue (counted and logged) when iteration ends. maxEventBytes <= 0 disables this.
+ Sorted(ctx context.Context, limit, maxEventBytes int) iter.Seq2[[]byte, *pb.CoordinatedEvent]
+
+ // Remove removes events from the queue by execution ID.
+ Remove(ctx context.Context, executionIDs iter.Seq[string])
}
// Stats is a point-in-time view of a Queue.
@@ -55,10 +77,24 @@ type CentralQueue struct {
lggr logger.Logger
mu sync.Mutex
- events []CoordinatedEvent
+ events []centralQueueEvent
depthByWorkflow map[string]uint64
depthByTriggerType map[string]uint64
droppedByReason map[string]uint64
+
+ lastConsumed atomic.Int64 // unix nanoseconds of the last Sorted call, zero if never
+}
+
+type centralQueueEvent struct {
+ CoordinatedEvent
+ pb *pb.CoordinatedEvent
+ timelessHash []byte
+ executionID string
+ blobSize int // encoded size of pb without timestamps: its size as an element of a blob
+}
+
+func (q *centralQueueEvent) Compare(other centralQueueEvent) int {
+ return cmp.Or(q.Deadline.Compare(other.Deadline), bytes.Compare(q.timelessHash, other.timelessHash))
}
// NewQueue returns the node's central trigger queue. limit is read on every Put. If it cannot be read, the
@@ -87,7 +123,23 @@ func (q *CentralQueue) Put(ctx context.Context, e CoordinatedEvent) error {
q.drop(ctx, monitoring.CentralTriggerQueueDropReasonQueueFull)
return ErrQueueFull
}
- q.events = append(q.events, e)
+ pbe := e.ToProto()
+ timelessBytes, err := pbe.MarshalTimeless() // as it appears in a blob: hashed, and sized for the oversize filter
+ if err != nil {
+ return fmt.Errorf("failed to marshal event without timestamps: %w", err)
+ }
+ timelessHash := sha256.Sum256(timelessBytes)
+ execID, err := workflows.GenerateExecutionIDWithTriggerIndex(e.WorkflowID, e.Event.Event.ID, e.TriggerIndex)
+ if err != nil {
+ return fmt.Errorf("failed to generate execution ID: %w", err)
+ }
+ q.events = append(q.events, centralQueueEvent{
+ CoordinatedEvent: e,
+ pb: pbe,
+ timelessHash: timelessHash[:],
+ executionID: execID,
+ blobSize: len(timelessBytes),
+ })
q.depthByWorkflow[e.WorkflowID]++
q.depthByTriggerType[e.TriggerCapID]++
q.metrics.IncrementPutsCounter(ctx)
@@ -103,7 +155,10 @@ func (q *CentralQueue) Drain(ctx context.Context) ([]CoordinatedEvent, error) {
q.mu.Lock()
defer q.mu.Unlock()
- events := q.events
+ events := make([]CoordinatedEvent, len(q.events))
+ for i, pbe := range q.events {
+ events[i] = pbe.CoordinatedEvent
+ }
q.events = nil
q.depthByWorkflow = map[string]uint64{}
q.depthByTriggerType = map[string]uint64{}
@@ -113,6 +168,127 @@ func (q *CentralQueue) Drain(ctx context.Context) ([]CoordinatedEvent, error) {
return events, nil
}
+func (q *CentralQueue) Remove(ctx context.Context, executionIDs iter.Seq[string]) {
+ execIDSet := map[string]struct{}{}
+ for triggerEventID := range executionIDs {
+ execIDSet[triggerEventID] = struct{}{}
+ }
+
+ capacity := q.capacity(ctx)
+
+ q.mu.Lock()
+ defer q.mu.Unlock()
+
+ var deleted int
+ q.events = slices.DeleteFunc(q.events, func(cqe centralQueueEvent) bool {
+ _, ok := execIDSet[cqe.executionID]
+ if ok {
+ deleted++
+ q.depthByWorkflow[cqe.WorkflowID]--
+ q.depthByTriggerType[cqe.TriggerCapID]--
+ q.metrics.RecordEventAge(ctx, time.Since(cqe.ObservedAt).Seconds())
+ }
+ return ok
+ })
+ q.metrics.IncrementDrainedEventsCounter(ctx, deleted)
+ q.metrics.RecordDepth(ctx, len(q.events))
+ q.metrics.RecordCapacity(ctx, q.effectiveCapacity(capacity))
+}
+
+func (q *CentralQueue) Sorted(ctx context.Context, limit, maxEventBytes int) iter.Seq2[[]byte, *pb.CoordinatedEvent] {
+ q.lastConsumed.Store(time.Now().UnixNano())
+ q.mu.Lock()
+ events := priorityQueue(slices.Clone(q.events))
+ q.mu.Unlock()
+
+ heap.Init(&events)
+
+ return func(yield func([]byte, *pb.CoordinatedEvent) bool) {
+ // Events are only examined as they are pulled. Those too large to ever be observed are skipped (they do not
+ // count toward limit), and then dropped from the queue once the caller is done pulling.
+ var oversize []centralQueueEvent
+ defer func() { q.dropOversize(ctx, oversize, maxEventBytes) }()
+
+ for count := 0; events.Len() > 0 && count < limit; {
+ cqe := heap.Pop(&events).(centralQueueEvent)
+ if maxEventBytes > 0 && cqe.blobSize > maxEventBytes {
+ oversize = append(oversize, cqe)
+ continue
+ }
+ count++
+ if !yield(cqe.timelessHash, proto.CloneOf(cqe.pb)) {
+ return
+ }
+ }
+ }
+}
+
+// dropOversize removes the events from the queue, if they are still there. They are dropped, not run locally instead:
+// executions must be coordinated by consensus, and an event that cannot be put in a blob cannot reach it.
+func (q *CentralQueue) dropOversize(ctx context.Context, oversize []centralQueueEvent, maxEventBytes int) {
+ if len(oversize) == 0 {
+ return
+ }
+ executionIDs := make(map[string]struct{}, len(oversize))
+ for _, cqe := range oversize {
+ executionIDs[cqe.executionID] = struct{}{}
+ }
+
+ q.mu.Lock()
+ defer q.mu.Unlock()
+ var dropped int
+ q.events = slices.DeleteFunc(q.events, func(cqe centralQueueEvent) bool {
+ if _, ok := executionIDs[cqe.executionID]; !ok {
+ return false
+ }
+ dropped++
+ q.depthByWorkflow[cqe.WorkflowID]--
+ q.depthByTriggerType[cqe.TriggerCapID]--
+ q.lggr.Errorw("Dropping event too large to be observed", "workflowID", cqe.WorkflowID, "executionID", cqe.executionID,
+ "size", cqe.blobSize, "maxSize", maxEventBytes)
+ q.drop(ctx, monitoring.CentralTriggerQueueDropReasonOversize)
+ return true
+ })
+ if dropped > 0 {
+ q.metrics.RecordDepth(ctx, len(q.events))
+ }
+}
+
+// LastConsumed is when Sorted was last called, which is how the consensus queue plugin reads the queue, or the zero
+// time if it never was. The drainer uses it to leave the events to the plugin while it is reading them.
+func (q *CentralQueue) LastConsumed() time.Time {
+ n := q.lastConsumed.Load()
+ if n == 0 {
+ return time.Time{}
+ }
+ return time.Unix(0, n)
+}
+
+// DropExpired removes the events whose deadline is before cutoff, and returns how many. Nothing else expires events,
+// and an event that never reaches consensus would otherwise stay for good.
+func (q *CentralQueue) DropExpired(ctx context.Context, cutoff time.Time) int {
+ capacity := q.capacity(ctx)
+
+ q.mu.Lock()
+ defer q.mu.Unlock()
+ var dropped int
+ q.events = slices.DeleteFunc(q.events, func(cqe centralQueueEvent) bool {
+ if !cqe.Deadline.Before(cutoff) {
+ return false
+ }
+ dropped++
+ q.depthByWorkflow[cqe.WorkflowID]--
+ q.depthByTriggerType[cqe.TriggerCapID]--
+ q.drop(ctx, monitoring.CentralTriggerQueueDropReasonExpired)
+ return true
+ })
+ if dropped > 0 {
+ q.metrics.RecordDepth(ctx, len(q.events))
+ q.metrics.RecordCapacity(ctx, q.effectiveCapacity(capacity))
+ }
+ return dropped
+}
+
// Stats returns copies of the queue's maps, so callers may keep or change them.
func (q *CentralQueue) Stats(ctx context.Context) (Stats, error) {
capacity := q.capacity(ctx)
@@ -160,3 +336,37 @@ type queueCapacity struct {
limit int
ok bool
}
+
+var _ heap.Interface = (*priorityQueue)(nil)
+
+// priorityQueue is a heap of coordinated events, ordered by deadline and then trigger event ID.
+type priorityQueue []centralQueueEvent
+
+func (p *priorityQueue) Len() int {
+ if p == nil {
+ return 0
+ }
+ return len(*p)
+}
+
+func (p *priorityQueue) Less(i, j int) bool {
+ a, b := (*p)[i], (*p)[j]
+ return a.Compare(b) < 0
+}
+
+func (p *priorityQueue) Swap(i, j int) {
+ (*p)[i], (*p)[j] = (*p)[j], (*p)[i]
+}
+
+func (p *priorityQueue) Push(x any) {
+ *p = append(*p, x.(centralQueueEvent))
+}
+
+func (p *priorityQueue) Pop() any {
+ if p.Len() == 0 {
+ return nil
+ }
+ e := (*p)[len(*p)-1]
+ *p = (*p)[:len(*p)-1]
+ return e
+}
diff --git a/core/services/workflows/v2/triggers/queue_test.go b/core/services/workflows/v2/triggers/queue_test.go
index 3966a48396d..488475a107e 100644
--- a/core/services/workflows/v2/triggers/queue_test.go
+++ b/core/services/workflows/v2/triggers/queue_test.go
@@ -3,6 +3,8 @@ package triggers
import (
"context"
"fmt"
+ "slices"
+ "strings"
"sync"
"testing"
"time"
@@ -12,6 +14,7 @@ import (
"go.opentelemetry.io/otel/attribute"
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
"go.opentelemetry.io/otel/sdk/metric/metricdata"
+ "google.golang.org/protobuf/proto"
"github.com/smartcontractkit/chainlink-common/pkg/capabilities"
"github.com/smartcontractkit/chainlink-common/pkg/logger"
@@ -69,15 +72,14 @@ func testQueueMetrics(t *testing.T) (*monitoring.CentralTriggerQueueMetricLabele
// centralEvent returns an event for the given registration. Deadline and SequenceNumber are set so a test
// can tell if the queue changes them.
func centralEvent(workflowID string, triggerIndex int, id string) CoordinatedEvent {
- observed := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
+ observed := time.Now()
return CoordinatedEvent{
- WorkflowID: workflowID,
- TriggerCapID: fmt.Sprintf("trigger-%d@1.0.0", triggerIndex),
- TriggerIndex: triggerIndex,
- ObservedAt: observed,
- Deadline: observed.Add(time.Minute),
- SequenceNumber: 42,
- Event: capabilities.TriggerResponse{Event: capabilities.TriggerEvent{ID: id}},
+ WorkflowID: workflowID,
+ TriggerCapID: fmt.Sprintf("trigger-%d@1.0.0", triggerIndex),
+ TriggerIndex: triggerIndex,
+ ObservedAt: observed,
+ Deadline: observed.Add(time.Minute),
+ Event: capabilities.TriggerResponse{Event: capabilities.TriggerEvent{ID: id}},
}
}
@@ -269,9 +271,8 @@ func TestQueue_ConcurrentPutDrain(t *testing.T) {
var wg sync.WaitGroup
for p := range producers {
wg.Go(func() {
- for seq := range perProducer {
+ for range perProducer {
e := centralEvent(fmt.Sprintf("wf-%d", p), 0, "evt")
- e.SequenceNumber = uint64(seq)
err := q.Put(t.Context(), e)
if err == nil {
accepted[p]++
@@ -334,13 +335,13 @@ func TestQueue_ConcurrentPutDrain(t *testing.T) {
assert.Positive(t, totalDropped, "the drop path never ran")
}
- last := map[string]uint64{}
+ last := map[string]time.Time{}
for _, e := range drained {
prev, seen := last[e.WorkflowID]
if seen {
- assert.Greater(t, e.SequenceNumber, prev, "order for %s", e.WorkflowID)
+ assert.True(t, e.ObservedAt.After(prev), "expected observedAt %s to be after previous %s", e.ObservedAt.UnixNano(), prev.UnixNano())
}
- last[e.WorkflowID] = e.SequenceNumber
+ last[e.WorkflowID] = e.ObservedAt
}
stats, err := q.Stats(t.Context())
@@ -479,3 +480,178 @@ func dataPointAttributes(t *testing.T, m metricdata.Metrics) []attribute.Set {
}
return sets
}
+
+func TestQueue_BlobSize(t *testing.T) {
+ t.Parallel()
+
+ q := newTestCentralQueue(t, &fakeLimit{limit: 10})
+ require.NoError(t, q.Put(t.Context(), centralEvent("wf", 0, "a")))
+
+ // the size recorded at Put is that of the event as it appears in a blob: timestamps stripped
+ stripped := proto.CloneOf(q.events[0].pb)
+ stripped.ObservedAt, stripped.Deadline = nil, nil
+ want, err := proto.MarshalOptions{Deterministic: true}.Marshal(stripped)
+ require.NoError(t, err)
+ assert.Equal(t, len(want), q.events[0].blobSize)
+ assert.NotNil(t, q.events[0].pb.ObservedAt, "stored event keeps its timestamps")
+ assert.NotNil(t, q.events[0].pb.Deadline)
+}
+
+func TestQueue_SortedDropsOversize(t *testing.T) {
+ t.Parallel()
+
+ newQueue := func(t *testing.T) (q *CentralQueue, maxSmall int) {
+ q = newTestCentralQueue(t, &fakeLimit{limit: 10})
+ big := centralEvent("big-wf", 1, "big")
+ big.Event.Event.TriggerType = strings.Repeat("x", 5000)
+ a, b := centralEvent("wf", 0, "a"), centralEvent("wf", 0, "b")
+ a.Deadline = a.Deadline.Add(-time.Second) // explicit order: a, big, b
+ b.Deadline = b.Deadline.Add(time.Second)
+ require.NoError(t, q.Put(t.Context(), a))
+ require.NoError(t, q.Put(t.Context(), big))
+ require.NoError(t, q.Put(t.Context(), b))
+ return q, max(q.events[0].blobSize, q.events[2].blobSize)
+ }
+ ids := func(q *CentralQueue, limit, maxSize int) (got []string) {
+ for _, e := range q.Sorted(t.Context(), limit, maxSize) {
+ got = append(got, e.Event.Event.Id)
+ }
+ return
+ }
+
+ t.Run("oversize events are dropped, counted and no longer queued", func(t *testing.T) {
+ t.Parallel()
+ q, maxSmall := newQueue(t)
+
+ assert.ElementsMatch(t, []string{"a", "b"}, ids(q, 10, maxSmall))
+
+ stats, err := q.Stats(t.Context())
+ require.NoError(t, err)
+ assert.Equal(t, uint64(2), stats.Len)
+ assert.Equal(t, uint64(1), stats.DroppedByReason[monitoring.CentralTriggerQueueDropReasonOversize])
+ assert.Zero(t, stats.DepthByWorkflow["big-wf"])
+ assert.Equal(t, uint64(2), stats.DepthByWorkflow["wf"])
+
+ // dropping happens once
+ assert.ElementsMatch(t, []string{"a", "b"}, ids(q, 10, maxSmall))
+ stats, err = q.Stats(t.Context())
+ require.NoError(t, err)
+ assert.Equal(t, uint64(1), stats.DroppedByReason[monitoring.CentralTriggerQueueDropReasonOversize])
+ })
+
+ t.Run("an event exactly at the limit is kept", func(t *testing.T) {
+ t.Parallel()
+ q, maxSmall := newQueue(t)
+ assert.Len(t, ids(q, 10, maxSmall), 2)
+ assert.Empty(t, ids(q, 10, maxSmall-1), "one byte less and the small events no longer fit")
+ })
+
+ t.Run("no maximum disables filtering", func(t *testing.T) {
+ t.Parallel()
+ q, _ := newQueue(t)
+ assert.Len(t, ids(q, 10, 0), 3)
+ assert.Len(t, ids(q, 10, -1), 3)
+ stats, err := q.Stats(t.Context())
+ require.NoError(t, err)
+ assert.Zero(t, stats.DroppedByReason[monitoring.CentralTriggerQueueDropReasonOversize])
+ })
+
+ t.Run("only events that are pulled are examined", func(t *testing.T) {
+ t.Parallel()
+ q, maxSmall := newQueue(t) // sorted: a, big, b
+ assert.Equal(t, []string{"a"}, ids(q, 1, maxSmall), "stops after the first, never reaching big")
+ stats, err := q.Stats(t.Context())
+ require.NoError(t, err)
+ assert.Equal(t, uint64(3), stats.Len, "nothing was dropped")
+ assert.Zero(t, stats.DroppedByReason[monitoring.CentralTriggerQueueDropReasonOversize])
+ })
+
+ t.Run("breaking out still drops the oversize events already skipped", func(t *testing.T) {
+ t.Parallel()
+ q, maxSmall := newQueue(t)
+ for _, e := range q.Sorted(t.Context(), 10, maxSmall) { // sorted: a, big (skipped), b
+ if e.Event.Event.Id == "b" {
+ break
+ }
+ }
+ stats, err := q.Stats(t.Context())
+ require.NoError(t, err)
+ assert.Equal(t, uint64(2), stats.Len)
+ assert.Equal(t, uint64(1), stats.DroppedByReason[monitoring.CentralTriggerQueueDropReasonOversize])
+ })
+
+ t.Run("the limit applies after filtering", func(t *testing.T) {
+ t.Parallel()
+ q, maxSmall := newQueue(t)
+ assert.Len(t, ids(q, 1, maxSmall), 1)
+ })
+}
+
+// How long an event was queued is recorded when consensus takes it from the queue, and not for those left in it.
+func TestQueue_RecordsHowLongRemovedEventsWereQueued(t *testing.T) {
+ t.Parallel()
+ qm, reader := testQueueMetrics(t)
+ q := NewQueue(&fakeLimit{limit: 10}, qm, logger.Test(t))
+
+ observedAgo := func(id string, ago time.Duration) CoordinatedEvent {
+ e := centralEvent("wf", 0, id)
+ e.ObservedAt = time.Now().Add(-ago)
+ return e
+ }
+ putAll(t, q, observedAgo("a", 5*time.Second), observedAgo("b", 9*time.Second), observedAgo("stays", time.Hour))
+ require.Len(t, q.events, 3)
+ removed := []string{q.events[0].executionID, q.events[1].executionID}
+
+ q.Remove(t.Context(), slices.Values(removed))
+
+ m := findMetric(t, reader, "platform_engine_central_trigger_queue_event_age_seconds")
+ require.NotNil(t, m)
+ hist, ok := m.Data.(metricdata.Histogram[float64])
+ require.True(t, ok)
+ require.Len(t, hist.DataPoints, 1)
+ assert.Equal(t, uint64(2), hist.DataPoints[0].Count, "one for each event removed, none for the one left")
+ assert.InDelta(t, 14.0, hist.DataPoints[0].Sum, 0.5, "5s and 9s")
+
+ q.Remove(t.Context(), slices.Values([]string{"not-queued"}))
+ m = findMetric(t, reader, "platform_engine_central_trigger_queue_event_age_seconds")
+ hist = m.Data.(metricdata.Histogram[float64])
+ assert.Equal(t, uint64(2), hist.DataPoints[0].Count, "removing what is not there records nothing")
+}
+
+// Sorted is how the consensus queue plugin reads the queue, so it is what makes the queue count as consumed.
+func TestQueue_LastConsumed(t *testing.T) {
+ t.Parallel()
+ q := newTestCentralQueue(t, &fakeLimit{limit: 10})
+ putAll(t, q, centralEvent("wf-a", 0, "evt-1"))
+
+ assert.True(t, q.LastConsumed().IsZero(), "never read")
+ _, err := q.Drain(t.Context())
+ require.NoError(t, err)
+ assert.True(t, q.LastConsumed().IsZero(), "draining is not consuming")
+
+ before := time.Now()
+ for range q.Sorted(t.Context(), 10, 0) {
+ }
+ assert.WithinDuration(t, before, q.LastConsumed(), time.Second)
+}
+
+func TestQueue_DropExpired(t *testing.T) {
+ t.Parallel()
+ q := newTestCentralQueue(t, &fakeLimit{limit: 10})
+ now := time.Now()
+ at := func(id string, deadline time.Time) CoordinatedEvent {
+ e := centralEvent("wf-a", 0, id)
+ e.Deadline = deadline
+ return e
+ }
+ putAll(t, q, at("old-1", now.Add(-2*time.Minute)), at("live", now.Add(time.Minute)), at("old-2", now.Add(-time.Minute)), at("edge", now))
+
+ assert.Equal(t, 2, q.DropExpired(t.Context(), now), "those with a deadline before the cutoff, not at it")
+ assert.Zero(t, q.DropExpired(t.Context(), now), "nothing more to drop")
+
+ stats, err := q.Stats(t.Context())
+ require.NoError(t, err)
+ assert.Equal(t, uint64(2), stats.DepthByWorkflow["wf-a"])
+ assert.Equal(t, uint64(2), stats.DroppedByReason[monitoring.CentralTriggerQueueDropReasonExpired])
+ assert.Equal(t, []string{"live", "edge"}, drainIDs(t, q), "the rest are untouched, in order")
+}
diff --git a/core/services/workflows/v2/triggers/triggers.go b/core/services/workflows/v2/triggers/triggers.go
index 3d584f10079..665c0d106d4 100644
--- a/core/services/workflows/v2/triggers/triggers.go
+++ b/core/services/workflows/v2/triggers/triggers.go
@@ -182,20 +182,17 @@ type CoordinatedEvent struct {
// A settings change after dispatch does not affect already-queued events
Deadline time.Time
- // SequenceNumber determines the execution order of trigger events across the DON.
- SequenceNumber uint64
- Event capabilities.TriggerResponse
+ Event capabilities.TriggerResponse
}
func (e *CoordinatedEvent) ToProto() *pb.CoordinatedEvent {
return &pb.CoordinatedEvent{
- WorkflowID: e.WorkflowID,
- TriggerCapID: e.TriggerCapID,
- TriggerIndex: int64(e.TriggerIndex),
- ObservedAt: timestamppb.New(e.ObservedAt),
- Deadline: timestamppb.New(e.Deadline),
- SequenceNumber: e.SequenceNumber,
- Event: pb.TriggerResponseToProto(e.Event),
+ WorkflowID: e.WorkflowID,
+ TriggerCapID: e.TriggerCapID,
+ TriggerIndex: int64(e.TriggerIndex),
+ ObservedAt: timestamppb.New(e.ObservedAt),
+ Deadline: timestamppb.New(e.Deadline),
+ Event: pb.TriggerResponseToProto(e.Event),
}
}
@@ -205,7 +202,6 @@ func (e *CoordinatedEvent) FromProto(p *pb.CoordinatedEvent) (err error) {
e.TriggerIndex = int(p.TriggerIndex)
e.ObservedAt = p.ObservedAt.AsTime()
e.Deadline = p.Deadline.AsTime()
- e.SequenceNumber = p.SequenceNumber
e.Event, err = pb.TriggerResponseFromProto(p.Event)
return
}
diff --git a/deployment/go.mod b/deployment/go.mod
index 8f29abd716d..f60708a1420 100644
--- a/deployment/go.mod
+++ b/deployment/go.mod
@@ -41,7 +41,7 @@ require (
github.com/smartcontractkit/chainlink-ccip/chains/solana/deployment v0.0.0-20260916222901-720a003dab50
github.com/smartcontractkit/chainlink-ccip/chains/solana/gobindings v0.0.0-20260922043016-517a12a4220e
github.com/smartcontractkit/chainlink-ccip/deployment v0.0.0-20261001213322-a2d686f610ca
- github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123132302-3db945c721d8
+ github.com/smartcontractkit/chainlink-common v0.11.2-0.20261124133622-53ca4463ec7d
github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb
github.com/smartcontractkit/chainlink-data-streams v1.1.3
github.com/smartcontractkit/chainlink-deployments-framework v0.126.0
diff --git a/deployment/go.sum b/deployment/go.sum
index 54821f4e940..ee18d260220 100644
--- a/deployment/go.sum
+++ b/deployment/go.sum
@@ -1421,8 +1421,8 @@ github.com/smartcontractkit/chainlink-ccip/deployment v0.0.0-20261001213322-a2d6
github.com/smartcontractkit/chainlink-ccip/deployment v0.0.0-20261001213322-a2d686f610ca/go.mod h1:Dm/Abz0vr7F2v9TygUX947q8HIwJEJikDfSdanX1Cic=
github.com/smartcontractkit/chainlink-ccv v0.16.0 h1:WhDQEEI2Kb5A4C0PNAa+nyGLDvG0H+uT6h4y1NwmkYg=
github.com/smartcontractkit/chainlink-ccv v0.16.0/go.mod h1:oaSLVHiJVbJ9aCcUQnoRuVONACWzA/DWVqvUnLAe9bE=
-github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123132302-3db945c721d8 h1:/Ha7GrK/2S2L6sXECIX4oreW8OlNDzNQ0SEOLhddftA=
-github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123132302-3db945c721d8/go.mod h1:Gv+qglZ5Kxtf4pvpYIx/FBbntZDuvxVH0a6zFNuG+e8=
+github.com/smartcontractkit/chainlink-common v0.11.2-0.20261124133622-53ca4463ec7d h1:hG4yKbTSx2vKuWz8Poy1R9FIGLSVbeND22NGEmYQ+HM=
+github.com/smartcontractkit/chainlink-common v0.11.2-0.20261124133622-53ca4463ec7d/go.mod h1:Gv+qglZ5Kxtf4pvpYIx/FBbntZDuvxVH0a6zFNuG+e8=
github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb h1:9rVrSeVOAwZsVe2pOpeVRp9XjhtMyjndgeROFglvOhg=
github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb/go.mod h1:WcOKzF6HkTDrkQ96aBHhcJ2IIYE7iK7M2tdt58ea2qc=
github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261119075727-f272852ab605 h1:8NbHKcKLqMf6EgVJz8Tejf/qbLFtlIopnEdKnrR2U2s=
diff --git a/go.mod b/go.mod
index 49a28a3a53d..c02c5665084 100644
--- a/go.mod
+++ b/go.mod
@@ -83,7 +83,7 @@ require (
github.com/smartcontractkit/chainlink-ccip/chains/solana v0.0.0-20260908155618-50f521d70e62
github.com/smartcontractkit/chainlink-ccip/chains/solana/gobindings v0.0.0-20260908155618-50f521d70e62
github.com/smartcontractkit/chainlink-ccv v0.16.0
- github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123132302-3db945c721d8
+ github.com/smartcontractkit/chainlink-common v0.11.2-0.20261124133622-53ca4463ec7d
github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb
github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261119075727-f272852ab605
github.com/smartcontractkit/chainlink-data-streams v1.1.3
diff --git a/go.sum b/go.sum
index e9ef0c636d4..941efeafd6f 100644
--- a/go.sum
+++ b/go.sum
@@ -1112,8 +1112,8 @@ github.com/smartcontractkit/chainlink-ccip/chains/solana/gobindings v0.0.0-20260
github.com/smartcontractkit/chainlink-ccip/chains/solana/gobindings v0.0.0-20260908155618-50f521d70e62/go.mod h1:c++Ed0jeYn4w8WIfiAboRwN6ClRRVGglL0qwB/QjJvM=
github.com/smartcontractkit/chainlink-ccv v0.16.0 h1:WhDQEEI2Kb5A4C0PNAa+nyGLDvG0H+uT6h4y1NwmkYg=
github.com/smartcontractkit/chainlink-ccv v0.16.0/go.mod h1:oaSLVHiJVbJ9aCcUQnoRuVONACWzA/DWVqvUnLAe9bE=
-github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123132302-3db945c721d8 h1:/Ha7GrK/2S2L6sXECIX4oreW8OlNDzNQ0SEOLhddftA=
-github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123132302-3db945c721d8/go.mod h1:Gv+qglZ5Kxtf4pvpYIx/FBbntZDuvxVH0a6zFNuG+e8=
+github.com/smartcontractkit/chainlink-common v0.11.2-0.20261124133622-53ca4463ec7d h1:hG4yKbTSx2vKuWz8Poy1R9FIGLSVbeND22NGEmYQ+HM=
+github.com/smartcontractkit/chainlink-common v0.11.2-0.20261124133622-53ca4463ec7d/go.mod h1:Gv+qglZ5Kxtf4pvpYIx/FBbntZDuvxVH0a6zFNuG+e8=
github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb h1:9rVrSeVOAwZsVe2pOpeVRp9XjhtMyjndgeROFglvOhg=
github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb/go.mod h1:WcOKzF6HkTDrkQ96aBHhcJ2IIYE7iK7M2tdt58ea2qc=
github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261119075727-f272852ab605 h1:8NbHKcKLqMf6EgVJz8Tejf/qbLFtlIopnEdKnrR2U2s=
diff --git a/integration-tests/go.mod b/integration-tests/go.mod
index cd241e2f293..3796a7f1ba5 100644
--- a/integration-tests/go.mod
+++ b/integration-tests/go.mod
@@ -30,7 +30,7 @@ require (
github.com/smartcontractkit/chainlink-ccip/chains/evm v0.0.0-20261001213322-a2d686f610ca
github.com/smartcontractkit/chainlink-ccip/chains/solana v0.0.0-20260922043016-517a12a4220e
github.com/smartcontractkit/chainlink-ccip/chains/solana/gobindings v0.0.0-20260922043016-517a12a4220e
- github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123132302-3db945c721d8
+ github.com/smartcontractkit/chainlink-common v0.11.2-0.20261124133622-53ca4463ec7d
github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb
github.com/smartcontractkit/chainlink-deployments-framework v0.126.0
github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261118192309-cfc3cc2381a2
diff --git a/integration-tests/go.sum b/integration-tests/go.sum
index 2dd85ecb161..eb56e014fd8 100644
--- a/integration-tests/go.sum
+++ b/integration-tests/go.sum
@@ -1406,8 +1406,8 @@ github.com/smartcontractkit/chainlink-ccip/deployment v0.0.0-20261001213322-a2d6
github.com/smartcontractkit/chainlink-ccip/deployment v0.0.0-20261001213322-a2d686f610ca/go.mod h1:Dm/Abz0vr7F2v9TygUX947q8HIwJEJikDfSdanX1Cic=
github.com/smartcontractkit/chainlink-ccv v0.16.0 h1:WhDQEEI2Kb5A4C0PNAa+nyGLDvG0H+uT6h4y1NwmkYg=
github.com/smartcontractkit/chainlink-ccv v0.16.0/go.mod h1:oaSLVHiJVbJ9aCcUQnoRuVONACWzA/DWVqvUnLAe9bE=
-github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123132302-3db945c721d8 h1:/Ha7GrK/2S2L6sXECIX4oreW8OlNDzNQ0SEOLhddftA=
-github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123132302-3db945c721d8/go.mod h1:Gv+qglZ5Kxtf4pvpYIx/FBbntZDuvxVH0a6zFNuG+e8=
+github.com/smartcontractkit/chainlink-common v0.11.2-0.20261124133622-53ca4463ec7d h1:hG4yKbTSx2vKuWz8Poy1R9FIGLSVbeND22NGEmYQ+HM=
+github.com/smartcontractkit/chainlink-common v0.11.2-0.20261124133622-53ca4463ec7d/go.mod h1:Gv+qglZ5Kxtf4pvpYIx/FBbntZDuvxVH0a6zFNuG+e8=
github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb h1:9rVrSeVOAwZsVe2pOpeVRp9XjhtMyjndgeROFglvOhg=
github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb/go.mod h1:WcOKzF6HkTDrkQ96aBHhcJ2IIYE7iK7M2tdt58ea2qc=
github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261119075727-f272852ab605 h1:8NbHKcKLqMf6EgVJz8Tejf/qbLFtlIopnEdKnrR2U2s=
diff --git a/integration-tests/load/go.mod b/integration-tests/load/go.mod
index 896962ff237..c1c750ebef7 100644
--- a/integration-tests/load/go.mod
+++ b/integration-tests/load/go.mod
@@ -20,7 +20,7 @@ require (
github.com/smartcontractkit/chainlink-ccip/chains/evm v0.0.0-20261001213322-a2d686f610ca
github.com/smartcontractkit/chainlink-ccip/chains/solana v0.0.0-20260922043016-517a12a4220e
github.com/smartcontractkit/chainlink-ccip/chains/solana/gobindings v0.0.0-20260922043016-517a12a4220e
- github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123132302-3db945c721d8
+ github.com/smartcontractkit/chainlink-common v0.11.2-0.20261124133622-53ca4463ec7d
github.com/smartcontractkit/chainlink-deployments-framework v0.126.0
github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261118192309-cfc3cc2381a2
github.com/smartcontractkit/chainlink-testing-framework/framework v0.16.9
diff --git a/integration-tests/load/go.sum b/integration-tests/load/go.sum
index e3292417554..74b49aa0c1a 100644
--- a/integration-tests/load/go.sum
+++ b/integration-tests/load/go.sum
@@ -1646,8 +1646,8 @@ github.com/smartcontractkit/chainlink-ccip/deployment v0.0.0-20261001213322-a2d6
github.com/smartcontractkit/chainlink-ccip/deployment v0.0.0-20261001213322-a2d686f610ca/go.mod h1:Dm/Abz0vr7F2v9TygUX947q8HIwJEJikDfSdanX1Cic=
github.com/smartcontractkit/chainlink-ccv v0.16.0 h1:WhDQEEI2Kb5A4C0PNAa+nyGLDvG0H+uT6h4y1NwmkYg=
github.com/smartcontractkit/chainlink-ccv v0.16.0/go.mod h1:oaSLVHiJVbJ9aCcUQnoRuVONACWzA/DWVqvUnLAe9bE=
-github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123132302-3db945c721d8 h1:/Ha7GrK/2S2L6sXECIX4oreW8OlNDzNQ0SEOLhddftA=
-github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123132302-3db945c721d8/go.mod h1:Gv+qglZ5Kxtf4pvpYIx/FBbntZDuvxVH0a6zFNuG+e8=
+github.com/smartcontractkit/chainlink-common v0.11.2-0.20261124133622-53ca4463ec7d h1:hG4yKbTSx2vKuWz8Poy1R9FIGLSVbeND22NGEmYQ+HM=
+github.com/smartcontractkit/chainlink-common v0.11.2-0.20261124133622-53ca4463ec7d/go.mod h1:Gv+qglZ5Kxtf4pvpYIx/FBbntZDuvxVH0a6zFNuG+e8=
github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb h1:9rVrSeVOAwZsVe2pOpeVRp9XjhtMyjndgeROFglvOhg=
github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb/go.mod h1:WcOKzF6HkTDrkQ96aBHhcJ2IIYE7iK7M2tdt58ea2qc=
github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261119075727-f272852ab605 h1:8NbHKcKLqMf6EgVJz8Tejf/qbLFtlIopnEdKnrR2U2s=
diff --git a/system-tests/lib/go.mod b/system-tests/lib/go.mod
index 69e94fad92b..98541b8e9d9 100644
--- a/system-tests/lib/go.mod
+++ b/system-tests/lib/go.mod
@@ -32,7 +32,7 @@ require (
github.com/smartcontractkit/chain-selectors v1.0.112
github.com/smartcontractkit/chainlink-aptos v0.0.0-20260923062809-ca886ade4d26
github.com/smartcontractkit/chainlink-ccip/chains/solana v0.0.0-20260922043016-517a12a4220e
- github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123132302-3db945c721d8
+ github.com/smartcontractkit/chainlink-common v0.11.2-0.20261124133622-53ca4463ec7d
github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb
github.com/smartcontractkit/chainlink-confidential-compute v1.3.0
github.com/smartcontractkit/chainlink-deployments-framework v0.126.0
diff --git a/system-tests/lib/go.sum b/system-tests/lib/go.sum
index 0269687f745..571169287e1 100644
--- a/system-tests/lib/go.sum
+++ b/system-tests/lib/go.sum
@@ -1667,8 +1667,8 @@ github.com/smartcontractkit/chainlink-ccip/deployment v0.0.0-20261001213322-a2d6
github.com/smartcontractkit/chainlink-ccip/deployment v0.0.0-20261001213322-a2d686f610ca/go.mod h1:Dm/Abz0vr7F2v9TygUX947q8HIwJEJikDfSdanX1Cic=
github.com/smartcontractkit/chainlink-ccv v0.16.0 h1:WhDQEEI2Kb5A4C0PNAa+nyGLDvG0H+uT6h4y1NwmkYg=
github.com/smartcontractkit/chainlink-ccv v0.16.0/go.mod h1:oaSLVHiJVbJ9aCcUQnoRuVONACWzA/DWVqvUnLAe9bE=
-github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123132302-3db945c721d8 h1:/Ha7GrK/2S2L6sXECIX4oreW8OlNDzNQ0SEOLhddftA=
-github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123132302-3db945c721d8/go.mod h1:Gv+qglZ5Kxtf4pvpYIx/FBbntZDuvxVH0a6zFNuG+e8=
+github.com/smartcontractkit/chainlink-common v0.11.2-0.20261124133622-53ca4463ec7d h1:hG4yKbTSx2vKuWz8Poy1R9FIGLSVbeND22NGEmYQ+HM=
+github.com/smartcontractkit/chainlink-common v0.11.2-0.20261124133622-53ca4463ec7d/go.mod h1:Gv+qglZ5Kxtf4pvpYIx/FBbntZDuvxVH0a6zFNuG+e8=
github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb h1:9rVrSeVOAwZsVe2pOpeVRp9XjhtMyjndgeROFglvOhg=
github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb/go.mod h1:WcOKzF6HkTDrkQ96aBHhcJ2IIYE7iK7M2tdt58ea2qc=
github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261119075727-f272852ab605 h1:8NbHKcKLqMf6EgVJz8Tejf/qbLFtlIopnEdKnrR2U2s=
diff --git a/system-tests/tests/go.mod b/system-tests/tests/go.mod
index 0d3635ef5a1..6dabd3f68e3 100644
--- a/system-tests/tests/go.mod
+++ b/system-tests/tests/go.mod
@@ -73,7 +73,7 @@ require (
github.com/smartcontractkit/chain-selectors v1.0.112
github.com/smartcontractkit/chainlink-aptos v0.0.0-20260923062809-ca886ade4d26
github.com/smartcontractkit/chainlink-ccip/chains/solana v0.0.0-20260922043016-517a12a4220e
- github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123132302-3db945c721d8
+ github.com/smartcontractkit/chainlink-common v0.11.2-0.20261124133622-53ca4463ec7d
github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb
github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261119075727-f272852ab605
github.com/smartcontractkit/chainlink-confidential-compute v1.3.0
diff --git a/system-tests/tests/go.sum b/system-tests/tests/go.sum
index 904b65bd93d..673cfe7b328 100644
--- a/system-tests/tests/go.sum
+++ b/system-tests/tests/go.sum
@@ -1846,8 +1846,8 @@ github.com/smartcontractkit/chainlink-ccip/deployment v0.0.0-20261001213322-a2d6
github.com/smartcontractkit/chainlink-ccip/deployment v0.0.0-20261001213322-a2d686f610ca/go.mod h1:Dm/Abz0vr7F2v9TygUX947q8HIwJEJikDfSdanX1Cic=
github.com/smartcontractkit/chainlink-ccv v0.16.0 h1:WhDQEEI2Kb5A4C0PNAa+nyGLDvG0H+uT6h4y1NwmkYg=
github.com/smartcontractkit/chainlink-ccv v0.16.0/go.mod h1:oaSLVHiJVbJ9aCcUQnoRuVONACWzA/DWVqvUnLAe9bE=
-github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123132302-3db945c721d8 h1:/Ha7GrK/2S2L6sXECIX4oreW8OlNDzNQ0SEOLhddftA=
-github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123132302-3db945c721d8/go.mod h1:Gv+qglZ5Kxtf4pvpYIx/FBbntZDuvxVH0a6zFNuG+e8=
+github.com/smartcontractkit/chainlink-common v0.11.2-0.20261124133622-53ca4463ec7d h1:hG4yKbTSx2vKuWz8Poy1R9FIGLSVbeND22NGEmYQ+HM=
+github.com/smartcontractkit/chainlink-common v0.11.2-0.20261124133622-53ca4463ec7d/go.mod h1:Gv+qglZ5Kxtf4pvpYIx/FBbntZDuvxVH0a6zFNuG+e8=
github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb h1:9rVrSeVOAwZsVe2pOpeVRp9XjhtMyjndgeROFglvOhg=
github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb/go.mod h1:WcOKzF6HkTDrkQ96aBHhcJ2IIYE7iK7M2tdt58ea2qc=
github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261119075727-f272852ab605 h1:8NbHKcKLqMf6EgVJz8Tejf/qbLFtlIopnEdKnrR2U2s=
diff --git a/system-tests/tests/smoke/cre/shadow_trigger_mode_test.go b/system-tests/tests/smoke/cre/shadow_trigger_mode_test.go
index d70be4aa6fc..3407d9aebe9 100644
--- a/system-tests/tests/smoke/cre/shadow_trigger_mode_test.go
+++ b/system-tests/tests/smoke/cre/shadow_trigger_mode_test.go
@@ -15,16 +15,18 @@ import (
t_helpers "github.com/smartcontractkit/chainlink/system-tests/tests/test-helpers"
)
-// shadowDrainedLogMessage is the debug line the central queue drainer writes per workflow per drained batch.
-const shadowDrainedLogMessage = "Drained shadow trigger events"
+// shadowSkippedLogMessage is the line the coordinator logs when the consensus queue plugin chose a shadowed event and the
+// coordinator did not start it. Every node logs it for the same event, and more than once, as events are started again.
+const shadowSkippedLogMessage = "Shadow mode: not starting the coordinated event"
// shadowWindowLayout matches the time range format of FeatureShadowTriggerModeActivePeriod in cresettings.
const shadowWindowLayout = "2006-01-02 15:04:05 -0700 MST"
// Test_CRE_V2_ShadowTriggerMode asserts shadow trigger mode end to end on a real DON. A shadow window delivered
-// through CRE settings for one workflow sends that workflow's events through the central queue and drainer,
-// while both workflows keep executing. A workflow outside the window is never shadowed. Moving the window into
-// the future stops shadowing with no restart.
+// through CRE settings for one workflow sends that workflow's events through the central queue to the consensus
+// queue plugin. When consensus chooses an event, the coordinator logs it instead of starting it. Both workflows keep
+// executing, from their own queues. A workflow outside the window is never shadowed. Moving the window into the
+// future stops shadowing with no restart.
//
// Shadow mode only affects coordinated engines, so CoordinatedEngineEnabled is on for the whole test. It is a
// global override on the shared environment, hence serial.
@@ -58,9 +60,11 @@ func Test_CRE_V2_ShadowTriggerMode(t *testing.T) {
t_helpers.WatchWorkflowLogs(t, testLogger, userLogsCh, baseMessageCh, t_helpers.WorkflowEngineInitErrorLog,
"Amazing workflow user log", 2*time.Minute, t_helpers.WithUserLogWorkflowID(workflowID))
}
- drained := func(workflowID string) int {
+ // skipped counts the events of workflowID that reached consensus in shadow mode. The central queue's drainer leaves
+ // the events to the plugin while it reads the queue, so what the plugin did with them is what is counted.
+ skipped := func(workflowID string) int {
t.Helper()
- return len(logLinesForWorkflow(t, testEnv, coordinatedEngineDON, shadowDrainedLogMessage, workflowID))
+ return len(logLinesForWorkflow(t, testEnv, coordinatedEngineDON, shadowSkippedLogMessage, workflowID))
}
workflowFileLocation := "../../../../core/scripts/cre/environment/examples/workflows/cron/main.go"
@@ -72,7 +76,7 @@ func Test_CRE_V2_ShadowTriggerMode(t *testing.T) {
t_helpers.UniqueWorkflowName(testEnv, "controlcron"), &workflowConfig, workflowFileLocation)
executes(shadowedID)
executes(controlID)
- require.Zero(t, drained(shadowedID), "shadow mode must be off by default")
+ require.Zero(t, skipped(shadowedID), "shadow mode must be off by default")
// Each phase is one ApplyCRESettings call, because overlapping overrides fail fast. The coordinated engine
// flag is read only when an engine is created, so the short reset does not change the running engines.
@@ -81,23 +85,27 @@ func Test_CRE_V2_ShadowTriggerMode(t *testing.T) {
settings = t_helpers.ApplyCRESettings(t, testEnv, coordinated,
t_helpers.Workflow(shadowedID, shadowWindow(now.Add(-time.Hour), now.Add(time.Hour))))
- requireLogForWorkflow(t, testEnv, coordinatedEngineDON, shadowDrainedLogMessage, shadowedID)
+ // A freshly started environment can take a few minutes before the plugin's OCR rounds begin (the nodes must find each
+ // other first). Until then the central queue's drainer takes the events, so the first one the plugin sees may be
+ // several ticks away.
+ require.Eventually(t, func() bool { return skipped(shadowedID) > 0 }, 4*time.Minute, 5*time.Second,
+ "expected a %q line for workflow %s on nodeset %s", shadowSkippedLogMessage, shadowedID, coordinatedEngineDON)
executes(shadowedID)
executes(controlID)
- require.Zero(t, drained(controlID), "a workflow outside the window must not be shadowed")
+ require.Zero(t, skipped(controlID), "a workflow outside the window must not be shadowed")
- // Kill switch. Once the new window has reached the nodes, the drained count stops growing while the
+ // Kill switch. Once the new window has reached the nodes, the skipped count stops growing while the
// workflow keeps executing.
settings.Reset(t)
t_helpers.ApplyCRESettings(t, testEnv, coordinated,
t_helpers.Workflow(shadowedID, shadowWindow(now.Add(time.Hour), now.Add(2*time.Hour))))
// Samples are further apart than the 30s cron period, so an equal pair means a tick passed unshadowed.
- settled := waitForStableCount(t, func() int { return drained(shadowedID) }, 40*time.Second, 4*time.Minute)
+ settled := waitForStableCount(t, func() int { return skipped(shadowedID) }, 40*time.Second, 4*time.Minute)
executes(shadowedID)
executes(shadowedID)
- require.Equal(t, settled, drained(shadowedID), "shadowing must stop once the window is in the future")
- require.Zero(t, drained(controlID), "a workflow outside the window must not be shadowed")
+ require.Equal(t, settled, skipped(shadowedID), "shadowing must stop once the window is in the future")
+ require.Zero(t, skipped(controlID), "a workflow outside the window must not be shadowed")
}
// shadowWindow returns the PerWorkflow TOML that sets the shadow trigger mode window to [from, to].