From 8f1afd84a8b9cd06625f382fcadd457e5949ceac Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Thu, 29 Oct 2026 07:16:59 -0500 Subject: [PATCH 01/38] ConsensusQueue: wire no-op ReportingPlugin --- .../workflow-gateway-capabilities-don.toml | 2 +- core/services/internal/internal.go | 9 ++ core/services/ocr2/delegate.go | 39 +++-- core/services/ocr2/validate/validate.go | 11 ++ core/services/ocr3_1/plugins/queue/config.go | 14 ++ core/services/ocr3_1/plugins/queue/queue.go | 89 ++++++----- .../ocr3_1/plugins/queue/transmitter.go | 33 ++++ .../workflows/v2/capability_executor.go | 12 +- .../workflows/v2/capability_executor_test.go | 8 +- .../workflows/v2/triggers/triggers.go | 25 +++ .../jobs/pkg/templates/consensus-queue.tmpl | 14 ++ deployment/cre/jobs/propose_job_spec_test.go | 2 + system-tests/lib/cre/don.go | 2 +- .../lib/cre/environment/environment.go | 43 ++++++ system-tests/lib/cre/features/queue/queue.go | 146 ++++++++++++++++++ system-tests/lib/cre/features/sets/sets.go | 2 + system-tests/lib/cre/flags/provider.go | 2 + system-tests/lib/cre/types.go | 3 +- 18 files changed, 384 insertions(+), 72 deletions(-) create mode 100644 core/services/internal/internal.go create mode 100644 core/services/ocr3_1/plugins/queue/config.go create mode 100644 core/services/ocr3_1/plugins/queue/transmitter.go create mode 100644 deployment/cre/jobs/pkg/templates/consensus-queue.tmpl create mode 100644 system-tests/lib/cre/features/queue/queue.go diff --git a/core/scripts/cre/environment/configs/workflow-gateway-capabilities-don.toml b/core/scripts/cre/environment/configs/workflow-gateway-capabilities-don.toml index e9cf7c74544..a885c6e09ab 100644 --- a/core/scripts/cre/environment/configs/workflow-gateway-capabilities-don.toml +++ b/core/scripts/cre/environment/configs/workflow-gateway-capabilities-don.toml @@ -49,7 +49,7 @@ supported_evm_chains = [1337, 2337] env_vars = { CL_EVM_CMD = "", OTEL_SERVICE_NAME = "chainlink-node", CL_CRE_SETTINGS = '{"global":{"PerOrg":{"BaseTriggerRetransmitEnabled":"true"}}}' } - capabilities = ["cron", "http-action", "http-trigger", "consensus", "don-time", "evm-1337"] + capabilities = ["cron", "http-action", "http-trigger", "consensus", "don-time", "evm-1337", "consensus-queue"] registry_based_launch_allowlist = ["cron-trigger@1.0.0", "dontime@1.0.0"] # See ./examples/workflow-don-overrides.toml to learn how to override capability configs diff --git a/core/services/internal/internal.go b/core/services/internal/internal.go new file mode 100644 index 00000000000..7da30869133 --- /dev/null +++ b/core/services/internal/internal.go @@ -0,0 +1,9 @@ +package internal + +import "github.com/smartcontractkit/chainlink-common/pkg/capabilities/actions/vault" + +const ( + ConsensusQueueCapabilityID = "consensus-queue@1.0.0" + DontimeCapabilityID = "dontime@1.0.0" + VaultCapabilityID = vault.CapabilityID +) diff --git a/core/services/ocr2/delegate.go b/core/services/ocr2/delegate.go index 0f3c7cdf358..faa8c5befc5 100644 --- a/core/services/ocr2/delegate.go +++ b/core/services/ocr2/delegate.go @@ -60,6 +60,7 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/config/env" "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/arbiter" + "github.com/smartcontractkit/chainlink/v2/core/services/internal" "github.com/smartcontractkit/chainlink/v2/core/services/job" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/services/llo" @@ -86,17 +87,17 @@ import ( ) const ( - vaultCapabilityID = "vault@1.0.0" + vaultCapabilityID = internal.VaultCapabilityID vaultOCRConfigKey = "vault" dkgOCRConfigKey = "dkg" - dontimeCapabilityID = "dontime@1.0.0" + dontimeCapabilityID = internal.DontimeCapabilityID // dontimeCapabilityPrefix matches any dontime version (e.g. "dontime@2.0.0"), // so the registry-driven launch guard keeps working if the version changes. dontimeCapabilityPrefix = "dontime" gaugeVaultDiskUsageBytes = "platform_vault_disk_usage_bytes" vaultDiskMonitorTickInterval = time.Minute - consensusQueueCapabilityID = "consensus-queue@1.0.0" + consensusQueueCapabilityID = internal.ConsensusQueueCapabilityID consensusQueueOCRConfigKey = "consensus-queue" gaugeConsensusQueueBytes = "platform_consensus_queue_usage_bytes" consensusQueueDiskMonitorTickInterval = time.Minute @@ -798,7 +799,11 @@ func (d *Delegate) newServicesConsensusQueue( ) (srvs []job.ServiceCtx, err error) { spec := jb.OCR2OracleSpec - // TODO ticket validate job spec + cfg := &queue.PluginConfig{} + err = json.Unmarshal(spec.PluginConfig.Bytes(), cfg) + if err != nil { + return nil, fmt.Errorf("failed to unmarshal plugin config: %w", err) + } rid, relayer, err := d.getRelayer(spec) if err != nil { @@ -826,7 +831,7 @@ func (d *Delegate) newServicesConsensusQueue( rid.Network, rid.ChainID, spec.ContractID, - synchronization.TelemetryType(types.VaultPlugin), + synchronization.TelemetryType(types.ConsensusQueue), ) ocrLogger := ocrcommon.NewOCRWrapper(lggr, d.cfg.OCR2().TraceLogging(), func(ctx context.Context, msg string) { @@ -859,7 +864,6 @@ func (d *Delegate) newServicesConsensusQueue( return nil, err } - // Get DKG config tracker and digester, optionally wrapping with OCRConfigService configTracker, configDigester, lc, err := d.maybeWrapConfigService(consensusQueueCapabilityID, consensusQueueOCRConfigKey, lggr, provider.ContractConfigTracker(), provider.OffchainConfigDigester(), lc) if err != nil { return nil, err @@ -869,19 +873,20 @@ func (d *Delegate) newServicesConsensusQueue( BinaryNetworkEndpointFactory: d.peerWrapper.Peer3_1, V2Bootstrappers: bootstrapPeers, ContractConfigTracker: configTracker, - ContractTransmitter: nil, // TODO ticket transmitter - Database: ocrDB, - KeyValueDatabaseFactory: kvFactory, - LocalConfig: lc, - Logger: ocrLogger, - MonitoringEndpoint: oracleEndpoint, - OffchainConfigDigester: configDigester, - OffchainKeyring: kb, - OnchainKeyring: ocr3shims.OnchainKeyringAsOnchainKeyring2(onchainKeyringAdapter), - MetricsRegisterer: prometheus.WrapRegistererWith(map[string]string{"job_name": jb.Name.ValueOrZero()}, prometheus.DefaultRegisterer), + //TODO pass engine as EventSink + ContractTransmitter: queue.NewTransmitter(lggr, ocrtypes.Account(spec.TransmitterID.String), nil), + Database: ocrDB, + KeyValueDatabaseFactory: kvFactory, + LocalConfig: lc, + Logger: ocrLogger, + MonitoringEndpoint: oracleEndpoint, + OffchainConfigDigester: configDigester, + OffchainKeyring: kb, + OnchainKeyring: ocr3shims.OnchainKeyringAsOnchainKeyring2(onchainKeyringAdapter), + 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, cfg, d.limitsFactory) if err != nil { return nil, err } diff --git a/core/services/ocr2/validate/validate.go b/core/services/ocr2/validate/validate.go index 5e2b8668e1a..687e3eb2a11 100644 --- a/core/services/ocr2/validate/validate.go +++ b/core/services/ocr2/validate/validate.go @@ -23,6 +23,7 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/services/job" ringconfig "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/ring/config" "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/vault" + "github.com/smartcontractkit/chainlink/v2/core/services/ocr3_1/plugins/queue" "github.com/smartcontractkit/chainlink/v2/core/services/ocrcommon" "github.com/smartcontractkit/chainlink/v2/core/services/relay" "github.com/smartcontractkit/chainlink/v2/plugins" @@ -122,6 +123,8 @@ func validateSpec(ctx context.Context, tree *toml.Tree, spec job.Job, rc plugins return validateDonTimePluginSpec(spec.OCR2OracleSpec.PluginConfig) case types.RingPlugin: return validateRingPluginSpec(spec.OCR2OracleSpec.PluginConfig) + case types.ConsensusQueue: + return validateConsensusQueuePluginSpec(spec.OCR2OracleSpec.PluginConfig) case "": return errors.New("no plugin specified") default: @@ -323,3 +326,11 @@ func validateOCR2LLOSpec(jsonConfig job.JSONConfig) error { } return pkgerrors.Wrap(pluginConfig.Validate(), "LLO PluginConfig is invalid") } + +func validateConsensusQueuePluginSpec(jsonConfig job.JSONConfig) error { + cfg := &queue.PluginConfig{} + if err := json.Unmarshal(jsonConfig.Bytes(), &cfg); err != nil { + return fmt.Errorf("failed to unmarshal consensus queue plugin config: %w", err) + } + return cfg.Validate() +} diff --git a/core/services/ocr3_1/plugins/queue/config.go b/core/services/ocr3_1/plugins/queue/config.go new file mode 100644 index 00000000000..b63436ca646 --- /dev/null +++ b/core/services/ocr3_1/plugins/queue/config.go @@ -0,0 +1,14 @@ +package queue + +import ( + "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types" +) + +type PluginConfig struct { + Limits ocr3_1types.ReportingPluginLimits `json:"limits,omitzero"` +} + +func (c *PluginConfig) Validate() error { + //TODO validate? + return nil +} diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index 27f76a0a775..73a3b43bf9c 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -2,13 +2,14 @@ package queue import ( "context" - "errors" "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/logger" + "github.com/smartcontractkit/chainlink-common/pkg/services" "github.com/smartcontractkit/chainlink-common/pkg/settings/limits" ) @@ -16,83 +17,87 @@ var _ ocr3_1types.ReportingPluginFactory[[]byte] = &consensusQueuePluginFactory{ type consensusQueuePluginFactory struct { lggr logger.Logger + cfg *PluginConfig } -func NewConsensusQueuePluginFactory(lggr logger.Logger, limitsFactory limits.Factory) (ocr3_1types.ReportingPluginFactory[[]byte], error) { +func NewConsensusQueuePluginFactory(lggr logger.Logger, cfg *PluginConfig, limitsFactory limits.Factory) (ocr3_1types.ReportingPluginFactory[[]byte], error) { // TODO pass CentralTriggerQueue, CapacityReporter, EngineRegistry // TODO construct limiters - return &consensusQueuePluginFactory{lggr: lggr}, nil + return &consensusQueuePluginFactory{lggr: lggr, cfg: cfg}, nil } func (c *consensusQueuePluginFactory) NewReportingPlugin(ctx context.Context, config ocr3types.ReportingPluginConfig, fetcher ocr3_1types.BlobBroadcastFetcher) (ocr3_1types.ReportingPlugin[[]byte], ocr3_1types.ReportingPluginInfo, error) { - plugin := newConsensusQueuePlugin(c.lggr) + plugin := newConsensusQueuePlugin(c.lggr, config) pluginInfo := ocr3_1types.ReportingPluginInfo1{ - Name: "ConsensusQueueReportingPlugin", - Limits: ocr3_1types.ReportingPluginLimits{ - // TODO limits - MaxQueryBytes: 0, - MaxObservationBytes: 0, - MaxReportsPlusPrecursorBytes: 0, - MaxReportBytes: 0, - MaxReportCount: 0, - MaxKeyValueModifiedKeys: 0, - MaxKeyValueModifiedKeysPlusValuesBytes: 0, - MaxBlobPayloadBytes: 0, - MaxPerOracleUnexpiredBlobCumulativePayloadBytes: 0, - MaxPerOracleUnexpiredBlobCount: 0, - }, + Name: "ConsensusQueueReportingPlugin", + Limits: c.cfg.Limits, } - return plugin, pluginInfo, nil + return plugin, pluginInfo, plugin.Start(ctx) } var _ ocr3_1types.ReportingPlugin[[]byte] = &consensusQueuePlugin{} type consensusQueuePlugin struct { - lggr logger.Logger + services.Service + eng *services.Engine + lggr logger.Logger + onchainCfg ocr3types.ReportingPluginConfig } -func newConsensusQueuePlugin(lggr logger.Logger) ocr3_1types.ReportingPlugin[[]byte] { - return &consensusQueuePlugin{lggr: logger.Named(lggr, "ConsensusQueuePlugin")} +func newConsensusQueuePlugin(lggr logger.Logger, onchainCfg ocr3types.ReportingPluginConfig) *consensusQueuePlugin { + c := &consensusQueuePlugin{lggr: logger.Named(lggr, "ConsensusQueuePlugin"), onchainCfg: onchainCfg} + c.Service, c.eng = services.Config{ + Name: "ConsensusQueueReportingPlugin", + Close: c.Close, + }.NewServiceEngine(lggr) + + return c } -func (c *consensusQueuePlugin) Query(ctx context.Context, seqNr uint64, keyValueStateReader ocr3_1types.KeyValueStateReader, blobBroadcastFetcher ocr3_1types.BlobBroadcastFetcher) (ocrtypes.Query, error) { - return nil, errors.ErrUnsupported +func (c *consensusQueuePlugin) Query(_ context.Context, _ uint64, _ ocr3_1types.KeyValueStateReader, _ ocr3_1types.BlobBroadcastFetcher) (ocrtypes.Query, error) { + return nil, nil } -func (c *consensusQueuePlugin) Observation(ctx context.Context, seqNr uint64, aq ocrtypes.AttributedQuery, keyValueStateReader ocr3_1types.KeyValueStateReader, blobBroadcastFetcher ocr3_1types.BlobBroadcastFetcher) (ocrtypes.Observation, error) { - // TODO observe queue via c.CentralTriggerQueue.TakeForObservation() - return nil, errors.ErrUnsupported +func (c *consensusQueuePlugin) Observation( + ctx context.Context, seqNr uint64, _ ocrtypes.AttributedQuery, kvState ocr3_1types.KeyValueStateReader, _ ocr3_1types.BlobBroadcastFetcher, +) (ocrtypes.Observation, error) { + return nil, nil } -func (c *consensusQueuePlugin) ValidateObservation(ctx context.Context, seqNr uint64, aq ocrtypes.AttributedQuery, ao ocrtypes.AttributedObservation, keyValueStateReader ocr3_1types.KeyValueStateReader, blobFetcher ocr3_1types.BlobFetcher) error { - return errors.ErrUnsupported +func (c *consensusQueuePlugin) ValidateObservation( + ctx context.Context, seqNr uint64, _ ocrtypes.AttributedQuery, ao ocrtypes.AttributedObservation, + _ ocr3_1types.KeyValueStateReader, _ ocr3_1types.BlobFetcher, +) error { + //TODO validate + return nil } -func (c *consensusQueuePlugin) ObservationQuorum(ctx context.Context, seqNr uint64, aq ocrtypes.AttributedQuery, aos []ocrtypes.AttributedObservation, keyValueStateReader ocr3_1types.KeyValueStateReader, blobFetcher ocr3_1types.BlobFetcher) (quorumReached bool, err error) { - return false, errors.ErrUnsupported +func (c *consensusQueuePlugin) ObservationQuorum( + ctx context.Context, seqNr 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, keyValueStateReadWriter ocr3_1types.KeyValueStateReadWriter, blobFetcher ocr3_1types.BlobFetcher) (ocr3_1types.ReportsPlusPrecursor, error) { - // TODO write to KV store - return nil, errors.ErrUnsupported +func (c *consensusQueuePlugin) StateTransition( + ctx context.Context, seqNr uint64, aq ocrtypes.AttributedQuery, aos []ocrtypes.AttributedObservation, + kvState ocr3_1types.KeyValueStateReadWriter, _ ocr3_1types.BlobFetcher, +) (ocr3_1types.ReportsPlusPrecursor, error) { + return ocr3_1types.ReportsPlusPrecursor{}, nil } func (c *consensusQueuePlugin) Committed(ctx context.Context, seqNr uint64, keyValueStateReader ocr3_1types.KeyValueStateReader) error { - return nil // no-op + return nil } func (c *consensusQueuePlugin) Reports(ctx context.Context, seqNr uint64, reportsPlusPrecursor ocr3_1types.ReportsPlusPrecursor) ([]ocr3types.ReportPlus[[]byte], error) { - return nil, errors.ErrUnsupported + return nil, nil } func (c *consensusQueuePlugin) ShouldAcceptAttestedReport(ctx context.Context, seqNr uint64, reportWithInfo ocr3types.ReportWithInfo[[]byte]) (bool, error) { - return false, errors.ErrUnsupported + return true, nil } func (c *consensusQueuePlugin) ShouldTransmitAcceptedReport(ctx context.Context, seqNr uint64, reportWithInfo ocr3types.ReportWithInfo[[]byte]) (bool, error) { - return false, errors.ErrUnsupported -} - -func (c *consensusQueuePlugin) Close() error { - return nil + return true, nil } diff --git a/core/services/ocr3_1/plugins/queue/transmitter.go b/core/services/ocr3_1/plugins/queue/transmitter.go new file mode 100644 index 00000000000..69ad7a77d04 --- /dev/null +++ b/core/services/ocr3_1/plugins/queue/transmitter.go @@ -0,0 +1,33 @@ +package queue + +import ( + "context" + + "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types" + ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" + + "github.com/smartcontractkit/chainlink-common/pkg/logger" + "github.com/smartcontractkit/chainlink/v2/core/services/workflows/v2/triggers" +) + +type contractTransmitter struct { + lggr logger.Logger + fromAccount ocrtypes.Account + eventSink triggers.EventSink +} + +func NewTransmitter(lggr logger.Logger, fromAccount ocrtypes.Account, eventSink triggers.EventSink) ocr3types.ContractTransmitter[[]byte] { + return &contractTransmitter{ + lggr: lggr, + fromAccount: fromAccount, + eventSink: eventSink, + } +} + +func (c *contractTransmitter) 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) { + return c.fromAccount, nil +} diff --git a/core/services/workflows/v2/capability_executor.go b/core/services/workflows/v2/capability_executor.go index c290d0095f5..a99de9f579b 100644 --- a/core/services/workflows/v2/capability_executor.go +++ b/core/services/workflows/v2/capability_executor.go @@ -23,6 +23,7 @@ import ( protoevents "github.com/smartcontractkit/chainlink-protos/workflows/go/events" eventsv2 "github.com/smartcontractkit/chainlink-protos/workflows/go/v2" "github.com/smartcontractkit/chainlink/v2/core/platform" + "github.com/smartcontractkit/chainlink/v2/core/services/internal" "github.com/smartcontractkit/chainlink/v2/core/services/workflows/metering" "github.com/smartcontractkit/chainlink/v2/core/services/workflows/store" ) @@ -411,16 +412,13 @@ func (c *ExecutionHelper) EmitUserMetric(ctx context.Context, metric *eventsv2.W return c.base.cfg.EventEmitter.EmitUserMetric(ctx, c.base.eventLabels(), metric) } -// dontimeCapabilityID matches the capability ID registered by the OCR2 delegate -// (core/services/ocr2/delegate.go). -const dontimeCapabilityID = "dontime@1.0.0" - // systemCapabilities lists capability IDs that are internal plumbing and must // not be callable from user workflow steps. var systemCapabilities = map[string]bool{ - confidentialWorkflowsCapabilityID: true, - vaultcommon.CapabilityID: true, - dontimeCapabilityID: true, + confidentialWorkflowsCapabilityID: true, + internal.VaultCapabilityID: true, + internal.DontimeCapabilityID: true, + internal.ConsensusQueueCapabilityID: true, } func isSystemCapability(capID string) bool { diff --git a/core/services/workflows/v2/capability_executor_test.go b/core/services/workflows/v2/capability_executor_test.go index 2ed9173b250..a99e5109b5f 100644 --- a/core/services/workflows/v2/capability_executor_test.go +++ b/core/services/workflows/v2/capability_executor_test.go @@ -14,10 +14,11 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/settings" "github.com/smartcontractkit/chainlink-common/pkg/settings/cresettings" "github.com/smartcontractkit/chainlink-common/pkg/settings/limits" - core "github.com/smartcontractkit/chainlink-common/pkg/types/core" + "github.com/smartcontractkit/chainlink-common/pkg/types/core" "github.com/smartcontractkit/chainlink-protos/cre/go/sdk" eventsv2 "github.com/smartcontractkit/chainlink-protos/workflows/go/v2" "github.com/smartcontractkit/chainlink/v2/core/logger" + "github.com/smartcontractkit/chainlink/v2/core/services/internal" ) func TestExecutionHelper_SystemCapabilityBlocked(t *testing.T) { @@ -157,8 +158,9 @@ func TestIsSystemCapability(t *testing.T) { want bool }{ {"confidential-workflows registered ID", confidentialWorkflowsCapabilityID, true}, - {"vault registered ID", vault.CapabilityID, true}, - {"dontime registered ID", dontimeCapabilityID, true}, + {"vault registered ID", internal.VaultCapabilityID, true}, + {"dontime registered ID", internal.DontimeCapabilityID, true}, + {"consensus queue registered ID", internal.ConsensusQueueCapabilityID, true}, {"confidential-workflows other version", "confidential-workflows@1.0.0", false}, {"vault other version", "vault@2.0.0", false}, {"vault unversioned", "vault", false}, diff --git a/core/services/workflows/v2/triggers/triggers.go b/core/services/workflows/v2/triggers/triggers.go index 74da564ed38..2b04f4a8761 100644 --- a/core/services/workflows/v2/triggers/triggers.go +++ b/core/services/workflows/v2/triggers/triggers.go @@ -12,8 +12,10 @@ import ( "golang.org/x/sync/errgroup" "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/types/known/anypb" + "google.golang.org/protobuf/types/known/timestamppb" "github.com/smartcontractkit/chainlink-common/pkg/capabilities" + "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb" "github.com/smartcontractkit/chainlink-common/pkg/capabilities/registry" "github.com/smartcontractkit/chainlink-common/pkg/contexts" "github.com/smartcontractkit/chainlink-common/pkg/logger" @@ -151,6 +153,29 @@ type CoordinatedEvent struct { 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), + } +} + +func (e *CoordinatedEvent) FromProto(p *pb.CoordinatedEvent) (err error) { + e.WorkflowID = p.WorkflowID + e.TriggerCapID = p.TriggerCapID + 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 +} + // ReadLoop consumes triggerEventCh until it closes or ctx is done, // converting each received capabilities.TriggerResponse into a // CoordinatedEvent and handing it to deliver. diff --git a/deployment/cre/jobs/pkg/templates/consensus-queue.tmpl b/deployment/cre/jobs/pkg/templates/consensus-queue.tmpl new file mode 100644 index 00000000000..9f7d38356d8 --- /dev/null +++ b/deployment/cre/jobs/pkg/templates/consensus-queue.tmpl @@ -0,0 +1,14 @@ +type = "offchainreporting2" +schemaVersion = 1 +externalJobID = "{{ .ExternalJobID }}" +name = "{{ .JobName }}" +contractID = "{{ .ContractID }}" +ocrKeyBundleID = "{{ .OCR2EVMKeyBundleID }}" +p2pv2Bootstrappers = [ +{{ range .P2Pv2Bootstrappers }} "{{ . }}", +{{ end }}] +pluginType = "consensus-queue" +transmitterID = "{{ .TransmitterID }}" +relay = "evm" +[relayConfig] +chainID = "{{ .ChainID }}" diff --git a/deployment/cre/jobs/propose_job_spec_test.go b/deployment/cre/jobs/propose_job_spec_test.go index 8182079d7b5..4d25ebe9f6d 100644 --- a/deployment/cre/jobs/propose_job_spec_test.go +++ b/deployment/cre/jobs/propose_job_spec_test.go @@ -31,6 +31,7 @@ import ( "github.com/smartcontractkit/chainlink/deployment/cre/test" ) +// TODO add a subtest for ConsensusQueue func TestProposeJobSpec_VerifyPreconditions(t *testing.T) { j := jobs.ProposeJobSpec{} var env cldf.Environment @@ -508,6 +509,7 @@ func TestProposeJobSpec_VerifyPreconditions_Aptos(t *testing.T) { } } +// TODO add a subtest for ConsensusQueue func TestProposeJobSpec_Apply(t *testing.T) { h := test.NewTestHarness(t) env := new(h.Runtime.Environment()) diff --git a/system-tests/lib/cre/don.go b/system-tests/lib/cre/don.go index 46d0ed9d43e..585abd6b2e3 100644 --- a/system-tests/lib/cre/don.go +++ b/system-tests/lib/cre/don.go @@ -946,7 +946,7 @@ func HasFlag(values []string, capability string) bool { } for _, value := range values { - if strings.HasPrefix(value, capability+"-") { + if strings.HasPrefix(value, capability+"-") { //TODO collisions? return true } } diff --git a/system-tests/lib/cre/environment/environment.go b/system-tests/lib/cre/environment/environment.go index bcd91e893f2..51e01805129 100644 --- a/system-tests/lib/cre/environment/environment.go +++ b/system-tests/lib/cre/environment/environment.go @@ -288,6 +288,49 @@ func SetupTestEnvironment( // allow to pass custom job spec factories for extensibility jobSpecFactoryFunctions = append(jobSpecFactoryFunctions, input.JobSpecFactoryFunctions...) + // ConsensusQueue + //TODO remove - replaced by feature + //jobSpecFactoryFunctions = append(jobSpecFactoryFunctions, func(input *cre.JobSpecInput) (cre.DonJobs, error) { + // chainID, err := chainselectors.GetChainIDFromSelector(deployedBlockchains.RegistryChain().ChainSelector()) + // if err != nil { + // return nil, fmt.Errorf("failed to get chain ID from selector: %w", err) + // } + // evmChainID, err := strconv.ParseUint(chainID, 10, 64) + // if err != nil { + // return nil, fmt.Errorf("non-integer chain ID: %s: %w", chainID, err) + // } + // + // don := dons.MustWorkflowDON() + // + // bs, ok := dons.Bootstrap() + // if !ok { + // return nil, fmt.Errorf("failed to look up bootstrap node") + // } + // jobConfig := pkg.OCR3JobConfig{ + // JobName: "consensus-queue-test", + // ChainID: chainID, + // ContractID: "0x0000000000000000000000000000000000000000", // TODO + // P2Pv2Bootstrappers: []string{bs.Keys.P2PKey.PeerID.Raw() + "@" + bs.Host + ":" + strconv.Itoa(cre.OCRPeeringPort)}, + // ExternalJobID: uuid.NewV4().String(), // TODO deterministic? + // TemplateName: "consensus-queue", + // } + // + // var donJobs cre.DonJobs + // for _, node := range don.Nodes { + // jobConfig.P2PID = node.PeerID() + // jobConfig.OCR2EVMKeyBundleID = node.Keys.OCR2BundleIDs["evm"] + // jobConfig.TransmitterID = node.Keys.EVM[evmChainID].PublicAddress.String() + // + // jobSpec, err := jobConfig.ResolveJob() + // if err != nil { + // return nil, fmt.Errorf("failed to resolve OCR3 job spec: %w", err) + // } + // nodeID := node.JobDistributorDetails.NodeID + // donJobs = append(donJobs, &job.ProposeJobRequest{NodeId: nodeID, Spec: jobSpec}) + // } + // return donJobs, nil + //}) + createJobsDeps := CreateJobsWithJdOpDeps{ Logger: testLogger, SingleFileLogger: singleFileLogger, diff --git a/system-tests/lib/cre/features/queue/queue.go b/system-tests/lib/cre/features/queue/queue.go new file mode 100644 index 00000000000..eff5f9b3b5e --- /dev/null +++ b/system-tests/lib/cre/features/queue/queue.go @@ -0,0 +1,146 @@ +package queue + +import ( + "context" + "fmt" + "strconv" + + "dario.cat/mergo" + "github.com/google/uuid" + "github.com/pkg/errors" + "github.com/rs/zerolog" + + capabilitiespb "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb" + kcr "github.com/smartcontractkit/chainlink-evm/gethwrappers/keystone/generated/capabilities_registry_1_1_0" + cre_jobs "github.com/smartcontractkit/chainlink/deployment/cre/jobs" + cre_jobs_ops "github.com/smartcontractkit/chainlink/deployment/cre/jobs/operations" + job_types "github.com/smartcontractkit/chainlink/deployment/cre/jobs/types" + "github.com/smartcontractkit/chainlink/deployment/cre/ocr3" + "github.com/smartcontractkit/chainlink/deployment/cre/pkg/offchain" + keystone_changeset "github.com/smartcontractkit/chainlink/deployment/keystone/changeset" + "github.com/smartcontractkit/chainlink/system-tests/lib/cre" + "github.com/smartcontractkit/chainlink/system-tests/lib/cre/contracts" + "github.com/smartcontractkit/chainlink/system-tests/lib/cre/don/jobs" +) + +const flag = cre.ConsensusQueueCapability + +const consensusQueueLabelledName = cre.ConsensusQueueCapability + +type ConsensusQueue struct{} + +func (o *ConsensusQueue) Flag() cre.CapabilityFlag { return flag } +func (o *ConsensusQueue) PreEnvStartup( + ctx context.Context, + testLogger zerolog.Logger, + don *cre.DonMetadata, + topology *cre.Topology, + creEnv *cre.Environment, +) (*cre.PreEnvStartupOutput, error) { + if !don.HasFlag(flag) { + return nil, nil + } + + return &cre.PreEnvStartupOutput{ + DONCapabilityWithConfig: []keystone_changeset.DONCapabilityWithConfig{{ + Capability: kcr.CapabilitiesRegistryCapability{ + LabelledName: consensusQueueLabelledName, + Version: "1.0.0", + CapabilityType: 2, // CONSENSUS + ResponseType: 0, // REPORT (not used) + }, + Config: &capabilitiespb.CapabilityConfig{ + LocalOnly: don.HasOnlyLocalCapabilities(), + }, + UseCapRegOCRConfig: true, + }}, + CapabilityToOCR3Config: map[string]*ocr3.OracleConfig{ + //TODO don't we need DefaultOCR3_1Config? + consensusQueueLabelledName: contracts.DefaultOCR3Config(), + }, + }, nil +} + +func (o *ConsensusQueue) PostEnvStartup( + ctx context.Context, + testLogger zerolog.Logger, + don *cre.Don, + dons *cre.Dons, + creEnv *cre.Environment, +) error { + if !don.HasFlag(flag) { + return nil + } + + err := createJobs(ctx, creEnv, don, dons) + if err != nil { + return fmt.Errorf("failed to create consensusQueue jobs: %w", err) + } + //TODO more? + return nil +} + +func createJobs( + ctx context.Context, + creEnv *cre.Environment, + don *cre.Don, + dons *cre.Dons, +) error { + bootstrap, isBootstrap := dons.Bootstrap() + if !isBootstrap { + return errors.New("could not find bootstrap node in topology, exactly one bootstrap node is required") + } + + peeringCfg, err := cre.PeeringCfgs(bootstrap) + if err != nil { + return errors.Wrap(err, "failed to get peering configs") + } + + input := cre_jobs.ProposeJobSpecInput{ + Domain: offchain.ProductLabel, + Environment: creEnv.CldfEnvironment.Name, + DONName: don.Name, + JobName: cre.ConsensusQueueCapability + "-worker", + ExtraLabels: map[string]string{cre.CapabilityLabelKey: cre.ConsensusQueueCapability}, + DONFilters: []offchain.TargetDONFilter{ + {Key: offchain.FilterKeyDONName, Value: don.Name}, + }, + Template: job_types.OCR3, + Inputs: job_types.JobSpecInput{ + "chainSelectorEVM": creEnv.RegistryChainSelector, + "contractQualifier": cre.ConsensusQueueCapability, + "templateName": cre.ConsensusQueueCapability, + "bootstrapperOCR3Urls": []string{peeringCfg.BootstrapperPeerID + "@" + peeringCfg.BootstrapperHost + ":" + strconv.Itoa(peeringCfg.Port)}, + }, + } + if creEnv.FreshExternalJobIDs { + input.Inputs["externalJobID"] = uuid.NewString() + } + if err := (cre_jobs.ProposeJobSpec{}).VerifyPreconditions(*creEnv.CldfEnvironment, input); err != nil { + return errors.Wrapf(err, "precondition verification failed for %s worker job", flag) + } + + report, err := (cre_jobs.ProposeJobSpec{}).Apply(*creEnv.CldfEnvironment, input) + if err != nil { + return errors.Wrapf(err, "failed to propose %s worker job spec", flag) + } + + // Proposing only queues the spec in Job Distributor; without approval the + // nodes never run it and the capability never registers locally. + specs := make(map[string][]string) + for _, r := range report.Reports { + out, ok := r.Output.(cre_jobs_ops.ProposeOCR3JobOutput) + if !ok { + return fmt.Errorf("unable to cast to ProposeOCR3JobOutput, actual type: %T", r.Output) + } + if mErr := mergo.Merge(&specs, out.Specs, mergo.WithAppendSlice); mErr != nil { + return errors.Wrapf(mErr, "failed to merge %s worker job specs", flag) + } + } + + if aErr := jobs.Approve(ctx, creEnv.CldfEnvironment.Offchain, dons, specs); aErr != nil { + return errors.Wrapf(aErr, "failed to approve %s worker jobs", flag) + } + + return nil +} diff --git a/system-tests/lib/cre/features/sets/sets.go b/system-tests/lib/cre/features/sets/sets.go index 8db4cb51b28..90c4bc8e9e7 100644 --- a/system-tests/lib/cre/features/sets/sets.go +++ b/system-tests/lib/cre/features/sets/sets.go @@ -11,6 +11,7 @@ import ( evm_feature "github.com/smartcontractkit/chainlink/system-tests/lib/cre/features/evm/v2" http_actions_feature "github.com/smartcontractkit/chainlink/system-tests/lib/cre/features/http_action" http_trigger_feature "github.com/smartcontractkit/chainlink/system-tests/lib/cre/features/http_trigger" + consensus_queue_feature "github.com/smartcontractkit/chainlink/system-tests/lib/cre/features/queue" solana_feature "github.com/smartcontractkit/chainlink/system-tests/lib/cre/features/solana/v2" stellar_feature "github.com/smartcontractkit/chainlink/system-tests/lib/cre/features/stellar" vault_feature "github.com/smartcontractkit/chainlink/system-tests/lib/cre/features/vault" @@ -30,5 +31,6 @@ func New() cre.Features { &vault_feature.Vault{}, &confidential_relay_feature.ConfidentialRelay{}, &confidential_workflows_feature.ConfidentialWorkflows{}, + &consensus_queue_feature.ConsensusQueue{}, ) } diff --git a/system-tests/lib/cre/flags/provider.go b/system-tests/lib/cre/flags/provider.go index e045aef025d..635af1e0021 100644 --- a/system-tests/lib/cre/flags/provider.go +++ b/system-tests/lib/cre/flags/provider.go @@ -21,6 +21,7 @@ func NewDefaultCapabilityFlagsProvider() *DefaultCapbilityFlagsProvider { cre.StellarCapability, cre.ConfidentialRelayCapability, cre.ConfidentialWorkflowsCapability, + cre.ConsensusQueueCapability, }, } } @@ -44,6 +45,7 @@ func NewExtensibleCapabilityFlagsProvider(extraGlobalFlags []string) *Extensible cre.HTTPActionCapability, cre.ConfidentialRelayCapability, cre.ConfidentialWorkflowsCapability, + cre.ConsensusQueueCapability, }, extraGlobalFlags...), chainSpecificCapabilities: []cre.CapabilityFlag{ cre.EVMCapability, diff --git a/system-tests/lib/cre/types.go b/system-tests/lib/cre/types.go index ae28fa68b2a..156befa9d2c 100644 --- a/system-tests/lib/cre/types.go +++ b/system-tests/lib/cre/types.go @@ -66,6 +66,7 @@ const ( ConfidentialRelayCapability CapabilityFlag = "confidential-relay" // ConfidentialWorkflowsCapability doubles as the enclave application name. ConfidentialWorkflowsCapability CapabilityFlag = "confidential-workflows" + ConsensusQueueCapability CapabilityFlag = "consensus-queue" AptosCapability CapabilityFlag = "aptos" StellarCapability CapabilityFlag = "stellar" // Add more capabilities as needed @@ -777,7 +778,7 @@ func (m *DonMetadata) StellarChains() []string { func (m *DonMetadata) RequiresOCR() bool { return slices.Contains(m.Flags, ConsensusCapability) || - slices.Contains(m.Flags, VaultCapability) || slices.Contains(m.Flags, EVMCapability) || slices.Contains(m.Flags, SolanaCapability) + slices.Contains(m.Flags, VaultCapability) || slices.Contains(m.Flags, ConsensusQueueCapability) || slices.Contains(m.Flags, EVMCapability) || slices.Contains(m.Flags, SolanaCapability) } func (m *DonMetadata) RequiresGateway() bool { From a2b6326bffc56988f50a7404eea65f0693d774ad Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Thu, 29 Oct 2026 07:08:19 -0500 Subject: [PATCH 02/38] core/services/ocr3_1/plugins/queue: ReportingPlugin implementation --- core/scripts/go.mod | 2 +- core/scripts/go.sum | 4 +- core/services/ocr3_1/plugins/queue/kvstate.go | 103 +++++++++++ core/services/ocr3_1/plugins/queue/queue.go | 175 +++++++++++++++++- .../ocr3_1/plugins/queue/transmitter.go | 26 +++ deployment/go.mod | 2 +- deployment/go.sum | 4 +- go.mod | 2 +- go.sum | 4 +- integration-tests/go.mod | 2 +- integration-tests/go.sum | 4 +- integration-tests/load/go.mod | 2 +- integration-tests/load/go.sum | 4 +- system-tests/lib/go.mod | 2 +- system-tests/lib/go.sum | 4 +- system-tests/tests/go.mod | 2 +- system-tests/tests/go.sum | 4 +- 17 files changed, 324 insertions(+), 22 deletions(-) create mode 100644 core/services/ocr3_1/plugins/queue/kvstate.go diff --git a/core/scripts/go.mod b/core/scripts/go.mod index 06e0341d330..433daf2ab63 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.20261020093734-0127cb4d6ae5 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261022195454-600e2b321c7a diff --git a/core/scripts/go.sum b/core/scripts/go.sum index a7b2fc3f3af..d09e43690ea 100644 --- a/core/scripts/go.sum +++ b/core/scripts/go.sum @@ -1686,8 +1686,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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261020093734-0127cb4d6ae5 h1:mpb2dy2Cr3/J3d09u5L0vjOeA4SVPvk2VZcuOEWUopY= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261020093734-0127cb4d6ae5/go.mod h1:QeHe1mlcVzzg+awYAkRfl/8mDLRAhsl18IIOg4MVZec= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d h1:PmhBu41LVNATLXKNX+bzuRShPexHj2H4Ryi4HH1VBbc= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d/go.mod h1:ZRHl1hjJyTPrnv669e3thza3U7Z2as5zKCDZP0kJXuw= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= 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..39175f4bce3 --- /dev/null +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -0,0 +1,103 @@ +package queue + +import ( + "cmp" + "container/heap" + + "google.golang.org/protobuf/proto" + + "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types" + + "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb" +) + +// KV store Keys +const ( + proposedEventsKey = "proposed_events::index" // proposed events waiting for consensus ( maxObservationSize { // too large, end of batch + // remove this one + obs.Events = obs.Events[:len(obs.Events)-1] + if addedCap { + delete(obs.WorkflowCapacities, id) + } + break + } + } + return protoOpts.Marshal(obs) } func (c *consensusQueuePlugin) ValidateObservation( @@ -83,13 +127,142 @@ func (c *consensusQueuePlugin) StateTransition( ctx context.Context, seqNr uint64, aq ocrtypes.AttributedQuery, aos []ocrtypes.AttributedObservation, kvState ocr3_1types.KeyValueStateReadWriter, _ ocr3_1types.BlobFetcher, ) (ocr3_1types.ReportsPlusPrecursor, error) { + var wg sync.WaitGroup + + // TODO In parallel: + var capacity int + var wfCapacity map[string]int + var observedProposals map[string][]uint8 // trigger event ID -> observer node IDs + var observedEvents map[string]*pb.CoordinatedEvent // trigger event ID -> event + go func() { + defer wg.Done() + + // - Aggregate each node’s view of how many trigger events we can pop from the KV store queue (i.e. how many executions we can start) + // - Aggregate the per workflow free capacity + // - Achieve quorum on observations -> any item with F+1 observations goes into the queue + // - Medianize the logical clock value in the observations to order events + }() + + // Deserialize the KV store into memory + state := newStateReadWriter(kvState) + proposedEvents, err := state.readProposedEvents() + if err != nil { + return nil, err + } + priorityQueue, err := state.readPriorityQueue() + if err != nil { + return nil, err + } + heap.Init(&priorityQueue) //TODO or can we trust it? + + //TODO prune expired events from proposed and priorityQueue + + wg.Wait() + + // Collect observed proposals and promote to priority queue on f+1 + for id, nodes := range observedProposals { + if obs, ok := proposedEvents.Observers[id]; !ok && len(nodes) >= c.onchainCfg.F+1 { + // new proposal straight to priority queue + heap.Push(&priorityQueue, proposedEvents.Events[id]) + continue + } else if !ok { + // new proposal < f + 1 + proposedEvents.Observers[id] = &pb.NodeIDList{Ids: nodes} + proposedEvents.Events[id] = observedEvents[id] + continue + } else if len(nodes) < c.onchainCfg.F+1 { + // update proposal + // TODO opt: build a map to avoid n^2? or nbd since n < f+1 + for _, node := range nodes { + if !slices.Contains(obs.Ids, node) { + obs.Ids = append(obs.Ids, node) + } + } + if len(obs.Ids) < c.onchainCfg.F+1 { + continue + } + } + // f+1 - promote proposal to priority queue + delete(proposedEvents.Observers, id) + delete(proposedEvents.Events, id) + heap.Push(&priorityQueue, proposedEvents.Events[id]) + } + + // Select items from queue based on priority and capacity + var consensusEvents []*pb.CoordinatedEvent + var workflowLimited []*pb.CoordinatedEvent // omitted due to workflow limit + for len(consensusEvents) < capacity { + if len(priorityQueue) == 0 { + break + } + next, ok := heap.Pop(&priorityQueue).(*pb.CoordinatedEvent) + if !ok { + return nil, fmt.Errorf("failed to cast *pb.CoordinatedEvent: got type %T", next) + } + if wfCapacity[next.WorkflowID] == 0 { + workflowLimited = append(workflowLimited, next) + continue + } + wfCapacity[next.WorkflowID]-- + consensusEvents = append(consensusEvents, next) + } + // restore omitted for next time + for _, event := range workflowLimited { + heap.Push(&priorityQueue, event) + } + + // Updated KV Store + err = state.writeProposedEvents(proposedEvents) + if err != nil { + return nil, err + } + err = state.writePriorityQueue(priorityQueue) + if err != nil { + return nil, err + } + err = state.writeConsensusEvents(&pb.CoordinatedEventList{Events: consensusEvents}) + if err != nil { + return nil, err + } + + // no report to return, executions start when committed return ocr3_1types.ReportsPlusPrecursor{}, nil } func (c *consensusQueuePlugin) Committed(ctx context.Context, seqNr uint64, keyValueStateReader ocr3_1types.KeyValueStateReader) error { + c.tryStartExecutions(keyValueStateReader) return 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(reader ocr3_1types.KeyValueStateReader) { + state := stateReader{reader} + pbs, err := state.readConsensusEvents() + if err != nil { + //TODO log? + return + } + errs := make([]error, len(pbs.Events)) + var wg sync.WaitGroup + for i, pbEvent := range pbs.Events { + var event triggers.CoordinatedEvent + if err := event.FromProto(pbEvent); err != nil { + errs[i] = fmt.Errorf("failed to unmarshal event: %s: %w", pbEvent, err) + continue + } + wg.Add(1) + c.eng.Go(func(ctx context.Context) { + defer wg.Done() + // TODO fetch workflow engine instance + // TODO execute StartExecution + errs[i] = nil + }) + } + wg.Wait() + //TODO process errors? or just log as we go? +} + func (c *consensusQueuePlugin) Reports(ctx context.Context, seqNr uint64, reportsPlusPrecursor ocr3_1types.ReportsPlusPrecursor) ([]ocr3types.ReportPlus[[]byte], error) { return nil, nil } diff --git a/core/services/ocr3_1/plugins/queue/transmitter.go b/core/services/ocr3_1/plugins/queue/transmitter.go index 69ad7a77d04..42c3ddeae95 100644 --- a/core/services/ocr3_1/plugins/queue/transmitter.go +++ b/core/services/ocr3_1/plugins/queue/transmitter.go @@ -2,10 +2,13 @@ package queue import ( "context" + "fmt" "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" + "google.golang.org/protobuf/proto" + "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb" "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink/v2/core/services/workflows/v2/triggers" ) @@ -25,6 +28,29 @@ func NewTransmitter(lggr logger.Logger, fromAccount ocrtypes.Account, eventSink } func (c *contractTransmitter) Transmit(ctx context.Context, digest ocrtypes.ConfigDigest, seqNum uint64, rpi ocr3types.ReportWithInfo[[]byte], signatures []ocrtypes.AttributedOnchainSignature) error { + //TODO relocate & replace with no-op? + var report pb.CoordinatedEventList + err := proto.Unmarshal(rpi.Report, &report) + if err != nil { + return fmt.Errorf("failed to unmarshal report: %w", err) + } + // Execute each event + for _, message := range report.Events { + var event triggers.CoordinatedEvent + if err := event.FromProto(message); err != nil { + c.lggr.Errorw("Failed to convert trigger event proto", "err", err) + continue + } + if c.eventSink == nil { + c.lggr.Warnw("Unable to execute trigger - no event sink configured", "event", event) + continue + } + err := c.eventSink.ExecuteTrigger(ctx, event) + if err != nil { + c.lggr.Errorw("Failed to execute trigger", "event", event, "err", err) + } + } + return nil } diff --git a/deployment/go.mod b/deployment/go.mod index aad81685f37..2d3cfc9be94 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-20260916222901-720a003dab50 github.com/smartcontractkit/chainlink-ccip/deployment v0.0.0-20261001213322-a2d686f610ca - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261020093734-0127cb4d6ae5 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd github.com/smartcontractkit/chainlink-data-streams v1.1.2-0.20261009064810-68424c714170 github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 diff --git a/deployment/go.sum b/deployment/go.sum index 84a162998f0..7c18de10579 100644 --- a/deployment/go.sum +++ b/deployment/go.sum @@ -1411,8 +1411,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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261020093734-0127cb4d6ae5 h1:mpb2dy2Cr3/J3d09u5L0vjOeA4SVPvk2VZcuOEWUopY= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261020093734-0127cb4d6ae5/go.mod h1:QeHe1mlcVzzg+awYAkRfl/8mDLRAhsl18IIOg4MVZec= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d h1:PmhBu41LVNATLXKNX+bzuRShPexHj2H4Ryi4HH1VBbc= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d/go.mod h1:ZRHl1hjJyTPrnv669e3thza3U7Z2as5zKCDZP0kJXuw= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= diff --git a/go.mod b/go.mod index 7e8aca189bc..1ad05c537a6 100644 --- a/go.mod +++ b/go.mod @@ -82,7 +82,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.15.1-0.20261020204039-1a47492cdb37 - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261020093734-0127cb4d6ae5 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260903141829-ef07b52a737d github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 github.com/smartcontractkit/chainlink-data-streams v1.1.2-0.20261009064810-68424c714170 diff --git a/go.sum b/go.sum index 349c3b414ac..356fa153750 100644 --- a/go.sum +++ b/go.sum @@ -1104,8 +1104,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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261020093734-0127cb4d6ae5 h1:mpb2dy2Cr3/J3d09u5L0vjOeA4SVPvk2VZcuOEWUopY= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261020093734-0127cb4d6ae5/go.mod h1:QeHe1mlcVzzg+awYAkRfl/8mDLRAhsl18IIOg4MVZec= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d h1:PmhBu41LVNATLXKNX+bzuRShPexHj2H4Ryi4HH1VBbc= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d/go.mod h1:ZRHl1hjJyTPrnv669e3thza3U7Z2as5zKCDZP0kJXuw= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260903141829-ef07b52a737d h1:M9xuiIvdiHtim4nlxCVajyC/Mk63tAg9ESWb/biAhNA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260903141829-ef07b52a737d/go.mod h1:rI2njmTlyTvh+xhmORmK6qX3+V1ycDAqGJLu8LS8WpU= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= diff --git a/integration-tests/go.mod b/integration-tests/go.mod index 9a70720706c..2001d2f6a45 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-20260916222901-720a003dab50 github.com/smartcontractkit/chainlink-ccip/chains/solana/gobindings v0.0.0-20260916222901-720a003dab50 - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261020093734-0127cb4d6ae5 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261022195454-600e2b321c7a diff --git a/integration-tests/go.sum b/integration-tests/go.sum index 2aa7365670c..a8818091a1e 100644 --- a/integration-tests/go.sum +++ b/integration-tests/go.sum @@ -1396,8 +1396,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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261020093734-0127cb4d6ae5 h1:mpb2dy2Cr3/J3d09u5L0vjOeA4SVPvk2VZcuOEWUopY= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261020093734-0127cb4d6ae5/go.mod h1:QeHe1mlcVzzg+awYAkRfl/8mDLRAhsl18IIOg4MVZec= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d h1:PmhBu41LVNATLXKNX+bzuRShPexHj2H4Ryi4HH1VBbc= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d/go.mod h1:ZRHl1hjJyTPrnv669e3thza3U7Z2as5zKCDZP0kJXuw= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= diff --git a/integration-tests/load/go.mod b/integration-tests/load/go.mod index fc6d035f840..2094bc06a45 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-20260916222901-720a003dab50 github.com/smartcontractkit/chainlink-ccip/chains/solana/gobindings v0.0.0-20260916222901-720a003dab50 - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261020093734-0127cb4d6ae5 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261022195454-600e2b321c7a 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 6bb93b929ad..c1fdd13aa85 100644 --- a/integration-tests/load/go.sum +++ b/integration-tests/load/go.sum @@ -1636,8 +1636,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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261020093734-0127cb4d6ae5 h1:mpb2dy2Cr3/J3d09u5L0vjOeA4SVPvk2VZcuOEWUopY= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261020093734-0127cb4d6ae5/go.mod h1:QeHe1mlcVzzg+awYAkRfl/8mDLRAhsl18IIOg4MVZec= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d h1:PmhBu41LVNATLXKNX+bzuRShPexHj2H4Ryi4HH1VBbc= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d/go.mod h1:ZRHl1hjJyTPrnv669e3thza3U7Z2as5zKCDZP0kJXuw= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= diff --git a/system-tests/lib/go.mod b/system-tests/lib/go.mod index 4c6466ddef2..670ac65dd03 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-20260916222901-720a003dab50 - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261020093734-0127cb4d6ae5 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd 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 957b3b0f077..533893e83bf 100644 --- a/system-tests/lib/go.sum +++ b/system-tests/lib/go.sum @@ -1657,8 +1657,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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261020093734-0127cb4d6ae5 h1:mpb2dy2Cr3/J3d09u5L0vjOeA4SVPvk2VZcuOEWUopY= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261020093734-0127cb4d6ae5/go.mod h1:QeHe1mlcVzzg+awYAkRfl/8mDLRAhsl18IIOg4MVZec= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d h1:PmhBu41LVNATLXKNX+bzuRShPexHj2H4Ryi4HH1VBbc= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d/go.mod h1:ZRHl1hjJyTPrnv669e3thza3U7Z2as5zKCDZP0kJXuw= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= diff --git a/system-tests/tests/go.mod b/system-tests/tests/go.mod index 391187922bb..e24d08d9de5 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-20260916222901-720a003dab50 - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261020093734-0127cb4d6ae5 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 github.com/smartcontractkit/chainlink-confidential-compute v1.3.0 diff --git a/system-tests/tests/go.sum b/system-tests/tests/go.sum index 6eb14ec54a0..063fffac0ae 100644 --- a/system-tests/tests/go.sum +++ b/system-tests/tests/go.sum @@ -1836,8 +1836,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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261020093734-0127cb4d6ae5 h1:mpb2dy2Cr3/J3d09u5L0vjOeA4SVPvk2VZcuOEWUopY= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261020093734-0127cb4d6ae5/go.mod h1:QeHe1mlcVzzg+awYAkRfl/8mDLRAhsl18IIOg4MVZec= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d h1:PmhBu41LVNATLXKNX+bzuRShPexHj2H4Ryi4HH1VBbc= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d/go.mod h1:ZRHl1hjJyTPrnv669e3thza3U7Z2as5zKCDZP0kJXuw= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= From 8e8882484a5c2d5108efca0b1fc114ebdcb99b69 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Fri, 30 Oct 2026 09:00:43 -0500 Subject: [PATCH 03/38] inject triggers.Coordinator; implement more StateTransition --- core/services/chainlink/application.go | 1 + core/services/cre/cre.go | 43 ++++--- core/services/ocr2/delegate.go | 6 +- core/services/ocr3_1/plugins/queue/queue.go | 132 +++++++++++++------- 4 files changed, 117 insertions(+), 65 deletions(-) diff --git a/core/services/chainlink/application.go b/core/services/chainlink/application.go index 3b3f4cadaa3..a5b915678f8 100644 --- a/core/services/chainlink/application.go +++ b/core/services/chainlink/application.go @@ -820,6 +820,7 @@ func NewApplication(ctx context.Context, opts ApplicationOpts) (Application, err OrgResolver: creServices.OrgResolver, LimitsFactory: limitsFactory, OCRConfigService: creServices.OCRConfigService, + TriggerCoordinator: creServices.TriggerCoordinator, DefaultBootstrappers: safeDefaultBootstrappers(cfg), CapRegistryAddress: safeExternalRegistryAddress(cfg), CapRegistryChainID: safeExternalRegistryChainID(cfg), diff --git a/core/services/cre/cre.go b/core/services/cre/cre.go index 8574312e4d4..566d45126d9 100644 --- a/core/services/cre/cre.go +++ b/core/services/cre/cre.go @@ -134,6 +134,8 @@ type Services struct { WorkflowRegistrySyncer syncerV2.WorkflowRegistrySyncer + TriggerCoordinator triggers.Coordinator + OrgResolver orgresolver.OrgResolver OCRConfigService capregconfig.OCRConfigService @@ -280,7 +282,7 @@ func (s *Services) newSubservices( // the handler resolves the workflow DON id later from the don notifier. meterIdentity := newSyncerMeterIdentity(cfg) - wfSyncer, billingClient, wfSyncerSrvcs, err := newWorkflowRegistrySyncer( + wfSyncer, triggerCoordinator, billingClient, wfSyncerSrvcs, err := newWorkflowRegistrySyncer( cfg, relayerChainInterops, opts, @@ -302,6 +304,7 @@ func (s *Services) newSubservices( } s.BillingClient = billingClient s.WorkflowRegistrySyncer = wfSyncer + s.TriggerCoordinator = triggerCoordinator srvs = append(srvs, wfSyncerSrvcs...) return srvs, nil @@ -866,14 +869,14 @@ func newWorkflowRegistrySyncerV2( meterIdentity resourcemanager.ResourceIdentity, dispatcher remotetypes.Dispatcher, shardIndexMapper *shardownership.ShardIndexMapper, -) (syncerV2.WorkflowRegistrySyncer, []commonsrv.Service, error) { +) (syncerV2.WorkflowRegistrySyncer, triggers.Coordinator, []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, err } artifactsStore, err := artifactsV2.NewStore( @@ -890,29 +893,29 @@ func newWorkflowRegistrySyncerV2( }), ) if err != nil { - return nil, nil, fmt.Errorf("unable to create artifact store: %w", err) + return 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, 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, 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, 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, fmt.Errorf("failed to instantiate contract reader factory: %w", err) } var shardOrchestratorClient shardorchestrator.ClientInterface @@ -921,7 +924,7 @@ func newWorkflowRegistrySyncerV2( } else { c, clientErr := newShardOrchestratorClient(cfg, lggr) if clientErr != nil { - return nil, nil, clientErr + return nil, nil, nil, clientErr } if c != nil { shardOrchestratorClient = c @@ -968,7 +971,7 @@ 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, fmt.Errorf("unable to init trigger coordinator metrics: %w", err) } triggerCoordinator := triggers.NewCoordinator( triggers.RegisterDeps{ @@ -1018,7 +1021,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, fmt.Errorf("unable to create workflow spec meter: %w", smErr) } handlerOpts = append(handlerOpts, syncerV2.WithSpecMeter(specMeter)) } @@ -1039,7 +1042,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, fmt.Errorf("unable to create file module store: %w", fsErr) } if diskMonitorEnabled { @@ -1049,7 +1052,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, fmt.Errorf("unable to create module cache disk monitor: %w", dmErr) } srvcs = append(srvcs, dm) @@ -1059,7 +1062,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, fmt.Errorf("unable to create module cache metrics: %w", cmErr) } var idleTimeout time.Duration @@ -1109,7 +1112,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, fmt.Errorf("unable to create workflow registry event handler: %w", err) } addSources := wfReg.AdditionalSources() @@ -1162,12 +1165,12 @@ func newWorkflowRegistrySyncerV2( registryOpts..., ) if err != nil { - return nil, nil, fmt.Errorf("unable to create workflow registry syncer: %w", err) + return 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, srvcs, nil } // newWorkflowRegistrySyncer creates a workflow registry syncer. @@ -1187,7 +1190,7 @@ func newWorkflowRegistrySyncer( meterIdentity resourcemanager.ResourceIdentity, dispatcher remotetypes.Dispatcher, shardIndexMapper *shardownership.ShardIndexMapper, -) (syncerV2.WorkflowRegistrySyncer, metering.BillingClient, []commonsrv.Service, error) { +) (syncerV2.WorkflowRegistrySyncer, triggers.Coordinator, metering.BillingClient, []commonsrv.Service, error) { lggr.Debugw("Creating WorkflowRegistrySyncer") lggr = logger.Named(lggr, "WorkflowRegistrySyncer") @@ -1196,7 +1199,7 @@ func newWorkflowRegistrySyncer( lggr.Infof("failed to create billing client: %s", err) } - syncer, srvcs, err := newWorkflowRegistrySyncerV2( + syncer, triggerCoordinator, srvcs, err := newWorkflowRegistrySyncerV2( cfg, relayerChainInterops, billingClient, @@ -1214,7 +1217,7 @@ func newWorkflowRegistrySyncer( dispatcher, shardIndexMapper, ) - return syncer, billingClient, srvcs, err + return syncer, triggerCoordinator, billingClient, srvcs, err } // NewServices creates and initializes all CRE services diff --git a/core/services/ocr2/delegate.go b/core/services/ocr2/delegate.go index faa8c5befc5..fd6aaf65896 100644 --- a/core/services/ocr2/delegate.go +++ b/core/services/ocr2/delegate.go @@ -82,6 +82,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" ) @@ -157,6 +158,7 @@ type Delegate struct { OrgResolver orgresolver.OrgResolver limitsFactory limits.Factory ocrConfigService capregconfig.OCRConfigService + triggerCoordinator triggers.Coordinator // Registry-driven launch support: when the delegate is used via // LocalCapabilityManager (no job spec), these fields provide the @@ -297,6 +299,7 @@ type DelegateOpts struct { OrgResolver orgresolver.OrgResolver LimitsFactory limits.Factory OCRConfigService capregconfig.OCRConfigService + TriggerCoordinator triggers.Coordinator // Registry-driven launch support: defaults for capabilities launched // via LocalCapabilityManager (no job spec). @@ -339,6 +342,7 @@ func NewDelegate( OrgResolver: opts.OrgResolver, limitsFactory: opts.LimitsFactory, ocrConfigService: opts.OCRConfigService, + triggerCoordinator: opts.TriggerCoordinator, defaultBootstrappers: opts.DefaultBootstrappers, capRegistryAddress: opts.CapRegistryAddress, capRegistryChainID: opts.CapRegistryChainID, @@ -886,7 +890,7 @@ func (d *Delegate) newServicesConsensusQueue( MetricsRegisterer: prometheus.WrapRegistererWith(map[string]string{"job_name": jb.Name.ValueOrZero()}, prometheus.DefaultRegisterer), } - rpf, err := queue.NewConsensusQueuePluginFactory(lggr, cfg, d.limitsFactory) + rpf, err := queue.NewConsensusQueuePluginFactory(lggr, cfg, d.limitsFactory, d.triggerCoordinator) if err != nil { return nil, err } diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index 24dfa624ba4..21e3275a0bd 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -4,9 +4,11 @@ import ( "container/heap" "context" "fmt" + "math" "slices" "sync" + "golang.org/x/exp/constraints" "google.golang.org/protobuf/proto" "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types" @@ -25,18 +27,19 @@ import ( var _ ocr3_1types.ReportingPluginFactory[[]byte] = &consensusQueuePluginFactory{} type consensusQueuePluginFactory struct { - lggr logger.Logger - cfg *PluginConfig + lggr logger.Logger + cfg *PluginConfig + triggerCoordinator triggers.Coordinator } -func NewConsensusQueuePluginFactory(lggr logger.Logger, cfg *PluginConfig, limitsFactory limits.Factory) (ocr3_1types.ReportingPluginFactory[[]byte], error) { - // TODO pass CentralTriggerQueue, CapacityReporter, EngineRegistry +func NewConsensusQueuePluginFactory(lggr logger.Logger, cfg *PluginConfig, limitsFactory limits.Factory, triggerCoordinator triggers.Coordinator) (ocr3_1types.ReportingPluginFactory[[]byte], error) { + // TODO inject CapacityReporter // TODO construct limiters - return &consensusQueuePluginFactory{lggr: lggr, cfg: cfg}, nil + return &consensusQueuePluginFactory{lggr: lggr, cfg: cfg, triggerCoordinator: triggerCoordinator}, nil } func (c *consensusQueuePluginFactory) NewReportingPlugin(ctx context.Context, config ocr3types.ReportingPluginConfig, fetcher ocr3_1types.BlobBroadcastFetcher) (ocr3_1types.ReportingPlugin[[]byte], ocr3_1types.ReportingPluginInfo, error) { - plugin := newConsensusQueuePlugin(c.lggr, config) + plugin := newConsensusQueuePlugin(c.lggr, config, c.triggerCoordinator) pluginInfo := ocr3_1types.ReportingPluginInfo1{ Name: "ConsensusQueueReportingPlugin", Limits: c.cfg.Limits, @@ -48,13 +51,18 @@ 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 + triggerCoordinator triggers.Coordinator } -func newConsensusQueuePlugin(lggr logger.Logger, onchainCfg ocr3types.ReportingPluginConfig) *consensusQueuePlugin { - c := &consensusQueuePlugin{lggr: logger.Named(lggr, "ConsensusQueuePlugin"), onchainCfg: onchainCfg} +func newConsensusQueuePlugin(lggr logger.Logger, onchainCfg ocr3types.ReportingPluginConfig, triggerCoordinator triggers.Coordinator) *consensusQueuePlugin { + c := &consensusQueuePlugin{ + lggr: logger.Named(lggr, "ConsensusQueuePlugin"), + onchainCfg: onchainCfg, + triggerCoordinator: triggerCoordinator, + } c.Service, c.eng = services.Config{ Name: "ConsensusQueueReportingPlugin", Close: c.Close, @@ -74,30 +82,40 @@ func (c *consensusQueuePlugin) Observation( // tryStartExecutions is idempotent. c.tryStartExecutions(kvState) - // TODO Fetch limits from node + capacity, err := c.triggerCoordinator.AvailableCapacity(ctx) + if err != nil { + //TODO or just log and make a best effort to observe events regardless? + return nil, fmt.Errorf("failed to get available capacity: %w", err) + } // Build Observation var events []triggers.CoordinatedEvent // TODO observe queue via c.CentralTriggerQueue.TakeForObservation()... one at at time? obs := &pb.ConsensusQueueObservation{ Events: make([]*pb.CoordinatedEvent, 0, len(events)), - Capacity: 0, //TODO set - WorkflowCapacities: nil, //TODO for everything proposed and queued in the KV store? + Capacity: uint32(min(capacity.Global, math.MaxUint32)), + WorkflowCapacities: make(map[string]uint32), + } + for wf, c := range capacity.PerWorkflow { + //TODO only for events proposed and queued in the KV store? + obs.WorkflowCapacities[wf] = uint32(min(c, math.MaxUint32)) } const maxObservationSize = 0 //TODO protoOpts := proto.MarshalOptions{Deterministic: true} for _, e := range events { m := e.ToProto() + // Try adding to batch obs.Events = append(obs.Events, m) id := e.Event.Event.ID var addedCap bool - if _, ok := obs.WorkflowCapacities[id]; !ok { + if _, ok := obs.WorkflowCapacities[e.WorkflowID]; !ok { addedCap = true - //TODO set it + obs.WorkflowCapacities[e.WorkflowID] = uint32(min(capacity.PerWorkflow[e.WorkflowID], math.MaxUint32)) } - if protoOpts.Size(obs) > maxObservationSize { // too large, end of batch - // remove this one + // Check size + if protoOpts.Size(obs) > maxObservationSize { + // too large, remove this one obs.Events = obs.Events[:len(obs.Events)-1] if addedCap { delete(obs.WorkflowCapacities, id) @@ -112,7 +130,11 @@ func (c *consensusQueuePlugin) ValidateObservation( ctx context.Context, seqNr uint64, _ ocrtypes.AttributedQuery, ao ocrtypes.AttributedObservation, _ ocr3_1types.KeyValueStateReader, _ ocr3_1types.BlobFetcher, ) error { - //TODO validate + var obs pb.ConsensusQueueObservation + err := proto.Unmarshal(ao.Observation, &obs) + if err != nil { + return fmt.Errorf("failed to unmarshal observation: %w", err) + } return nil } @@ -129,18 +151,36 @@ func (c *consensusQueuePlugin) StateTransition( ) (ocr3_1types.ReportsPlusPrecursor, error) { var wg sync.WaitGroup - // TODO In parallel: - var capacity int - var wfCapacity map[string]int - var observedProposals map[string][]uint8 // trigger event ID -> observer node IDs + //TODO is median only logical option for capacity? what if honest nodes have less, don't we ideally want execute min(honest)? + var medianCap uint32 + var medianCapPerWF map[string]uint32 // wf ID -> capacity + var observedProposals map[string][]uint8 // trigger event ID -> observer OracleIDs var observedEvents map[string]*pb.CoordinatedEvent // trigger event ID -> event go func() { defer wg.Done() - // - Aggregate each node’s view of how many trigger events we can pop from the KV store queue (i.e. how many executions we can start) - // - Aggregate the per workflow free capacity - // - Achieve quorum on observations -> any item with F+1 observations goes into the queue - // - Medianize the logical clock value in the observations to order events + capacities := make([]uint32, 0, len(aos)) + wfCapacities := make(map[string][]uint32) + for _, ao := range aos { + var obs pb.ConsensusQueueObservation + err := proto.Unmarshal(ao.Observation, &obs) + if err != nil { + c.lggr.Errorw("Failed to unmarshal observation", "err", err) + continue + } + capacities = append(capacities, obs.Capacity) + for wf, c := range obs.WorkflowCapacities { + wfCapacities[wf] = append(wfCapacities[wf], c) + } + for _, event := range obs.Events { + observedProposals[event.Event.Event.Id] = append(observedProposals[event.Event.Event.Id], uint8(ao.Observer)) + observedEvents[event.Event.Event.Id] = event //TODO last value is not sufficient - must handle disagreement + } + } + medianCap = median(capacities) + for wf, c := range wfCapacities { + medianCapPerWF[wf] = median(c) + } }() // Deserialize the KV store into memory @@ -157,7 +197,7 @@ func (c *consensusQueuePlugin) StateTransition( //TODO prune expired events from proposed and priorityQueue - wg.Wait() + wg.Wait() // TODO also wait if we return early for error // Collect observed proposals and promote to priority queue on f+1 for id, nodes := range observedProposals { @@ -191,7 +231,7 @@ func (c *consensusQueuePlugin) StateTransition( // Select items from queue based on priority and capacity var consensusEvents []*pb.CoordinatedEvent var workflowLimited []*pb.CoordinatedEvent // omitted due to workflow limit - for len(consensusEvents) < capacity { + for len(consensusEvents) < int(medianCap) { if len(priorityQueue) == 0 { break } @@ -199,11 +239,11 @@ func (c *consensusQueuePlugin) StateTransition( if !ok { return nil, fmt.Errorf("failed to cast *pb.CoordinatedEvent: got type %T", next) } - if wfCapacity[next.WorkflowID] == 0 { + if medianCapPerWF[next.WorkflowID] == 0 { workflowLimited = append(workflowLimited, next) continue } - wfCapacity[next.WorkflowID]-- + medianCapPerWF[next.WorkflowID]-- consensusEvents = append(consensusEvents, next) } // restore omitted for next time @@ -240,27 +280,26 @@ func (c *consensusQueuePlugin) tryStartExecutions(reader ocr3_1types.KeyValueSta state := stateReader{reader} pbs, err := state.readConsensusEvents() if err != nil { - //TODO log? + c.lggr.Errorw("Failed to read consensus events", "err", err) return } - errs := make([]error, len(pbs.Events)) + var wg sync.WaitGroup - for i, pbEvent := range pbs.Events { + for _, pbEvent := range pbs.Events { var event triggers.CoordinatedEvent - if err := event.FromProto(pbEvent); err != nil { - errs[i] = fmt.Errorf("failed to unmarshal event: %s: %w", pbEvent, err) - continue - } wg.Add(1) c.eng.Go(func(ctx context.Context) { defer wg.Done() - // TODO fetch workflow engine instance + + if err := event.FromProto(pbEvent); err != nil { + c.lggr.Errorw("Failed to unmarshal CoordinatedEvent", "pb", pbEvent.String(), "err", err) + } + // TODO execute StartExecution - errs[i] = nil + // c.triggerCoordinator.tryStartExecution(ctx, event) }) } - wg.Wait() - //TODO process errors? or just log as we go? + wg.Wait() //TODO do we need to wait? } func (c *consensusQueuePlugin) Reports(ctx context.Context, seqNr uint64, reportsPlusPrecursor ocr3_1types.ReportsPlusPrecursor) ([]ocr3types.ReportPlus[[]byte], error) { @@ -268,9 +307,14 @@ func (c *consensusQueuePlugin) Reports(ctx context.Context, seqNr uint64, report } func (c *consensusQueuePlugin) ShouldAcceptAttestedReport(ctx context.Context, seqNr uint64, reportWithInfo ocr3types.ReportWithInfo[[]byte]) (bool, error) { - return true, nil + return false, nil } func (c *consensusQueuePlugin) ShouldTransmitAcceptedReport(ctx context.Context, seqNr uint64, reportWithInfo ocr3types.ReportWithInfo[[]byte]) (bool, error) { - return true, nil + return false, nil +} + +func median[N constraints.Integer, S []N](s S) N { + slices.Sort(s) + return (s[len(s)/2-1] + s[len(s)/2]) / 2 } From 18675698bd65fe6e2085e3ad0966491c6543a5ab Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Sun, 1 Nov 2026 09:19:36 -0600 Subject: [PATCH 04/38] simplify --- core/services/ocr3_1/plugins/queue/kvstate.go | 63 +++++++++++++++++++ core/services/ocr3_1/plugins/queue/queue.go | 62 ++++-------------- 2 files changed, 75 insertions(+), 50 deletions(-) diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index 39175f4bce3..31fdd63bcca 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -3,6 +3,8 @@ package queue import ( "cmp" "container/heap" + "fmt" + "slices" "google.golang.org/protobuf/proto" @@ -101,3 +103,64 @@ func (p *priorityQueue) Push(x any) { func (p *priorityQueue) Pop() any { return (*p)[len(*p)-1] } + +// PopCap pops up to capacity events from the queue, each of which must have wf capacity. Mutates capPerWF. +func (p *priorityQueue) PopCap(capacity uint32, capPerWF map[string]uint32) ([]*pb.CoordinatedEvent, error) { + var events []*pb.CoordinatedEvent + var wfLimited []*pb.CoordinatedEvent // omitted due to workflow limit + for len(events) < int(capacity) { + if len(*p) == 0 { + break + } + next, ok := heap.Pop(p).(*pb.CoordinatedEvent) + if !ok { + return nil, fmt.Errorf("failed to cast *pb.CoordinatedEvent: got type %T", next) + } + if capPerWF[next.WorkflowID] == 0 { + wfLimited = append(wfLimited, next) + continue + } + capPerWF[next.WorkflowID]-- + events = append(events, next) + } + // restore omitted for next time + for _, event := range wfLimited { + heap.Push(p, event) + } + return events, nil +} + +type proposedAndQueued struct { + proposedEvents *pb.ConsensusQueueProposals + queuedEvents *priorityQueue +} + +func (s proposedAndQueued) processObserved(f int, observedProposals map[string][]uint8, observedEvents map[string]*pb.CoordinatedEvent) { + for id, nodes := range observedProposals { + if observers, ok := s.proposedEvents.Observers[id]; !ok && len(nodes) >= f+1 { + // new proposal straight to priority queue + heap.Push(s.queuedEvents, s.proposedEvents.Events[id]) + continue + } else if !ok { + // new proposal < f + 1 + s.proposedEvents.Observers[id] = &pb.NodeIDList{Ids: nodes} + s.proposedEvents.Events[id] = observedEvents[id] + continue + } else if len(nodes) < f+1 { + // update proposal + // TODO opt: build a map to avoid n^2? or nbd since n < f+1 + for _, node := range nodes { + if !slices.Contains(observers.Ids, node) { + observers.Ids = append(observers.Ids, node) + } + } + if len(observers.Ids) < f+1 { + continue + } + } + // f+1 - promote proposal to priority queue + delete(s.proposedEvents.Observers, id) + delete(s.proposedEvents.Events, id) + heap.Push(s.queuedEvents, s.proposedEvents.Events[id]) + } +} diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index 21e3275a0bd..40582cb8e34 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -152,6 +152,7 @@ func (c *consensusQueuePlugin) StateTransition( var wg sync.WaitGroup //TODO is median only logical option for capacity? what if honest nodes have less, don't we ideally want execute min(honest)? + // consider some configurable x% var medianCap uint32 var medianCapPerWF map[string]uint32 // wf ID -> capacity var observedProposals map[string][]uint8 // trigger event ID -> observer OracleIDs @@ -184,71 +185,32 @@ func (c *consensusQueuePlugin) StateTransition( }() // Deserialize the KV store into memory + //TODO package in a constructor for propsoedAndQueued? state := newStateReadWriter(kvState) proposedEvents, err := state.readProposedEvents() if err != nil { return nil, err } - priorityQueue, err := state.readPriorityQueue() + queuedEvents, err := state.readPriorityQueue() if err != nil { return nil, err } - heap.Init(&priorityQueue) //TODO or can we trust it? + heap.Init(&queuedEvents) //TODO or can we trust it? //TODO prune expired events from proposed and priorityQueue wg.Wait() // TODO also wait if we return early for error // Collect observed proposals and promote to priority queue on f+1 - for id, nodes := range observedProposals { - if obs, ok := proposedEvents.Observers[id]; !ok && len(nodes) >= c.onchainCfg.F+1 { - // new proposal straight to priority queue - heap.Push(&priorityQueue, proposedEvents.Events[id]) - continue - } else if !ok { - // new proposal < f + 1 - proposedEvents.Observers[id] = &pb.NodeIDList{Ids: nodes} - proposedEvents.Events[id] = observedEvents[id] - continue - } else if len(nodes) < c.onchainCfg.F+1 { - // update proposal - // TODO opt: build a map to avoid n^2? or nbd since n < f+1 - for _, node := range nodes { - if !slices.Contains(obs.Ids, node) { - obs.Ids = append(obs.Ids, node) - } - } - if len(obs.Ids) < c.onchainCfg.F+1 { - continue - } - } - // f+1 - promote proposal to priority queue - delete(proposedEvents.Observers, id) - delete(proposedEvents.Events, id) - heap.Push(&priorityQueue, proposedEvents.Events[id]) - } + proposedAndQueued{ + proposedEvents: proposedEvents, + queuedEvents: &queuedEvents, + }.processObserved(c.onchainCfg.F, observedProposals, observedEvents) // Select items from queue based on priority and capacity - var consensusEvents []*pb.CoordinatedEvent - var workflowLimited []*pb.CoordinatedEvent // omitted due to workflow limit - for len(consensusEvents) < int(medianCap) { - if len(priorityQueue) == 0 { - break - } - next, ok := heap.Pop(&priorityQueue).(*pb.CoordinatedEvent) - if !ok { - return nil, fmt.Errorf("failed to cast *pb.CoordinatedEvent: got type %T", next) - } - if medianCapPerWF[next.WorkflowID] == 0 { - workflowLimited = append(workflowLimited, next) - continue - } - medianCapPerWF[next.WorkflowID]-- - consensusEvents = append(consensusEvents, next) - } - // restore omitted for next time - for _, event := range workflowLimited { - heap.Push(&priorityQueue, event) + consensusEvents, err := queuedEvents.PopCap(medianCap, medianCapPerWF) + if err != nil { + return nil, err } // Updated KV Store @@ -256,7 +218,7 @@ func (c *consensusQueuePlugin) StateTransition( if err != nil { return nil, err } - err = state.writePriorityQueue(priorityQueue) + err = state.writePriorityQueue(queuedEvents) if err != nil { return nil, err } From 7482bef0575b56c6c31ac783e205bbd488b3ba52 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Mon, 9 Nov 2026 07:34:27 -0600 Subject: [PATCH 05/38] blob support --- core/scripts/go.mod | 8 +- core/scripts/go.sum | 16 +-- core/services/ocr3_1/plugins/queue/kvstate.go | 106 +++++++++++------- core/services/ocr3_1/plugins/queue/queue.go | 106 ++++++++++++++---- .../workflows/v2/triggers/triggers.go | 18 ++- deployment/go.mod | 8 +- deployment/go.sum | 16 +-- go.mod | 8 +- go.sum | 16 +-- integration-tests/go.mod | 8 +- integration-tests/go.sum | 16 +-- integration-tests/load/go.mod | 8 +- integration-tests/load/go.sum | 16 +-- system-tests/lib/go.mod | 8 +- system-tests/lib/go.sum | 16 +-- system-tests/tests/go.mod | 8 +- system-tests/tests/go.sum | 16 +-- 17 files changed, 242 insertions(+), 156 deletions(-) diff --git a/core/scripts/go.mod b/core/scripts/go.mod index 433daf2ab63..c232ee4d810 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.20261028234412-602b80b4cf8d + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261022195454-600e2b321c7a @@ -133,7 +133,7 @@ require ( github.com/buger/goterm v1.0.4 // indirect github.com/buger/jsonparser v1.2.0 // indirect github.com/buraksezer/consistent v0.10.0 // indirect - github.com/bytecodealliance/wasmtime-go/v47 v47.0.0 // indirect + github.com/bytecodealliance/wasmtime-go/v50 v50.0.0 // indirect github.com/bytedance/gopkg v0.1.3 // indirect github.com/bytedance/sonic v1.15.0 // indirect github.com/bytedance/sonic/loader v0.5.0 // indirect @@ -515,7 +515,7 @@ require ( github.com/smartcontractkit/chainlink-protos/chainlink-ccv/message-discovery v0.0.0-20251211142334-5c3421fe2c8d // indirect github.com/smartcontractkit/chainlink-protos/chainlink-ccv/message-rules v0.0.0-20260505131349-78e491b80735 // indirect github.com/smartcontractkit/chainlink-protos/chainlink-ccv/verifier v0.0.0-20251211142334-5c3421fe2c8d // indirect - github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b // indirect + github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261103151748-aa8c64acc53c // indirect github.com/smartcontractkit/chainlink-protos/data-feeds v0.1.1-0.20260501174546-2e8846986b36 // indirect github.com/smartcontractkit/chainlink-protos/linking-service/go v0.0.0-20260512230622-65f10f4cd305 // indirect github.com/smartcontractkit/chainlink-protos/metering/go v0.0.0-20260729184203-90b4cdd48536 // indirect @@ -525,7 +525,7 @@ require ( github.com/smartcontractkit/chainlink-protos/rmn/v1.6/go v0.0.0-20250131130834-15e0d4cde2a6 // indirect github.com/smartcontractkit/chainlink-protos/storage-service v0.3.0 // indirect github.com/smartcontractkit/chainlink-protos/svr v1.3.0 // indirect - github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20260821155228-fa1d775e2138 // indirect + github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20261028174148-0d48af26262a // indirect github.com/smartcontractkit/chainlink-solana/contracts v0.0.0-20260513123719-d347eaf314e1 // indirect github.com/smartcontractkit/chainlink-stellar/bindings v0.0.0-20261005072841-71e45e418098 // indirect github.com/smartcontractkit/chainlink-stellar/deployment v0.0.0-20261005072841-71e45e418098 // indirect diff --git a/core/scripts/go.sum b/core/scripts/go.sum index d09e43690ea..eb80205180c 100644 --- a/core/scripts/go.sum +++ b/core/scripts/go.sum @@ -316,8 +316,8 @@ github.com/bxcodec/faker v2.0.1+incompatible h1:P0KUpUw5w6WJXwrPfv35oc91i4d8nf40 github.com/bxcodec/faker v2.0.1+incompatible/go.mod h1:BNzfpVdTwnFJ6GtfYTcQu6l6rHShT+veBxNCnjCx5XM= github.com/bytecodealliance/wasmtime-go/v39 v39.0.1 h1:RibaT47yiyCRxMOj/l2cvL8cWiWBSqDXHyqsa9sGcCE= github.com/bytecodealliance/wasmtime-go/v39 v39.0.1/go.mod h1:miR4NYIEBXeDNamZIzpskhJ0z/p8al+lwMWylQ/ZJb4= -github.com/bytecodealliance/wasmtime-go/v47 v47.0.0 h1:PAe4o7Mq1VjSx81Dc+V4w1XvxLouFTB384N4ZT4o+7k= -github.com/bytecodealliance/wasmtime-go/v47 v47.0.0/go.mod h1:icJLhTDV7EyKlZpeuBuJl4yoTMqhjUvNv1mewMJUvr4= +github.com/bytecodealliance/wasmtime-go/v50 v50.0.0 h1:oC7otiLbHEIDiL+7otXozGw+hnwD4WihronoKYU3drM= +github.com/bytecodealliance/wasmtime-go/v50 v50.0.0/go.mod h1:xWTHNOKHkN8YVWrTRZpmb1eUOkWPMEXTaVtm3AOEWWE= github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE= @@ -1686,8 +1686,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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d h1:PmhBu41LVNATLXKNX+bzuRShPexHj2H4Ryi4HH1VBbc= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d/go.mod h1:ZRHl1hjJyTPrnv669e3thza3U7Z2as5zKCDZP0kJXuw= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 h1:2APdbnh8Uf/h/THKSZM3g2IW/10ah+ygqwMZltOlBqU= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360/go.mod h1:hdp2bQBzIDJt3UhXKnLz4OMHpsOW54Z9E9Txx4SVC8w= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= @@ -1726,8 +1726,8 @@ github.com/smartcontractkit/chainlink-protos/chainlink-ccv/message-rules v0.0.0- github.com/smartcontractkit/chainlink-protos/chainlink-ccv/message-rules v0.0.0-20260505131349-78e491b80735/go.mod h1:zAJq6Tpkx5AdFUwW67dIYnW+Bdf50drCCpMR81Qxb4E= github.com/smartcontractkit/chainlink-protos/chainlink-ccv/verifier v0.0.0-20251211142334-5c3421fe2c8d h1:AJy55QJ/pBhXkZjc7N+ATnWfxrcjq9BI9DmdtdjwDUQ= github.com/smartcontractkit/chainlink-protos/chainlink-ccv/verifier v0.0.0-20251211142334-5c3421fe2c8d/go.mod h1:5JdppgngCOUS76p61zCinSCgOhPeYQ+OcDUuome5THQ= -github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b h1:tlxPkVQ6ZpJIElqUWc4lU5VH4BB6OzhckG/gHwpaaa0= -github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b/go.mod h1:/i8hjTPFdVWHiY+QjeSiVS2Z3GB3WAZznGgXHstC02E= +github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261103151748-aa8c64acc53c h1:vt2LhimyZm6zPN46kGKlaRUmIiVbv+8VrPT7Hh4raAI= +github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261103151748-aa8c64acc53c/go.mod h1:/i8hjTPFdVWHiY+QjeSiVS2Z3GB3WAZznGgXHstC02E= github.com/smartcontractkit/chainlink-protos/data-feeds v0.1.1-0.20260501174546-2e8846986b36 h1:SG+wAsNyAcA6Kk19ljuxi3HK9Ll2lpHik8OKoY4x7A0= github.com/smartcontractkit/chainlink-protos/data-feeds v0.1.1-0.20260501174546-2e8846986b36/go.mod h1:vL1bDgPSJjV0EqHYs4dDlR+EEE0cJchgvGLYXhwIjXY= github.com/smartcontractkit/chainlink-protos/job-distributor v0.20.1-0.20260701185448-696c075849ea h1:gdA7tZgcRYMq3ryi7uNopYgn6s26g04Haw9SdmLRHzE= @@ -1750,8 +1750,8 @@ github.com/smartcontractkit/chainlink-protos/storage-service v0.3.0 h1:B7itmjy+C github.com/smartcontractkit/chainlink-protos/storage-service v0.3.0/go.mod h1:h6kqaGajbNRrezm56zhx03p0mVmmA2xxj7E/M4ytLUA= github.com/smartcontractkit/chainlink-protos/svr v1.3.0 h1:vOw+MbXtkPK8l/hA7uLASIgCwv05YzmuoIMuOXPa+g0= github.com/smartcontractkit/chainlink-protos/svr v1.3.0/go.mod h1:TcOliTQU6r59DwG4lo3U+mFM9WWyBHGuFkkxQpvSujo= -github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20260821155228-fa1d775e2138 h1:8c/R1dHoAeGTV3/s3ELHjCFuPGuStx5VlJCqe9X0gcM= -github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20260821155228-fa1d775e2138/go.mod h1:Oz1I5l+jsFc+YWPjLIrYdn5XUtjA3Iw/E6Z2G6pq5Q0= +github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20261028174148-0d48af26262a h1:CzHgJU/57hwO0Cm7Ev+S8UvuTZjIXDqSGRBM9z++Mck= +github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20261028174148-0d48af26262a/go.mod h1:9cjvCME22gVZthWieZDmjWbdWvwOzv0RPfPjAkqZ0oc= github.com/smartcontractkit/chainlink-solana v1.3.1-0.20260605202330-b5a89c32fdc1 h1:e4vdi3czYy+eK2j/eO5r3ceMxxkx4Qq5IsiAeSAQ9uc= github.com/smartcontractkit/chainlink-solana v1.3.1-0.20260605202330-b5a89c32fdc1/go.mod h1:wi1QdXqhSJnADt9YRaRtEWomqknLcrdkTS0JotupuOQ= github.com/smartcontractkit/chainlink-solana/contracts v0.0.0-20260513123719-d347eaf314e1 h1:/xvuNFI7DwOoTQnmAdYPDdY+sConn3RgZ2rMy/8AXlo= diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index 31fdd63bcca..604ea37dd2c 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -5,8 +5,10 @@ import ( "container/heap" "fmt" "slices" + "time" "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types" @@ -15,21 +17,21 @@ import ( // KV store Keys const ( - proposedEventsKey = "proposed_events::index" // proposed events waiting for consensus (= f+1 { +func (s observedAndQueued) addObservedEvents(f int, observedEvents map[string]*pb.ConsensusQueueObservedEvent) { + for id, event := range observedEvents { + obs, ok := s.observedEvents.Observations[id] + if !ok && len(event.NodeIds) >= f+1 { // new proposal straight to priority queue - heap.Push(s.queuedEvents, s.proposedEvents.Events[id]) - continue + heap.Push(s.queuedEvents, &pb.ConsensusQueueEvent{ + WorkflowID: "", //TODO parse? + TriggerEventID: "", //TODO parse? + Deadline: medianTimestamp(event.Deadlines), + Blobs: event.Blobs, + }) } else if !ok { // new proposal < f + 1 - s.proposedEvents.Observers[id] = &pb.NodeIDList{Ids: nodes} - s.proposedEvents.Events[id] = observedEvents[id] - continue - } else if len(nodes) < f+1 { + s.observedEvents.Observations[id] = event + } else { // update proposal - // TODO opt: build a map to avoid n^2? or nbd since n < f+1 - for _, node := range nodes { - if !slices.Contains(observers.Ids, node) { - observers.Ids = append(observers.Ids, node) - } + // TODO opt: build a map to avoid n^2? + for i, node := range event.NodeIds { + if !slices.Contains(obs.NodeIds, node) { + obs.NodeIds = append(obs.NodeIds, node) + obs.Deadlines = append(obs.Deadlines, event.Deadlines[i]) + obs.Blobs = append(obs.Blobs, event.Blobs[i]) + } //TODO what if a node reports twice with different deadline or nodeID? do we need to overwrite? } - if len(observers.Ids) < f+1 { - continue + if len(obs.NodeIds) >= f+1 { + // promote proposal to priority queue + delete(s.observedEvents.Observations, id) + heap.Push(s.queuedEvents, &pb.ConsensusQueueEvent{ + WorkflowID: "", //TODO + TriggerEventID: "", //TODO + Deadline: medianTimestamp(event.Deadlines), + Blobs: event.Blobs, + }) } } - // f+1 - promote proposal to priority queue - delete(s.proposedEvents.Observers, id) - delete(s.proposedEvents.Events, id) - heap.Push(s.queuedEvents, s.proposedEvents.Events[id]) } } + +func medianTimestamp(s []*timestamppb.Timestamp) *timestamppb.Timestamp { + var times []time.Time + for _, t := range s { + times = append(times, time.Unix(t.Seconds, int64(t.Nanos))) + } + slices.SortFunc(times, time.Time.Compare) + + a, b := times[len(times)/2], times[len(times)/2-1] + diff := a.Sub(b) + return timestamppb.New(a.Add(diff / 2)) +} diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index 40582cb8e34..b9eed61a0b5 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -9,7 +9,9 @@ import ( "sync" "golang.org/x/exp/constraints" + "golang.org/x/sync/errgroup" "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types" "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types" @@ -38,8 +40,8 @@ func NewConsensusQueuePluginFactory(lggr logger.Logger, cfg *PluginConfig, limit return &consensusQueuePluginFactory{lggr: lggr, cfg: cfg, triggerCoordinator: triggerCoordinator}, nil } -func (c *consensusQueuePluginFactory) NewReportingPlugin(ctx context.Context, config ocr3types.ReportingPluginConfig, fetcher ocr3_1types.BlobBroadcastFetcher) (ocr3_1types.ReportingPlugin[[]byte], ocr3_1types.ReportingPluginInfo, error) { - plugin := newConsensusQueuePlugin(c.lggr, config, c.triggerCoordinator) +func (c *consensusQueuePluginFactory) NewReportingPlugin(ctx context.Context, config ocr3types.ReportingPluginConfig, blobs ocr3_1types.BlobBroadcastFetcher) (ocr3_1types.ReportingPlugin[[]byte], ocr3_1types.ReportingPluginInfo, error) { + plugin := newConsensusQueuePlugin(c.lggr, config, c.triggerCoordinator, blobs) pluginInfo := ocr3_1types.ReportingPluginInfo1{ Name: "ConsensusQueueReportingPlugin", Limits: c.cfg.Limits, @@ -55,13 +57,15 @@ type consensusQueuePlugin struct { lggr logger.Logger onchainCfg ocr3types.ReportingPluginConfig triggerCoordinator triggers.Coordinator + blobs ocr3_1types.BlobBroadcastFetcher } -func newConsensusQueuePlugin(lggr logger.Logger, onchainCfg ocr3types.ReportingPluginConfig, triggerCoordinator triggers.Coordinator) *consensusQueuePlugin { +func newConsensusQueuePlugin(lggr logger.Logger, onchainCfg ocr3types.ReportingPluginConfig, triggerCoordinator triggers.Coordinator, blobs ocr3_1types.BlobBroadcastFetcher) *consensusQueuePlugin { c := &consensusQueuePlugin{ lggr: logger.Named(lggr, "ConsensusQueuePlugin"), onchainCfg: onchainCfg, triggerCoordinator: triggerCoordinator, + blobs: blobs, } c.Service, c.eng = services.Config{ Name: "ConsensusQueueReportingPlugin", @@ -76,7 +80,7 @@ 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, kvState ocr3_1types.KeyValueStateReader, blobs ocr3_1types.BlobBroadcastFetcher, ) (ocrtypes.Observation, error) { // Always attempt to start any executions from the KV Store in the event Committed was not called. // tryStartExecutions is idempotent. @@ -92,7 +96,7 @@ func (c *consensusQueuePlugin) Observation( var events []triggers.CoordinatedEvent // TODO observe queue via c.CentralTriggerQueue.TakeForObservation()... one at at time? obs := &pb.ConsensusQueueObservation{ - Events: make([]*pb.CoordinatedEvent, 0, len(events)), + Events: make([]*pb.ConsensusQueueEvent, 0, len(events)), Capacity: uint32(min(capacity.Global, math.MaxUint32)), WorkflowCapacities: make(map[string]uint32), } @@ -106,7 +110,19 @@ func (c *consensusQueuePlugin) Observation( for _, e := range events { m := e.ToProto() // Try adding to batch - obs.Events = append(obs.Events, m) + + //TODO broadcast now synchronously? or earlier so it's already available now? + //TODO pb.CoordinatedEvent? or could omit wfID, eventID, deadline + // handle, err := blobs.BroadcastBlob(ctx, []byte{}, ocr3_1types.BlobExpirationHintSequenceNumber{SeqNr: 0}) + obs.Events = append(obs.Events, &pb.ConsensusQueueEvent{ + WorkflowID: m.WorkflowID, + TriggerEventID: m.Event.Event.Id, + Deadline: m.Deadline, + Blobs: []*pb.CoordinatedEventBlobHandle{{ + Handle: nil, //TODO + Index: 0, //TODO + }}, + }) id := e.Event.Event.ID var addedCap bool if _, ok := obs.WorkflowCapacities[e.WorkflowID]; !ok { @@ -135,6 +151,8 @@ func (c *consensusQueuePlugin) ValidateObservation( if err != nil { return fmt.Errorf("failed to unmarshal observation: %w", err) } + //TODO ensure each event has single blob+deadline + //TODO ensure blobs exist? return nil } @@ -147,16 +165,16 @@ func (c *consensusQueuePlugin) ObservationQuorum( func (c *consensusQueuePlugin) StateTransition( ctx context.Context, seqNr uint64, aq ocrtypes.AttributedQuery, aos []ocrtypes.AttributedObservation, - kvState ocr3_1types.KeyValueStateReadWriter, _ ocr3_1types.BlobFetcher, + kvState ocr3_1types.KeyValueStateReadWriter, fetcher ocr3_1types.BlobFetcher, ) (ocr3_1types.ReportsPlusPrecursor, error) { var wg sync.WaitGroup //TODO is median only logical option for capacity? what if honest nodes have less, don't we ideally want execute min(honest)? // consider some configurable x% var medianCap uint32 - var medianCapPerWF map[string]uint32 // wf ID -> capacity - var observedProposals map[string][]uint8 // trigger event ID -> observer OracleIDs - var observedEvents map[string]*pb.CoordinatedEvent // trigger event ID -> event + var medianCapPerWF map[string]uint32 // wf ID -> capacity + //TODO key on eventID+workflowID? + var newObservedEvents map[string]*pb.ConsensusQueueObservedEvent // trigger event ID -> event go func() { defer wg.Done() @@ -174,8 +192,20 @@ func (c *consensusQueuePlugin) StateTransition( wfCapacities[wf] = append(wfCapacities[wf], c) } for _, event := range obs.Events { - observedProposals[event.Event.Event.Id] = append(observedProposals[event.Event.Event.Id], uint8(ao.Observer)) - observedEvents[event.Event.Event.Id] = event //TODO last value is not sufficient - must handle disagreement + //TODO key=WFID+eventID? + mergedEvent, ok := newObservedEvents[event.TriggerEventID] + if !ok { + mergedEvent = &pb.ConsensusQueueObservedEvent{ + Deadlines: []*timestamppb.Timestamp{event.Deadline}, + NodeIds: []uint8{uint8(ao.Observer)}, + Blobs: []*pb.CoordinatedEventBlobHandle{event.Blobs[0]}, + } + } else { + mergedEvent.Deadlines = append(mergedEvent.Deadlines, event.Deadline) + mergedEvent.Blobs = append(mergedEvent.Blobs, event.Blobs...) + } + + newObservedEvents[event.TriggerEventID] = mergedEvent } } medianCap = median(capacities) @@ -185,9 +215,9 @@ func (c *consensusQueuePlugin) StateTransition( }() // Deserialize the KV store into memory - //TODO package in a constructor for propsoedAndQueued? + //TODO package in a constructor for observedAndQueued? state := newStateReadWriter(kvState) - proposedEvents, err := state.readProposedEvents() + observedEvents, err := state.readObservedEvents() if err != nil { return nil, err } @@ -202,10 +232,10 @@ func (c *consensusQueuePlugin) StateTransition( wg.Wait() // TODO also wait if we return early for error // Collect observed proposals and promote to priority queue on f+1 - proposedAndQueued{ - proposedEvents: proposedEvents, + observedAndQueued{ + observedEvents: observedEvents, queuedEvents: &queuedEvents, - }.processObserved(c.onchainCfg.F, observedProposals, observedEvents) + }.addObservedEvents(c.onchainCfg.F, newObservedEvents) // Select items from queue based on priority and capacity consensusEvents, err := queuedEvents.PopCap(medianCap, medianCapPerWF) @@ -214,7 +244,9 @@ func (c *consensusQueuePlugin) StateTransition( } // Updated KV Store - err = state.writeProposedEvents(proposedEvents) + //TODO might we hit a KV size limit in the middle of these? then what? can't just drop proposals + // alternative: proposals only valid when there is definitely enough space + err = state.writeObservedEvents(observedEvents) if err != nil { return nil, err } @@ -222,7 +254,7 @@ func (c *consensusQueuePlugin) StateTransition( if err != nil { return nil, err } - err = state.writeConsensusEvents(&pb.CoordinatedEventList{Events: consensusEvents}) + err = state.writeConsensusEvents(&pb.ConsensusQueueEventList{Events: consensusEvents}) if err != nil { return nil, err } @@ -253,7 +285,41 @@ func (c *consensusQueuePlugin) tryStartExecutions(reader ocr3_1types.KeyValueSta c.eng.Go(func(ctx context.Context) { defer wg.Done() - if err := event.FromProto(pbEvent); err != nil { + // fetch blobs with observed events + errGrp := new(errgroup.Group) + observedEvents := make([]*pb.CoordinatedEvent, len(pbEvent.Blobs)) + for i, blob := range pbEvent.Blobs { + errGrp.Go(func() error { + var handle ocr3_1types.BlobHandle + if err := handle.UnmarshalBinary(blob.Handle); err != nil { + return fmt.Errorf("failed to unmarshal blob handle: %w", err) + } + b, err := c.blobs.FetchBlob(ctx, handle) + if err != nil { + return fmt.Errorf("failed to fetch blob: %w", err) + } + //TODO allocate element first? + if err := proto.Unmarshal(b, observedEvents[i]); err != nil { + return fmt.Errorf("failed to unmarshal CoordinatedEvent from blob: %w", err) + } + return nil + }) + } + if err := errGrp.Wait(); err != nil { + c.lggr.Errorw("Failed to fetch blob for event; unable to execute", "eventID", pbEvent.TriggerEventID, "err", err) + return + } + + //TODO we don't always want a continuous median, e.g. IDs + // maybe mode if it exists, otherwise fallback to each node using its own observed value? + if err := event.FromProto(&pb.CoordinatedEvent{ + WorkflowID: pbEvent.WorkflowID, + TriggerCapID: "", //TODO from blob median? + TriggerIndex: 0, //TODO from blob median? + ObservedAt: nil, //TODO from blob median? + Deadline: pbEvent.Deadline, + Event: nil, //TODO from blob ....piecewise median? + }); err != nil { c.lggr.Errorw("Failed to unmarshal CoordinatedEvent", "pb", pbEvent.String(), "err", err) } diff --git a/core/services/workflows/v2/triggers/triggers.go b/core/services/workflows/v2/triggers/triggers.go index 2b04f4a8761..7d80431c24e 100644 --- a/core/services/workflows/v2/triggers/triggers.go +++ b/core/services/workflows/v2/triggers/triggers.go @@ -148,20 +148,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), } } @@ -171,7 +168,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 2d3cfc9be94..dd2995105e0 100644 --- a/deployment/go.mod +++ b/deployment/go.mod @@ -41,14 +41,14 @@ 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-20260916222901-720a003dab50 github.com/smartcontractkit/chainlink-ccip/deployment v0.0.0-20261001213322-a2d686f610ca - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd github.com/smartcontractkit/chainlink-data-streams v1.1.2-0.20261009064810-68424c714170 github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261022195454-600e2b321c7a github.com/smartcontractkit/chainlink-evm/contracts/cre/gobindings v0.0.0-20260403151002-2c91155b5501 github.com/smartcontractkit/chainlink-evm/gethwrappers v0.0.0-20261005112317-b723176adfe8 - github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b + github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261103151748-aa8c64acc53c github.com/smartcontractkit/chainlink-protos/job-distributor v0.20.1-0.20260701185448-696c075849ea github.com/smartcontractkit/chainlink-protos/orchestrator v0.11.0 github.com/smartcontractkit/chainlink-solana v1.3.1-0.20260605202330-b5a89c32fdc1 @@ -163,7 +163,7 @@ require ( github.com/btcsuite/btcutil v1.0.3-0.20201208143702-a53e38424cce // indirect github.com/buger/jsonparser v1.2.0 // indirect github.com/buraksezer/consistent v0.10.0 // indirect - github.com/bytecodealliance/wasmtime-go/v47 v47.0.0 // indirect + github.com/bytecodealliance/wasmtime-go/v50 v50.0.0 // indirect github.com/bytedance/gopkg v0.1.3 // indirect github.com/bytedance/sonic v1.15.0 // indirect github.com/bytedance/sonic/loader v0.5.0 // indirect @@ -451,7 +451,7 @@ require ( github.com/smartcontractkit/chainlink-protos/rmn/v1.6/go v0.0.0-20250131130834-15e0d4cde2a6 // indirect github.com/smartcontractkit/chainlink-protos/storage-service v0.3.0 // indirect github.com/smartcontractkit/chainlink-protos/svr v1.3.0 // indirect - github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20260821155228-fa1d775e2138 // indirect + github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20261028174148-0d48af26262a // indirect github.com/smartcontractkit/chainlink-testing-framework/parrot v0.6.2 // indirect github.com/smartcontractkit/chainlink-testing-framework/seth v1.51.5 // indirect github.com/smartcontractkit/chainlink-ton/cciplib v0.1.1-0.20260925185547-7ea74de84cb2 // indirect diff --git a/deployment/go.sum b/deployment/go.sum index 7c18de10579..6e188fc630e 100644 --- a/deployment/go.sum +++ b/deployment/go.sum @@ -282,8 +282,8 @@ github.com/buraksezer/consistent v0.10.0 h1:hqBgz1PvNLC5rkWcEBVAL9dFMBWz6I0VgUCW github.com/buraksezer/consistent v0.10.0/go.mod h1:6BrVajWq7wbKZlTOUPs/XVfR8c0maujuPowduSpZqmw= github.com/bxcodec/faker v2.0.1+incompatible h1:P0KUpUw5w6WJXwrPfv35oc91i4d8nf40Nwln+M/+faA= github.com/bxcodec/faker v2.0.1+incompatible/go.mod h1:BNzfpVdTwnFJ6GtfYTcQu6l6rHShT+veBxNCnjCx5XM= -github.com/bytecodealliance/wasmtime-go/v47 v47.0.0 h1:PAe4o7Mq1VjSx81Dc+V4w1XvxLouFTB384N4ZT4o+7k= -github.com/bytecodealliance/wasmtime-go/v47 v47.0.0/go.mod h1:icJLhTDV7EyKlZpeuBuJl4yoTMqhjUvNv1mewMJUvr4= +github.com/bytecodealliance/wasmtime-go/v50 v50.0.0 h1:oC7otiLbHEIDiL+7otXozGw+hnwD4WihronoKYU3drM= +github.com/bytecodealliance/wasmtime-go/v50 v50.0.0/go.mod h1:xWTHNOKHkN8YVWrTRZpmb1eUOkWPMEXTaVtm3AOEWWE= github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE= @@ -1411,8 +1411,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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d h1:PmhBu41LVNATLXKNX+bzuRShPexHj2H4Ryi4HH1VBbc= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d/go.mod h1:ZRHl1hjJyTPrnv669e3thza3U7Z2as5zKCDZP0kJXuw= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 h1:2APdbnh8Uf/h/THKSZM3g2IW/10ah+ygqwMZltOlBqU= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360/go.mod h1:hdp2bQBzIDJt3UhXKnLz4OMHpsOW54Z9E9Txx4SVC8w= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= @@ -1449,8 +1449,8 @@ github.com/smartcontractkit/chainlink-protos/chainlink-ccv/message-rules v0.0.0- github.com/smartcontractkit/chainlink-protos/chainlink-ccv/message-rules v0.0.0-20260505131349-78e491b80735/go.mod h1:zAJq6Tpkx5AdFUwW67dIYnW+Bdf50drCCpMR81Qxb4E= github.com/smartcontractkit/chainlink-protos/chainlink-ccv/verifier v0.0.0-20251211142334-5c3421fe2c8d h1:AJy55QJ/pBhXkZjc7N+ATnWfxrcjq9BI9DmdtdjwDUQ= github.com/smartcontractkit/chainlink-protos/chainlink-ccv/verifier v0.0.0-20251211142334-5c3421fe2c8d/go.mod h1:5JdppgngCOUS76p61zCinSCgOhPeYQ+OcDUuome5THQ= -github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b h1:tlxPkVQ6ZpJIElqUWc4lU5VH4BB6OzhckG/gHwpaaa0= -github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b/go.mod h1:/i8hjTPFdVWHiY+QjeSiVS2Z3GB3WAZznGgXHstC02E= +github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261103151748-aa8c64acc53c h1:vt2LhimyZm6zPN46kGKlaRUmIiVbv+8VrPT7Hh4raAI= +github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261103151748-aa8c64acc53c/go.mod h1:/i8hjTPFdVWHiY+QjeSiVS2Z3GB3WAZznGgXHstC02E= github.com/smartcontractkit/chainlink-protos/data-feeds v0.1.1-0.20260501174546-2e8846986b36 h1:SG+wAsNyAcA6Kk19ljuxi3HK9Ll2lpHik8OKoY4x7A0= github.com/smartcontractkit/chainlink-protos/data-feeds v0.1.1-0.20260501174546-2e8846986b36/go.mod h1:vL1bDgPSJjV0EqHYs4dDlR+EEE0cJchgvGLYXhwIjXY= github.com/smartcontractkit/chainlink-protos/job-distributor v0.20.1-0.20260701185448-696c075849ea h1:gdA7tZgcRYMq3ryi7uNopYgn6s26g04Haw9SdmLRHzE= @@ -1473,8 +1473,8 @@ github.com/smartcontractkit/chainlink-protos/storage-service v0.3.0 h1:B7itmjy+C github.com/smartcontractkit/chainlink-protos/storage-service v0.3.0/go.mod h1:h6kqaGajbNRrezm56zhx03p0mVmmA2xxj7E/M4ytLUA= github.com/smartcontractkit/chainlink-protos/svr v1.3.0 h1:vOw+MbXtkPK8l/hA7uLASIgCwv05YzmuoIMuOXPa+g0= github.com/smartcontractkit/chainlink-protos/svr v1.3.0/go.mod h1:TcOliTQU6r59DwG4lo3U+mFM9WWyBHGuFkkxQpvSujo= -github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20260821155228-fa1d775e2138 h1:8c/R1dHoAeGTV3/s3ELHjCFuPGuStx5VlJCqe9X0gcM= -github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20260821155228-fa1d775e2138/go.mod h1:Oz1I5l+jsFc+YWPjLIrYdn5XUtjA3Iw/E6Z2G6pq5Q0= +github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20261028174148-0d48af26262a h1:CzHgJU/57hwO0Cm7Ev+S8UvuTZjIXDqSGRBM9z++Mck= +github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20261028174148-0d48af26262a/go.mod h1:9cjvCME22gVZthWieZDmjWbdWvwOzv0RPfPjAkqZ0oc= github.com/smartcontractkit/chainlink-solana v1.3.1-0.20260605202330-b5a89c32fdc1 h1:e4vdi3czYy+eK2j/eO5r3ceMxxkx4Qq5IsiAeSAQ9uc= github.com/smartcontractkit/chainlink-solana v1.3.1-0.20260605202330-b5a89c32fdc1/go.mod h1:wi1QdXqhSJnADt9YRaRtEWomqknLcrdkTS0JotupuOQ= github.com/smartcontractkit/chainlink-solana/contracts v0.0.0-20260513123719-d347eaf314e1 h1:/xvuNFI7DwOoTQnmAdYPDdY+sConn3RgZ2rMy/8AXlo= diff --git a/go.mod b/go.mod index 1ad05c537a6..833e8bd1f11 100644 --- a/go.mod +++ b/go.mod @@ -82,7 +82,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.15.1-0.20261020204039-1a47492cdb37 - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260903141829-ef07b52a737d github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 github.com/smartcontractkit/chainlink-data-streams v1.1.2-0.20261009064810-68424c714170 @@ -93,7 +93,7 @@ require ( github.com/smartcontractkit/chainlink-framework/chains v0.0.0-20261009212658-df7dcfcb7a77 github.com/smartcontractkit/chainlink-framework/multinode v0.0.0-20260625152110-9afcf56e4053 github.com/smartcontractkit/chainlink-protos/billing/go v0.0.0-20251024234028-0988426d98f4 - github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b + github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261103151748-aa8c64acc53c github.com/smartcontractkit/chainlink-protos/data-feeds v0.1.1-0.20260501174546-2e8846986b36 github.com/smartcontractkit/chainlink-protos/linking-service/go v0.0.0-20260512230622-65f10f4cd305 github.com/smartcontractkit/chainlink-protos/metering/go v0.0.0-20260729184203-90b4cdd48536 @@ -101,7 +101,7 @@ require ( github.com/smartcontractkit/chainlink-protos/orchestrator v0.11.0 github.com/smartcontractkit/chainlink-protos/ring/go v0.0.0-20260904122233-4d79005babd9 github.com/smartcontractkit/chainlink-protos/storage-service v0.3.0 - github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20260821155228-fa1d775e2138 + github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20261028174148-0d48af26262a github.com/smartcontractkit/chainlink-sui/codec v0.0.0-20260720132736-e99278bfdc96 github.com/smartcontractkit/chainlink-ton/cciplib v0.1.1-0.20260716214810-db5ecc877490 github.com/smartcontractkit/cre-sdk-go v1.17.0-capdev.1 @@ -179,7 +179,7 @@ require ( github.com/blendle/zapdriver v1.3.1 // indirect github.com/block-vision/sui-go-sdk v1.2.1 // indirect github.com/btcsuite/btcd/btcec/v2 v2.3.4 // indirect - github.com/bytecodealliance/wasmtime-go/v47 v47.0.0 // indirect + github.com/bytecodealliance/wasmtime-go/v50 v50.0.0 // indirect github.com/bytedance/sonic v1.12.3 // indirect github.com/bytedance/sonic/loader v0.2.0 // indirect github.com/cenkalti/backoff v2.2.1+incompatible // indirect diff --git a/go.sum b/go.sum index 356fa153750..2b0279f5ca4 100644 --- a/go.sum +++ b/go.sum @@ -167,8 +167,8 @@ github.com/buger/jsonparser v1.2.0 h1:4EFcvK1kD4jyj6YqNK6skK6w+y7FHHBR+XBCtxwu/6 github.com/buger/jsonparser v1.2.0/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= github.com/buraksezer/consistent v0.10.0 h1:hqBgz1PvNLC5rkWcEBVAL9dFMBWz6I0VgUCW25rrZlU= github.com/buraksezer/consistent v0.10.0/go.mod h1:6BrVajWq7wbKZlTOUPs/XVfR8c0maujuPowduSpZqmw= -github.com/bytecodealliance/wasmtime-go/v47 v47.0.0 h1:PAe4o7Mq1VjSx81Dc+V4w1XvxLouFTB384N4ZT4o+7k= -github.com/bytecodealliance/wasmtime-go/v47 v47.0.0/go.mod h1:icJLhTDV7EyKlZpeuBuJl4yoTMqhjUvNv1mewMJUvr4= +github.com/bytecodealliance/wasmtime-go/v50 v50.0.0 h1:oC7otiLbHEIDiL+7otXozGw+hnwD4WihronoKYU3drM= +github.com/bytecodealliance/wasmtime-go/v50 v50.0.0/go.mod h1:xWTHNOKHkN8YVWrTRZpmb1eUOkWPMEXTaVtm3AOEWWE= github.com/bytedance/sonic v1.12.3 h1:W2MGa7RCU1QTeYRTPE3+88mVC0yXmsRQRChiyVocVjU= github.com/bytedance/sonic v1.12.3/go.mod h1:B8Gt/XvtZ3Fqj+iSKMypzymZxw/FVwgIGKzMzT9r/rk= github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= @@ -1104,8 +1104,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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d h1:PmhBu41LVNATLXKNX+bzuRShPexHj2H4Ryi4HH1VBbc= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d/go.mod h1:ZRHl1hjJyTPrnv669e3thza3U7Z2as5zKCDZP0kJXuw= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 h1:2APdbnh8Uf/h/THKSZM3g2IW/10ah+ygqwMZltOlBqU= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360/go.mod h1:hdp2bQBzIDJt3UhXKnLz4OMHpsOW54Z9E9Txx4SVC8w= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260903141829-ef07b52a737d h1:M9xuiIvdiHtim4nlxCVajyC/Mk63tAg9ESWb/biAhNA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260903141829-ef07b52a737d/go.mod h1:rI2njmTlyTvh+xhmORmK6qX3+V1ycDAqGJLu8LS8WpU= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= @@ -1140,8 +1140,8 @@ github.com/smartcontractkit/chainlink-protos/chainlink-ccv/message-rules v0.0.0- github.com/smartcontractkit/chainlink-protos/chainlink-ccv/message-rules v0.0.0-20260505131349-78e491b80735/go.mod h1:zAJq6Tpkx5AdFUwW67dIYnW+Bdf50drCCpMR81Qxb4E= github.com/smartcontractkit/chainlink-protos/chainlink-ccv/verifier v0.0.0-20251211142334-5c3421fe2c8d h1:AJy55QJ/pBhXkZjc7N+ATnWfxrcjq9BI9DmdtdjwDUQ= github.com/smartcontractkit/chainlink-protos/chainlink-ccv/verifier v0.0.0-20251211142334-5c3421fe2c8d/go.mod h1:5JdppgngCOUS76p61zCinSCgOhPeYQ+OcDUuome5THQ= -github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b h1:tlxPkVQ6ZpJIElqUWc4lU5VH4BB6OzhckG/gHwpaaa0= -github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b/go.mod h1:/i8hjTPFdVWHiY+QjeSiVS2Z3GB3WAZznGgXHstC02E= +github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261103151748-aa8c64acc53c h1:vt2LhimyZm6zPN46kGKlaRUmIiVbv+8VrPT7Hh4raAI= +github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261103151748-aa8c64acc53c/go.mod h1:/i8hjTPFdVWHiY+QjeSiVS2Z3GB3WAZznGgXHstC02E= github.com/smartcontractkit/chainlink-protos/data-feeds v0.1.1-0.20260501174546-2e8846986b36 h1:SG+wAsNyAcA6Kk19ljuxi3HK9Ll2lpHik8OKoY4x7A0= github.com/smartcontractkit/chainlink-protos/data-feeds v0.1.1-0.20260501174546-2e8846986b36/go.mod h1:vL1bDgPSJjV0EqHYs4dDlR+EEE0cJchgvGLYXhwIjXY= github.com/smartcontractkit/chainlink-protos/linking-service/go v0.0.0-20260512230622-65f10f4cd305 h1:NJdGFhzT6zMaTod4QkBqVD2sg0I25iw1boOYtTpEwRo= @@ -1160,8 +1160,8 @@ github.com/smartcontractkit/chainlink-protos/storage-service v0.3.0 h1:B7itmjy+C github.com/smartcontractkit/chainlink-protos/storage-service v0.3.0/go.mod h1:h6kqaGajbNRrezm56zhx03p0mVmmA2xxj7E/M4ytLUA= github.com/smartcontractkit/chainlink-protos/svr v1.3.0 h1:vOw+MbXtkPK8l/hA7uLASIgCwv05YzmuoIMuOXPa+g0= github.com/smartcontractkit/chainlink-protos/svr v1.3.0/go.mod h1:TcOliTQU6r59DwG4lo3U+mFM9WWyBHGuFkkxQpvSujo= -github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20260821155228-fa1d775e2138 h1:8c/R1dHoAeGTV3/s3ELHjCFuPGuStx5VlJCqe9X0gcM= -github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20260821155228-fa1d775e2138/go.mod h1:Oz1I5l+jsFc+YWPjLIrYdn5XUtjA3Iw/E6Z2G6pq5Q0= +github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20261028174148-0d48af26262a h1:CzHgJU/57hwO0Cm7Ev+S8UvuTZjIXDqSGRBM9z++Mck= +github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20261028174148-0d48af26262a/go.mod h1:9cjvCME22gVZthWieZDmjWbdWvwOzv0RPfPjAkqZ0oc= github.com/smartcontractkit/chainlink-sui/codec v0.0.0-20260720132736-e99278bfdc96 h1:3R9f6pguDIjei+nKx5dUT9j6fX8urGmlZA7Ad3x9UBs= github.com/smartcontractkit/chainlink-sui/codec v0.0.0-20260720132736-e99278bfdc96/go.mod h1:pSW9q0/YqQE5R65Z/2zsyD9c50JZf+yRJJvN6Jo3LCU= github.com/smartcontractkit/chainlink-ton/cciplib v0.1.1-0.20260716214810-db5ecc877490 h1:ots2WddFOQJL/tDFGmvrhRrVu2iRXCd0XEAxhpkAE/Y= diff --git a/integration-tests/go.mod b/integration-tests/go.mod index 2001d2f6a45..490c471a243 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-20260916222901-720a003dab50 github.com/smartcontractkit/chainlink-ccip/chains/solana/gobindings v0.0.0-20260916222901-720a003dab50 - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261022195454-600e2b321c7a @@ -129,7 +129,7 @@ require ( github.com/btcsuite/btcutil v1.0.3-0.20201208143702-a53e38424cce // indirect github.com/buger/jsonparser v1.2.0 // indirect github.com/buraksezer/consistent v0.10.0 // indirect - github.com/bytecodealliance/wasmtime-go/v47 v47.0.0 // indirect + github.com/bytecodealliance/wasmtime-go/v50 v50.0.0 // indirect github.com/bytedance/gopkg v0.1.3 // indirect github.com/bytedance/sonic v1.15.0 // indirect github.com/bytedance/sonic/loader v0.5.0 // indirect @@ -419,7 +419,7 @@ require ( github.com/smartcontractkit/chainlink-protos/chainlink-ccv/message-discovery v0.0.0-20251211142334-5c3421fe2c8d // indirect github.com/smartcontractkit/chainlink-protos/chainlink-ccv/message-rules v0.0.0-20260505131349-78e491b80735 // indirect github.com/smartcontractkit/chainlink-protos/chainlink-ccv/verifier v0.0.0-20251211142334-5c3421fe2c8d // indirect - github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b // indirect + github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261103151748-aa8c64acc53c // indirect github.com/smartcontractkit/chainlink-protos/data-feeds v0.1.1-0.20260501174546-2e8846986b36 // indirect github.com/smartcontractkit/chainlink-protos/linking-service/go v0.0.0-20260512230622-65f10f4cd305 // indirect github.com/smartcontractkit/chainlink-protos/metering/go v0.0.0-20260729184203-90b4cdd48536 // indirect @@ -430,7 +430,7 @@ require ( github.com/smartcontractkit/chainlink-protos/rmn/v1.6/go v0.0.0-20250131130834-15e0d4cde2a6 // indirect github.com/smartcontractkit/chainlink-protos/storage-service v0.3.0 // indirect github.com/smartcontractkit/chainlink-protos/svr v1.3.0 // indirect - github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20260821155228-fa1d775e2138 // indirect + github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20261028174148-0d48af26262a // indirect github.com/smartcontractkit/chainlink-solana v1.3.1-0.20260605202330-b5a89c32fdc1 // indirect github.com/smartcontractkit/chainlink-stellar/bindings v0.0.0-20261005072841-71e45e418098 // indirect github.com/smartcontractkit/chainlink-testing-framework/framework v0.16.9 // indirect diff --git a/integration-tests/go.sum b/integration-tests/go.sum index a8818091a1e..af21626863c 100644 --- a/integration-tests/go.sum +++ b/integration-tests/go.sum @@ -269,8 +269,8 @@ github.com/buraksezer/consistent v0.10.0 h1:hqBgz1PvNLC5rkWcEBVAL9dFMBWz6I0VgUCW github.com/buraksezer/consistent v0.10.0/go.mod h1:6BrVajWq7wbKZlTOUPs/XVfR8c0maujuPowduSpZqmw= github.com/bxcodec/faker v2.0.1+incompatible h1:P0KUpUw5w6WJXwrPfv35oc91i4d8nf40Nwln+M/+faA= github.com/bxcodec/faker v2.0.1+incompatible/go.mod h1:BNzfpVdTwnFJ6GtfYTcQu6l6rHShT+veBxNCnjCx5XM= -github.com/bytecodealliance/wasmtime-go/v47 v47.0.0 h1:PAe4o7Mq1VjSx81Dc+V4w1XvxLouFTB384N4ZT4o+7k= -github.com/bytecodealliance/wasmtime-go/v47 v47.0.0/go.mod h1:icJLhTDV7EyKlZpeuBuJl4yoTMqhjUvNv1mewMJUvr4= +github.com/bytecodealliance/wasmtime-go/v50 v50.0.0 h1:oC7otiLbHEIDiL+7otXozGw+hnwD4WihronoKYU3drM= +github.com/bytecodealliance/wasmtime-go/v50 v50.0.0/go.mod h1:xWTHNOKHkN8YVWrTRZpmb1eUOkWPMEXTaVtm3AOEWWE= github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE= @@ -1396,8 +1396,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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d h1:PmhBu41LVNATLXKNX+bzuRShPexHj2H4Ryi4HH1VBbc= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d/go.mod h1:ZRHl1hjJyTPrnv669e3thza3U7Z2as5zKCDZP0kJXuw= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 h1:2APdbnh8Uf/h/THKSZM3g2IW/10ah+ygqwMZltOlBqU= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360/go.mod h1:hdp2bQBzIDJt3UhXKnLz4OMHpsOW54Z9E9Txx4SVC8w= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= @@ -1434,8 +1434,8 @@ github.com/smartcontractkit/chainlink-protos/chainlink-ccv/message-rules v0.0.0- github.com/smartcontractkit/chainlink-protos/chainlink-ccv/message-rules v0.0.0-20260505131349-78e491b80735/go.mod h1:zAJq6Tpkx5AdFUwW67dIYnW+Bdf50drCCpMR81Qxb4E= github.com/smartcontractkit/chainlink-protos/chainlink-ccv/verifier v0.0.0-20251211142334-5c3421fe2c8d h1:AJy55QJ/pBhXkZjc7N+ATnWfxrcjq9BI9DmdtdjwDUQ= github.com/smartcontractkit/chainlink-protos/chainlink-ccv/verifier v0.0.0-20251211142334-5c3421fe2c8d/go.mod h1:5JdppgngCOUS76p61zCinSCgOhPeYQ+OcDUuome5THQ= -github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b h1:tlxPkVQ6ZpJIElqUWc4lU5VH4BB6OzhckG/gHwpaaa0= -github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b/go.mod h1:/i8hjTPFdVWHiY+QjeSiVS2Z3GB3WAZznGgXHstC02E= +github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261103151748-aa8c64acc53c h1:vt2LhimyZm6zPN46kGKlaRUmIiVbv+8VrPT7Hh4raAI= +github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261103151748-aa8c64acc53c/go.mod h1:/i8hjTPFdVWHiY+QjeSiVS2Z3GB3WAZznGgXHstC02E= github.com/smartcontractkit/chainlink-protos/data-feeds v0.1.1-0.20260501174546-2e8846986b36 h1:SG+wAsNyAcA6Kk19ljuxi3HK9Ll2lpHik8OKoY4x7A0= github.com/smartcontractkit/chainlink-protos/data-feeds v0.1.1-0.20260501174546-2e8846986b36/go.mod h1:vL1bDgPSJjV0EqHYs4dDlR+EEE0cJchgvGLYXhwIjXY= github.com/smartcontractkit/chainlink-protos/job-distributor v0.20.1-0.20260701185448-696c075849ea h1:gdA7tZgcRYMq3ryi7uNopYgn6s26g04Haw9SdmLRHzE= @@ -1458,8 +1458,8 @@ github.com/smartcontractkit/chainlink-protos/storage-service v0.3.0 h1:B7itmjy+C github.com/smartcontractkit/chainlink-protos/storage-service v0.3.0/go.mod h1:h6kqaGajbNRrezm56zhx03p0mVmmA2xxj7E/M4ytLUA= github.com/smartcontractkit/chainlink-protos/svr v1.3.0 h1:vOw+MbXtkPK8l/hA7uLASIgCwv05YzmuoIMuOXPa+g0= github.com/smartcontractkit/chainlink-protos/svr v1.3.0/go.mod h1:TcOliTQU6r59DwG4lo3U+mFM9WWyBHGuFkkxQpvSujo= -github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20260821155228-fa1d775e2138 h1:8c/R1dHoAeGTV3/s3ELHjCFuPGuStx5VlJCqe9X0gcM= -github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20260821155228-fa1d775e2138/go.mod h1:Oz1I5l+jsFc+YWPjLIrYdn5XUtjA3Iw/E6Z2G6pq5Q0= +github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20261028174148-0d48af26262a h1:CzHgJU/57hwO0Cm7Ev+S8UvuTZjIXDqSGRBM9z++Mck= +github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20261028174148-0d48af26262a/go.mod h1:9cjvCME22gVZthWieZDmjWbdWvwOzv0RPfPjAkqZ0oc= github.com/smartcontractkit/chainlink-solana v1.3.1-0.20260605202330-b5a89c32fdc1 h1:e4vdi3czYy+eK2j/eO5r3ceMxxkx4Qq5IsiAeSAQ9uc= github.com/smartcontractkit/chainlink-solana v1.3.1-0.20260605202330-b5a89c32fdc1/go.mod h1:wi1QdXqhSJnADt9YRaRtEWomqknLcrdkTS0JotupuOQ= github.com/smartcontractkit/chainlink-stellar/bindings v0.0.0-20261005072841-71e45e418098 h1:gFe6t6i9283xHx2nsBA604rpKxn932504sbxPERpe24= diff --git a/integration-tests/load/go.mod b/integration-tests/load/go.mod index 2094bc06a45..3a48b7ec505 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-20260916222901-720a003dab50 github.com/smartcontractkit/chainlink-ccip/chains/solana/gobindings v0.0.0-20260916222901-720a003dab50 - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261022195454-600e2b321c7a github.com/smartcontractkit/chainlink-testing-framework/framework v0.16.9 @@ -120,7 +120,7 @@ require ( github.com/btcsuite/btcutil v1.0.3-0.20201208143702-a53e38424cce // indirect github.com/buger/jsonparser v1.2.0 // indirect github.com/buraksezer/consistent v0.10.0 // indirect - github.com/bytecodealliance/wasmtime-go/v47 v47.0.0 // indirect + github.com/bytecodealliance/wasmtime-go/v50 v50.0.0 // indirect github.com/bytedance/gopkg v0.1.3 // indirect github.com/bytedance/sonic v1.15.0 // indirect github.com/bytedance/sonic/loader v0.5.0 // indirect @@ -491,7 +491,7 @@ require ( github.com/smartcontractkit/chainlink-protos/chainlink-ccv/message-discovery v0.0.0-20251211142334-5c3421fe2c8d // indirect github.com/smartcontractkit/chainlink-protos/chainlink-ccv/message-rules v0.0.0-20260505131349-78e491b80735 // indirect github.com/smartcontractkit/chainlink-protos/chainlink-ccv/verifier v0.0.0-20251211142334-5c3421fe2c8d // indirect - github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b // indirect + github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261103151748-aa8c64acc53c // indirect github.com/smartcontractkit/chainlink-protos/data-feeds v0.1.1-0.20260501174546-2e8846986b36 // indirect github.com/smartcontractkit/chainlink-protos/job-distributor v0.20.1-0.20260701185448-696c075849ea // indirect github.com/smartcontractkit/chainlink-protos/linking-service/go v0.0.0-20260512230622-65f10f4cd305 // indirect @@ -503,7 +503,7 @@ require ( github.com/smartcontractkit/chainlink-protos/rmn/v1.6/go v0.0.0-20250131130834-15e0d4cde2a6 // indirect github.com/smartcontractkit/chainlink-protos/storage-service v0.3.0 // indirect github.com/smartcontractkit/chainlink-protos/svr v1.3.0 // indirect - github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20260821155228-fa1d775e2138 // indirect + github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20261028174148-0d48af26262a // indirect github.com/smartcontractkit/chainlink-solana v1.3.1-0.20260605202330-b5a89c32fdc1 // indirect github.com/smartcontractkit/chainlink-stellar/bindings v0.0.0-20261005072841-71e45e418098 // indirect github.com/smartcontractkit/chainlink-sui v0.0.0-20260922143238-46cc062ae5a3 // indirect diff --git a/integration-tests/load/go.sum b/integration-tests/load/go.sum index c1fdd13aa85..96d4c66a9d8 100644 --- a/integration-tests/load/go.sum +++ b/integration-tests/load/go.sum @@ -324,8 +324,8 @@ github.com/buraksezer/consistent v0.10.0 h1:hqBgz1PvNLC5rkWcEBVAL9dFMBWz6I0VgUCW github.com/buraksezer/consistent v0.10.0/go.mod h1:6BrVajWq7wbKZlTOUPs/XVfR8c0maujuPowduSpZqmw= github.com/bxcodec/faker v2.0.1+incompatible h1:P0KUpUw5w6WJXwrPfv35oc91i4d8nf40Nwln+M/+faA= github.com/bxcodec/faker v2.0.1+incompatible/go.mod h1:BNzfpVdTwnFJ6GtfYTcQu6l6rHShT+veBxNCnjCx5XM= -github.com/bytecodealliance/wasmtime-go/v47 v47.0.0 h1:PAe4o7Mq1VjSx81Dc+V4w1XvxLouFTB384N4ZT4o+7k= -github.com/bytecodealliance/wasmtime-go/v47 v47.0.0/go.mod h1:icJLhTDV7EyKlZpeuBuJl4yoTMqhjUvNv1mewMJUvr4= +github.com/bytecodealliance/wasmtime-go/v50 v50.0.0 h1:oC7otiLbHEIDiL+7otXozGw+hnwD4WihronoKYU3drM= +github.com/bytecodealliance/wasmtime-go/v50 v50.0.0/go.mod h1:xWTHNOKHkN8YVWrTRZpmb1eUOkWPMEXTaVtm3AOEWWE= github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE= @@ -1636,8 +1636,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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d h1:PmhBu41LVNATLXKNX+bzuRShPexHj2H4Ryi4HH1VBbc= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d/go.mod h1:ZRHl1hjJyTPrnv669e3thza3U7Z2as5zKCDZP0kJXuw= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 h1:2APdbnh8Uf/h/THKSZM3g2IW/10ah+ygqwMZltOlBqU= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360/go.mod h1:hdp2bQBzIDJt3UhXKnLz4OMHpsOW54Z9E9Txx4SVC8w= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= @@ -1674,8 +1674,8 @@ github.com/smartcontractkit/chainlink-protos/chainlink-ccv/message-rules v0.0.0- github.com/smartcontractkit/chainlink-protos/chainlink-ccv/message-rules v0.0.0-20260505131349-78e491b80735/go.mod h1:zAJq6Tpkx5AdFUwW67dIYnW+Bdf50drCCpMR81Qxb4E= github.com/smartcontractkit/chainlink-protos/chainlink-ccv/verifier v0.0.0-20251211142334-5c3421fe2c8d h1:AJy55QJ/pBhXkZjc7N+ATnWfxrcjq9BI9DmdtdjwDUQ= github.com/smartcontractkit/chainlink-protos/chainlink-ccv/verifier v0.0.0-20251211142334-5c3421fe2c8d/go.mod h1:5JdppgngCOUS76p61zCinSCgOhPeYQ+OcDUuome5THQ= -github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b h1:tlxPkVQ6ZpJIElqUWc4lU5VH4BB6OzhckG/gHwpaaa0= -github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b/go.mod h1:/i8hjTPFdVWHiY+QjeSiVS2Z3GB3WAZznGgXHstC02E= +github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261103151748-aa8c64acc53c h1:vt2LhimyZm6zPN46kGKlaRUmIiVbv+8VrPT7Hh4raAI= +github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261103151748-aa8c64acc53c/go.mod h1:/i8hjTPFdVWHiY+QjeSiVS2Z3GB3WAZznGgXHstC02E= github.com/smartcontractkit/chainlink-protos/data-feeds v0.1.1-0.20260501174546-2e8846986b36 h1:SG+wAsNyAcA6Kk19ljuxi3HK9Ll2lpHik8OKoY4x7A0= github.com/smartcontractkit/chainlink-protos/data-feeds v0.1.1-0.20260501174546-2e8846986b36/go.mod h1:vL1bDgPSJjV0EqHYs4dDlR+EEE0cJchgvGLYXhwIjXY= github.com/smartcontractkit/chainlink-protos/job-distributor v0.20.1-0.20260701185448-696c075849ea h1:gdA7tZgcRYMq3ryi7uNopYgn6s26g04Haw9SdmLRHzE= @@ -1698,8 +1698,8 @@ github.com/smartcontractkit/chainlink-protos/storage-service v0.3.0 h1:B7itmjy+C github.com/smartcontractkit/chainlink-protos/storage-service v0.3.0/go.mod h1:h6kqaGajbNRrezm56zhx03p0mVmmA2xxj7E/M4ytLUA= github.com/smartcontractkit/chainlink-protos/svr v1.3.0 h1:vOw+MbXtkPK8l/hA7uLASIgCwv05YzmuoIMuOXPa+g0= github.com/smartcontractkit/chainlink-protos/svr v1.3.0/go.mod h1:TcOliTQU6r59DwG4lo3U+mFM9WWyBHGuFkkxQpvSujo= -github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20260821155228-fa1d775e2138 h1:8c/R1dHoAeGTV3/s3ELHjCFuPGuStx5VlJCqe9X0gcM= -github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20260821155228-fa1d775e2138/go.mod h1:Oz1I5l+jsFc+YWPjLIrYdn5XUtjA3Iw/E6Z2G6pq5Q0= +github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20261028174148-0d48af26262a h1:CzHgJU/57hwO0Cm7Ev+S8UvuTZjIXDqSGRBM9z++Mck= +github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20261028174148-0d48af26262a/go.mod h1:9cjvCME22gVZthWieZDmjWbdWvwOzv0RPfPjAkqZ0oc= github.com/smartcontractkit/chainlink-solana v1.3.1-0.20260605202330-b5a89c32fdc1 h1:e4vdi3czYy+eK2j/eO5r3ceMxxkx4Qq5IsiAeSAQ9uc= github.com/smartcontractkit/chainlink-solana v1.3.1-0.20260605202330-b5a89c32fdc1/go.mod h1:wi1QdXqhSJnADt9YRaRtEWomqknLcrdkTS0JotupuOQ= github.com/smartcontractkit/chainlink-stellar/bindings v0.0.0-20261005072841-71e45e418098 h1:gFe6t6i9283xHx2nsBA604rpKxn932504sbxPERpe24= diff --git a/system-tests/lib/go.mod b/system-tests/lib/go.mod index 670ac65dd03..4d2ec1df93b 100644 --- a/system-tests/lib/go.mod +++ b/system-tests/lib/go.mod @@ -32,16 +32,16 @@ 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-20260916222901-720a003dab50 - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd github.com/smartcontractkit/chainlink-confidential-compute v1.3.0 github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261022195454-600e2b321c7a github.com/smartcontractkit/chainlink-evm/gethwrappers v0.0.0-20261005112317-b723176adfe8 - github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b + github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261103151748-aa8c64acc53c github.com/smartcontractkit/chainlink-protos/job-distributor v0.20.1-0.20260701185448-696c075849ea github.com/smartcontractkit/chainlink-protos/linking-service/go v0.0.0-20260512230622-65f10f4cd305 - github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20260821155228-fa1d775e2138 + github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20261028174148-0d48af26262a github.com/smartcontractkit/chainlink-stellar/bindings v0.0.0-20261005072841-71e45e418098 github.com/smartcontractkit/chainlink-stellar/deployment v0.0.0-20261005072841-71e45e418098 github.com/smartcontractkit/chainlink-testing-framework/framework v0.16.9 @@ -146,7 +146,7 @@ require ( github.com/buger/goterm v1.0.4 // indirect github.com/buger/jsonparser v1.2.0 // indirect github.com/buraksezer/consistent v0.10.0 // indirect - github.com/bytecodealliance/wasmtime-go/v47 v47.0.0 // indirect + github.com/bytecodealliance/wasmtime-go/v50 v50.0.0 // indirect github.com/bytedance/gopkg v0.1.3 // indirect github.com/bytedance/sonic v1.15.0 // indirect github.com/bytedance/sonic/loader v0.5.0 // indirect diff --git a/system-tests/lib/go.sum b/system-tests/lib/go.sum index 533893e83bf..48828ac54a2 100644 --- a/system-tests/lib/go.sum +++ b/system-tests/lib/go.sum @@ -313,8 +313,8 @@ github.com/bxcodec/faker v2.0.1+incompatible h1:P0KUpUw5w6WJXwrPfv35oc91i4d8nf40 github.com/bxcodec/faker v2.0.1+incompatible/go.mod h1:BNzfpVdTwnFJ6GtfYTcQu6l6rHShT+veBxNCnjCx5XM= github.com/bytecodealliance/wasmtime-go/v39 v39.0.1 h1:RibaT47yiyCRxMOj/l2cvL8cWiWBSqDXHyqsa9sGcCE= github.com/bytecodealliance/wasmtime-go/v39 v39.0.1/go.mod h1:miR4NYIEBXeDNamZIzpskhJ0z/p8al+lwMWylQ/ZJb4= -github.com/bytecodealliance/wasmtime-go/v47 v47.0.0 h1:PAe4o7Mq1VjSx81Dc+V4w1XvxLouFTB384N4ZT4o+7k= -github.com/bytecodealliance/wasmtime-go/v47 v47.0.0/go.mod h1:icJLhTDV7EyKlZpeuBuJl4yoTMqhjUvNv1mewMJUvr4= +github.com/bytecodealliance/wasmtime-go/v50 v50.0.0 h1:oC7otiLbHEIDiL+7otXozGw+hnwD4WihronoKYU3drM= +github.com/bytecodealliance/wasmtime-go/v50 v50.0.0/go.mod h1:xWTHNOKHkN8YVWrTRZpmb1eUOkWPMEXTaVtm3AOEWWE= github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE= @@ -1657,8 +1657,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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d h1:PmhBu41LVNATLXKNX+bzuRShPexHj2H4Ryi4HH1VBbc= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d/go.mod h1:ZRHl1hjJyTPrnv669e3thza3U7Z2as5zKCDZP0kJXuw= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 h1:2APdbnh8Uf/h/THKSZM3g2IW/10ah+ygqwMZltOlBqU= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360/go.mod h1:hdp2bQBzIDJt3UhXKnLz4OMHpsOW54Z9E9Txx4SVC8w= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= @@ -1697,8 +1697,8 @@ github.com/smartcontractkit/chainlink-protos/chainlink-ccv/message-rules v0.0.0- github.com/smartcontractkit/chainlink-protos/chainlink-ccv/message-rules v0.0.0-20260505131349-78e491b80735/go.mod h1:zAJq6Tpkx5AdFUwW67dIYnW+Bdf50drCCpMR81Qxb4E= github.com/smartcontractkit/chainlink-protos/chainlink-ccv/verifier v0.0.0-20251211142334-5c3421fe2c8d h1:AJy55QJ/pBhXkZjc7N+ATnWfxrcjq9BI9DmdtdjwDUQ= github.com/smartcontractkit/chainlink-protos/chainlink-ccv/verifier v0.0.0-20251211142334-5c3421fe2c8d/go.mod h1:5JdppgngCOUS76p61zCinSCgOhPeYQ+OcDUuome5THQ= -github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b h1:tlxPkVQ6ZpJIElqUWc4lU5VH4BB6OzhckG/gHwpaaa0= -github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b/go.mod h1:/i8hjTPFdVWHiY+QjeSiVS2Z3GB3WAZznGgXHstC02E= +github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261103151748-aa8c64acc53c h1:vt2LhimyZm6zPN46kGKlaRUmIiVbv+8VrPT7Hh4raAI= +github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261103151748-aa8c64acc53c/go.mod h1:/i8hjTPFdVWHiY+QjeSiVS2Z3GB3WAZznGgXHstC02E= github.com/smartcontractkit/chainlink-protos/data-feeds v0.1.1-0.20260501174546-2e8846986b36 h1:SG+wAsNyAcA6Kk19ljuxi3HK9Ll2lpHik8OKoY4x7A0= github.com/smartcontractkit/chainlink-protos/data-feeds v0.1.1-0.20260501174546-2e8846986b36/go.mod h1:vL1bDgPSJjV0EqHYs4dDlR+EEE0cJchgvGLYXhwIjXY= github.com/smartcontractkit/chainlink-protos/job-distributor v0.20.1-0.20260701185448-696c075849ea h1:gdA7tZgcRYMq3ryi7uNopYgn6s26g04Haw9SdmLRHzE= @@ -1721,8 +1721,8 @@ github.com/smartcontractkit/chainlink-protos/storage-service v0.3.0 h1:B7itmjy+C github.com/smartcontractkit/chainlink-protos/storage-service v0.3.0/go.mod h1:h6kqaGajbNRrezm56zhx03p0mVmmA2xxj7E/M4ytLUA= github.com/smartcontractkit/chainlink-protos/svr v1.3.0 h1:vOw+MbXtkPK8l/hA7uLASIgCwv05YzmuoIMuOXPa+g0= github.com/smartcontractkit/chainlink-protos/svr v1.3.0/go.mod h1:TcOliTQU6r59DwG4lo3U+mFM9WWyBHGuFkkxQpvSujo= -github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20260821155228-fa1d775e2138 h1:8c/R1dHoAeGTV3/s3ELHjCFuPGuStx5VlJCqe9X0gcM= -github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20260821155228-fa1d775e2138/go.mod h1:Oz1I5l+jsFc+YWPjLIrYdn5XUtjA3Iw/E6Z2G6pq5Q0= +github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20261028174148-0d48af26262a h1:CzHgJU/57hwO0Cm7Ev+S8UvuTZjIXDqSGRBM9z++Mck= +github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20261028174148-0d48af26262a/go.mod h1:9cjvCME22gVZthWieZDmjWbdWvwOzv0RPfPjAkqZ0oc= github.com/smartcontractkit/chainlink-solana v1.3.1-0.20260605202330-b5a89c32fdc1 h1:e4vdi3czYy+eK2j/eO5r3ceMxxkx4Qq5IsiAeSAQ9uc= github.com/smartcontractkit/chainlink-solana v1.3.1-0.20260605202330-b5a89c32fdc1/go.mod h1:wi1QdXqhSJnADt9YRaRtEWomqknLcrdkTS0JotupuOQ= github.com/smartcontractkit/chainlink-solana/contracts v0.0.0-20260513123719-d347eaf314e1 h1:/xvuNFI7DwOoTQnmAdYPDdY+sConn3RgZ2rMy/8AXlo= diff --git a/system-tests/tests/go.mod b/system-tests/tests/go.mod index e24d08d9de5..ad2b048379f 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-20260916222901-720a003dab50 - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 github.com/smartcontractkit/chainlink-confidential-compute v1.3.0 @@ -82,10 +82,10 @@ require ( github.com/smartcontractkit/chainlink-evm/contracts/cre/gobindings v0.0.0-20260403151002-2c91155b5501 github.com/smartcontractkit/chainlink-evm/gethwrappers v0.0.0-20261005112317-b723176adfe8 github.com/smartcontractkit/chainlink-framework/capabilities v0.0.0-20260423135514-5b1a7565a99c - github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b + github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261103151748-aa8c64acc53c github.com/smartcontractkit/chainlink-protos/ring/go v0.0.0-20260904122233-4d79005babd9 github.com/smartcontractkit/chainlink-protos/storage-service v0.3.0 - github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20260821155228-fa1d775e2138 + github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20261028174148-0d48af26262a github.com/smartcontractkit/chainlink-testing-framework/framework v0.16.9 github.com/smartcontractkit/chainlink-testing-framework/framework/components/chiprouter v1.0.4 github.com/smartcontractkit/chainlink-testing-framework/framework/components/fake v0.15.0 @@ -218,7 +218,7 @@ require ( github.com/buger/goterm v1.0.4 // indirect github.com/buger/jsonparser v1.2.0 // indirect github.com/buraksezer/consistent v0.10.0 // indirect - github.com/bytecodealliance/wasmtime-go/v47 v47.0.0 // indirect + github.com/bytecodealliance/wasmtime-go/v50 v50.0.0 // indirect github.com/bytedance/gopkg v0.1.3 // indirect github.com/bytedance/sonic v1.15.0 // indirect github.com/bytedance/sonic/loader v0.5.0 // indirect diff --git a/system-tests/tests/go.sum b/system-tests/tests/go.sum index 063fffac0ae..997f758cb2d 100644 --- a/system-tests/tests/go.sum +++ b/system-tests/tests/go.sum @@ -357,8 +357,8 @@ github.com/bxcodec/faker v2.0.1+incompatible h1:P0KUpUw5w6WJXwrPfv35oc91i4d8nf40 github.com/bxcodec/faker v2.0.1+incompatible/go.mod h1:BNzfpVdTwnFJ6GtfYTcQu6l6rHShT+veBxNCnjCx5XM= github.com/bytecodealliance/wasmtime-go/v39 v39.0.1 h1:RibaT47yiyCRxMOj/l2cvL8cWiWBSqDXHyqsa9sGcCE= github.com/bytecodealliance/wasmtime-go/v39 v39.0.1/go.mod h1:miR4NYIEBXeDNamZIzpskhJ0z/p8al+lwMWylQ/ZJb4= -github.com/bytecodealliance/wasmtime-go/v47 v47.0.0 h1:PAe4o7Mq1VjSx81Dc+V4w1XvxLouFTB384N4ZT4o+7k= -github.com/bytecodealliance/wasmtime-go/v47 v47.0.0/go.mod h1:icJLhTDV7EyKlZpeuBuJl4yoTMqhjUvNv1mewMJUvr4= +github.com/bytecodealliance/wasmtime-go/v50 v50.0.0 h1:oC7otiLbHEIDiL+7otXozGw+hnwD4WihronoKYU3drM= +github.com/bytecodealliance/wasmtime-go/v50 v50.0.0/go.mod h1:xWTHNOKHkN8YVWrTRZpmb1eUOkWPMEXTaVtm3AOEWWE= github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE= @@ -1836,8 +1836,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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d h1:PmhBu41LVNATLXKNX+bzuRShPexHj2H4Ryi4HH1VBbc= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261028234412-602b80b4cf8d/go.mod h1:ZRHl1hjJyTPrnv669e3thza3U7Z2as5zKCDZP0kJXuw= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 h1:2APdbnh8Uf/h/THKSZM3g2IW/10ah+ygqwMZltOlBqU= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360/go.mod h1:hdp2bQBzIDJt3UhXKnLz4OMHpsOW54Z9E9Txx4SVC8w= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= @@ -1880,8 +1880,8 @@ github.com/smartcontractkit/chainlink-protos/chainlink-ccv/message-rules v0.0.0- github.com/smartcontractkit/chainlink-protos/chainlink-ccv/message-rules v0.0.0-20260505131349-78e491b80735/go.mod h1:zAJq6Tpkx5AdFUwW67dIYnW+Bdf50drCCpMR81Qxb4E= github.com/smartcontractkit/chainlink-protos/chainlink-ccv/verifier v0.0.0-20251211142334-5c3421fe2c8d h1:AJy55QJ/pBhXkZjc7N+ATnWfxrcjq9BI9DmdtdjwDUQ= github.com/smartcontractkit/chainlink-protos/chainlink-ccv/verifier v0.0.0-20251211142334-5c3421fe2c8d/go.mod h1:5JdppgngCOUS76p61zCinSCgOhPeYQ+OcDUuome5THQ= -github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b h1:tlxPkVQ6ZpJIElqUWc4lU5VH4BB6OzhckG/gHwpaaa0= -github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b/go.mod h1:/i8hjTPFdVWHiY+QjeSiVS2Z3GB3WAZznGgXHstC02E= +github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261103151748-aa8c64acc53c h1:vt2LhimyZm6zPN46kGKlaRUmIiVbv+8VrPT7Hh4raAI= +github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261103151748-aa8c64acc53c/go.mod h1:/i8hjTPFdVWHiY+QjeSiVS2Z3GB3WAZznGgXHstC02E= github.com/smartcontractkit/chainlink-protos/data-feeds v0.1.1-0.20260501174546-2e8846986b36 h1:SG+wAsNyAcA6Kk19ljuxi3HK9Ll2lpHik8OKoY4x7A0= github.com/smartcontractkit/chainlink-protos/data-feeds v0.1.1-0.20260501174546-2e8846986b36/go.mod h1:vL1bDgPSJjV0EqHYs4dDlR+EEE0cJchgvGLYXhwIjXY= github.com/smartcontractkit/chainlink-protos/job-distributor v0.20.1-0.20260701185448-696c075849ea h1:gdA7tZgcRYMq3ryi7uNopYgn6s26g04Haw9SdmLRHzE= @@ -1904,8 +1904,8 @@ github.com/smartcontractkit/chainlink-protos/storage-service v0.3.0 h1:B7itmjy+C github.com/smartcontractkit/chainlink-protos/storage-service v0.3.0/go.mod h1:h6kqaGajbNRrezm56zhx03p0mVmmA2xxj7E/M4ytLUA= github.com/smartcontractkit/chainlink-protos/svr v1.3.0 h1:vOw+MbXtkPK8l/hA7uLASIgCwv05YzmuoIMuOXPa+g0= github.com/smartcontractkit/chainlink-protos/svr v1.3.0/go.mod h1:TcOliTQU6r59DwG4lo3U+mFM9WWyBHGuFkkxQpvSujo= -github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20260821155228-fa1d775e2138 h1:8c/R1dHoAeGTV3/s3ELHjCFuPGuStx5VlJCqe9X0gcM= -github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20260821155228-fa1d775e2138/go.mod h1:Oz1I5l+jsFc+YWPjLIrYdn5XUtjA3Iw/E6Z2G6pq5Q0= +github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20261028174148-0d48af26262a h1:CzHgJU/57hwO0Cm7Ev+S8UvuTZjIXDqSGRBM9z++Mck= +github.com/smartcontractkit/chainlink-protos/workflows/go v0.0.0-20261028174148-0d48af26262a/go.mod h1:9cjvCME22gVZthWieZDmjWbdWvwOzv0RPfPjAkqZ0oc= github.com/smartcontractkit/chainlink-solana v1.3.1-0.20260605202330-b5a89c32fdc1 h1:e4vdi3czYy+eK2j/eO5r3ceMxxkx4Qq5IsiAeSAQ9uc= github.com/smartcontractkit/chainlink-solana v1.3.1-0.20260605202330-b5a89c32fdc1/go.mod h1:wi1QdXqhSJnADt9YRaRtEWomqknLcrdkTS0JotupuOQ= github.com/smartcontractkit/chainlink-solana/contracts v0.0.0-20260513123719-d347eaf314e1 h1:/xvuNFI7DwOoTQnmAdYPDdY+sConn3RgZ2rMy/8AXlo= From 21514f362173049d0627837e621a9f01d1d52642 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Thu, 12 Nov 2026 14:48:15 -0600 Subject: [PATCH 06/38] blob helpers; kv cleanup; more validation; more methods --- core/scripts/go.mod | 4 +- core/scripts/go.sum | 8 +- core/services/ocr3_1/plugins/queue/blobs.go | 47 +++ core/services/ocr3_1/plugins/queue/kvstate.go | 151 ++++--- core/services/ocr3_1/plugins/queue/queue.go | 379 +++++++++++------- deployment/go.mod | 4 +- deployment/go.sum | 8 +- go.mod | 4 +- go.sum | 8 +- integration-tests/go.mod | 4 +- integration-tests/go.sum | 8 +- integration-tests/load/go.mod | 4 +- integration-tests/load/go.sum | 8 +- system-tests/lib/go.mod | 4 +- system-tests/lib/go.sum | 8 +- system-tests/tests/go.mod | 4 +- system-tests/tests/go.sum | 8 +- 17 files changed, 431 insertions(+), 230 deletions(-) create mode 100644 core/services/ocr3_1/plugins/queue/blobs.go diff --git a/core/scripts/go.mod b/core/scripts/go.mod index c232ee4d810..53e0b3320f5 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.20261109132522-ceedd30df360 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261022195454-600e2b321c7a @@ -500,7 +500,7 @@ require ( github.com/smartcontractkit/chainlink-ccip/chains/solana/gobindings v0.0.0-20260916222901-720a003dab50 // indirect github.com/smartcontractkit/chainlink-ccip/deployment v0.0.0-20261001213322-a2d686f610ca // indirect github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37 // indirect - github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 // indirect + github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 // indirect github.com/smartcontractkit/chainlink-common/x/config v0.0.0-20260928140953-a9b0d3a04daa // indirect github.com/smartcontractkit/chainlink-confidential-compute v1.3.0 // indirect github.com/smartcontractkit/chainlink-data-streams v1.1.2-0.20261009064810-68424c714170 // indirect diff --git a/core/scripts/go.sum b/core/scripts/go.sum index eb80205180c..d5cf426b16e 100644 --- a/core/scripts/go.sum +++ b/core/scripts/go.sum @@ -1686,12 +1686,12 @@ 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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 h1:2APdbnh8Uf/h/THKSZM3g2IW/10ah+ygqwMZltOlBqU= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360/go.mod h1:hdp2bQBzIDJt3UhXKnLz4OMHpsOW54Z9E9Txx4SVC8w= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 h1:nzm+zgN1C6kNVlQnlp3XlzqFl7g9K5h63mRyctvGNRE= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= -github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= -github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549/go.mod h1:Scyk7O80fde5rJF3Ty3fEE3xiS6j84eWbu8/2gl3pIY= +github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= +github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9/go.mod h1:Scyk7O80fde5rJF3Ty3fEE3xiS6j84eWbu8/2gl3pIY= github.com/smartcontractkit/chainlink-common/x/config v0.0.0-20260928140953-a9b0d3a04daa h1:7yIjZpk1mYYu630yXcGR7N+a+pcAHvn4OHlfhJK8GGY= github.com/smartcontractkit/chainlink-common/x/config v0.0.0-20260928140953-a9b0d3a04daa/go.mod h1:nfT8vdE44iAlhDWDV6PaBWucxZZAcDsgGkZ+D0kHpAI= github.com/smartcontractkit/chainlink-confidential-compute v1.3.0 h1:y64hOzM9H61E4EYRzQDtRwqunDBlKpsZc1SvFEUlSLE= 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..492b0d2c9fb --- /dev/null +++ b/core/services/ocr3_1/plugins/queue/blobs.go @@ -0,0 +1,47 @@ +package queue + +import ( + "context" + "fmt" + + "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types" + "google.golang.org/protobuf/proto" + + "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb" +) + +func fetchFromBlob(ctx context.Context, fetcher ocr3_1types.BlobFetcher, handle []byte, idx int) (*pb.CoordinatedEvent, []byte, error) { + var blobHandle ocr3_1types.BlobHandle + if err := blobHandle.UnmarshalBinary(handle); err != nil { + return nil, nil, fmt.Errorf("failed to unmarshal blob handle: %w", err) + } + //TODO cache to fetch just once + b, err := fetcher.FetchBlob(ctx, blobHandle) + if err != nil { + return nil, nil, fmt.Errorf("failed to fetch blob: %w", err) + } + //TODO optimize using protowire to avoid unmarshalling the entire blob + var coordEvents *pb.CoordinatedEventList + if err := proto.Unmarshal(b, coordEvents); err != nil { + return nil, nil, fmt.Errorf("failed to unmarshal blob: %w", err) + } + if idx >= len(coordEvents.Events) { + return nil, nil, fmt.Errorf("blob index %d is out of range for blob with %d events", idx, len(coordEvents.Events)) + } + coordEvent := coordEvents.Events[idx] + return coordEvent, nil, nil +} + +// broadcastAsBlob broadcasts a list of coordinated events and returns a blob handle. +func broadcastAsBlob(ctx context.Context, broadcaster ocr3_1types.BlobBroadcastFetcher, events []*pb.CoordinatedEvent, expSeq uint64) ([]byte, error) { + // TODO return a slice of hashes too; encode list with protowire to hash them along the way - w/ ZERO timestamps + data, err := proto.MarshalOptions{Deterministic: true}.Marshal(&pb.CoordinatedEventList{Events: events}) + if err != nil { + return nil, fmt.Errorf("failed to marshal blob: %w", err) + } + blobHandle, err := broadcaster.BroadcastBlob(ctx, data, ocr3_1types.BlobExpirationHintSequenceNumber{SeqNr: expSeq}) + if err != nil { + return nil, fmt.Errorf("failed to broadcast blob: %w", err) + } + return blobHandle.MarshalBinary() +} diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index 604ea37dd2c..63c9ca955ac 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -4,6 +4,7 @@ import ( "cmp" "container/heap" "fmt" + "maps" "slices" "time" @@ -17,53 +18,63 @@ import ( // KV store Keys const ( - observedEventsKey = "observed_events::index" // observed events waiting for consensus (= f+1 { +func (s *observedAndQueued) pruneExpiredObservations(expiration time.Time) { + unexpiredFn := func(t *timestamppb.Timestamp) bool { return t.AsTime().After(expiration) } + maps.DeleteFunc(s.observedEvents, func(k string, v *pb.ConsensusQueueObservedEvent) bool { + if !slices.ContainsFunc(v.Deadlines, unexpiredFn) { + return false // no unexpired deadlines, so delete the whole thing + } + + // some expired, so prune them + var toDelete []int + for i, d := range v.Deadlines { + if !unexpiredFn(d) { + toDelete = append(toDelete, i) + } + } + for _, i := range toDelete { + v.Deadlines = slices.Delete(v.Deadlines, i, i+1) + v.ObservedAts = slices.Delete(v.ObservedAts, i, i+1) + v.NodeIds = slices.Delete(v.NodeIds, i, i+1) + } + + return false + }) +} + +// TODO on promotion to priority queue, ack the trigger coordinator +func (s *observedAndQueued) addObservedEvents(f int, observedEvents map[string]*pb.ConsensusQueueObservedEvent) { + for blobHash, event := range observedEvents { + obs, ok := s.observedEvents[blobHash] + if !ok && len(event.NodeIds) >= 2*f+1 { // new proposal straight to priority queue - heap.Push(s.queuedEvents, &pb.ConsensusQueueEvent{ - WorkflowID: "", //TODO parse? - TriggerEventID: "", //TODO parse? + s.queuedEvents.push(&pb.ConsensusQueueEvent{ + WorkflowID: event.WorkflowID, + TriggerEventID: event.TriggerEventID, + ObservedAt: medianTimestamp(event.ObservedAts), Deadline: medianTimestamp(event.Deadlines), Blobs: event.Blobs, }) } else if !ok { // new proposal < f + 1 - s.observedEvents.Observations[id] = event + s.observedEvents[blobHash] = event } else { // update proposal // TODO opt: build a map to avoid n^2? @@ -163,12 +211,13 @@ func (s observedAndQueued) addObservedEvents(f int, observedEvents map[string]*p obs.Blobs = append(obs.Blobs, event.Blobs[i]) } //TODO what if a node reports twice with different deadline or nodeID? do we need to overwrite? } - if len(obs.NodeIds) >= f+1 { + if len(obs.NodeIds) >= 2*f+1 { // promote proposal to priority queue - delete(s.observedEvents.Observations, id) - heap.Push(s.queuedEvents, &pb.ConsensusQueueEvent{ - WorkflowID: "", //TODO - TriggerEventID: "", //TODO + delete(s.observedEvents, blobHash) + s.queuedEvents.push(&pb.ConsensusQueueEvent{ + WorkflowID: event.WorkflowID, + TriggerEventID: event.TriggerEventID, + ObservedAt: medianTimestamp(event.ObservedAts), Deadline: medianTimestamp(event.Deadlines), Blobs: event.Blobs, }) diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index b9eed61a0b5..d248cb9a1c2 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -1,12 +1,15 @@ package queue import ( - "container/heap" + "bytes" "context" + "crypto/sha256" + "errors" "fmt" "math" "slices" "sync" + "time" "golang.org/x/exp/constraints" "golang.org/x/sync/errgroup" @@ -21,6 +24,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb" "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/v2/core/services/workflows/v2/triggers" @@ -32,16 +36,22 @@ type consensusQueuePluginFactory struct { lggr logger.Logger cfg *PluginConfig triggerCoordinator triggers.Coordinator + expirationDur func(context.Context) (time.Duration, error) } func NewConsensusQueuePluginFactory(lggr logger.Logger, cfg *PluginConfig, limitsFactory limits.Factory, triggerCoordinator triggers.Coordinator) (ocr3_1types.ReportingPluginFactory[[]byte], error) { - // TODO inject CapacityReporter - // TODO construct limiters - return &consensusQueuePluginFactory{lggr: lggr, cfg: cfg, triggerCoordinator: triggerCoordinator}, nil + return &consensusQueuePluginFactory{ + lggr: lggr, + cfg: cfg, + triggerCoordinator: triggerCoordinator, + expirationDur: func(ctx context.Context) (time.Duration, error) { + return cresettings.Default.ConsensusQueueExpirationInterval.GetOrDefault(ctx, limitsFactory.Settings) + }, + }, nil } func (c *consensusQueuePluginFactory) NewReportingPlugin(ctx context.Context, config ocr3types.ReportingPluginConfig, blobs ocr3_1types.BlobBroadcastFetcher) (ocr3_1types.ReportingPlugin[[]byte], ocr3_1types.ReportingPluginInfo, error) { - plugin := newConsensusQueuePlugin(c.lggr, config, c.triggerCoordinator, blobs) + plugin := newConsensusQueuePlugin(c.lggr, config, c.triggerCoordinator, c.expirationDur, blobs) pluginInfo := ocr3_1types.ReportingPluginInfo1{ Name: "ConsensusQueueReportingPlugin", Limits: c.cfg.Limits, @@ -58,13 +68,15 @@ type consensusQueuePlugin struct { onchainCfg ocr3types.ReportingPluginConfig triggerCoordinator triggers.Coordinator blobs ocr3_1types.BlobBroadcastFetcher + expirationDur func(context.Context) (time.Duration, error) } -func newConsensusQueuePlugin(lggr logger.Logger, onchainCfg ocr3types.ReportingPluginConfig, triggerCoordinator triggers.Coordinator, blobs ocr3_1types.BlobBroadcastFetcher) *consensusQueuePlugin { +func newConsensusQueuePlugin(lggr logger.Logger, onchainCfg ocr3types.ReportingPluginConfig, triggerCoordinator triggers.Coordinator, expirationGraceDur func(context.Context) (time.Duration, error), blobs ocr3_1types.BlobBroadcastFetcher) *consensusQueuePlugin { c := &consensusQueuePlugin{ lggr: logger.Named(lggr, "ConsensusQueuePlugin"), onchainCfg: onchainCfg, triggerCoordinator: triggerCoordinator, + expirationDur: expirationGraceDur, blobs: blobs, } c.Service, c.eng = services.Config{ @@ -92,50 +104,74 @@ func (c *consensusQueuePlugin) Observation( return nil, fmt.Errorf("failed to get available capacity: %w", err) } - // Build Observation var events []triggers.CoordinatedEvent - // TODO observe queue via c.CentralTriggerQueue.TakeForObservation()... one at at time? + // TODO observe queue - but can't "take" - need to confirm during StateTransition + + 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{ Events: make([]*pb.ConsensusQueueEvent, 0, len(events)), + Expiration: timestamppb.New(expiration), Capacity: uint32(min(capacity.Global, math.MaxUint32)), WorkflowCapacities: make(map[string]uint32), } - for wf, c := range capacity.PerWorkflow { + for wf, wfCap := range capacity.PerWorkflow { //TODO only for events proposed and queued in the KV store? - obs.WorkflowCapacities[wf] = uint32(min(c, math.MaxUint32)) + obs.WorkflowCapacities[wf] = uint32(min(wfCap, math.MaxUint32)) + } + + const roundDur = 10 * time.Second //TODO dynamic calibration? + expSeqNr := seqNr + uint64(expirationGraceDur/roundDur) //TODO pad extra time and/or rounds + + pbEvents := make([]*pb.CoordinatedEvent, 0, len(events)) + for _, e := range events { + pbEvents = append(pbEvents, e.ToProto()) + } + blobHandle, err := broadcastAsBlob(ctx, blobs, pbEvents, expSeqNr) + if err != nil { + return nil, err } const maxObservationSize = 0 //TODO protoOpts := proto.MarshalOptions{Deterministic: true} - for _, e := range events { - m := e.ToProto() + for i, m := range pbEvents { // Try adding to batch - //TODO broadcast now synchronously? or earlier so it's already available now? - //TODO pb.CoordinatedEvent? or could omit wfID, eventID, deadline - // handle, err := blobs.BroadcastBlob(ctx, []byte{}, ocr3_1types.BlobExpirationHintSequenceNumber{SeqNr: 0}) + protoBytes, err := protoOpts.Marshal(m) //TODO opt: don't marshal again, get hash from broadcast helper + if err != nil { + //TODO log + continue + } + blobHash := sha256.Sum256(protoBytes) + obs.Events = append(obs.Events, &pb.ConsensusQueueEvent{ WorkflowID: m.WorkflowID, TriggerEventID: m.Event.Event.Id, Deadline: m.Deadline, + BlobHash: blobHash[:], Blobs: []*pb.CoordinatedEventBlobHandle{{ - Handle: nil, //TODO - Index: 0, //TODO + Handle: blobHandle, + Index: uint32(i), }}, }) - id := e.Event.Event.ID + var addedCap bool - if _, ok := obs.WorkflowCapacities[e.WorkflowID]; !ok { + if _, ok := obs.WorkflowCapacities[m.WorkflowID]; !ok { addedCap = true - obs.WorkflowCapacities[e.WorkflowID] = uint32(min(capacity.PerWorkflow[e.WorkflowID], math.MaxUint32)) + obs.WorkflowCapacities[m.WorkflowID] = uint32(min(capacity.PerWorkflow[m.WorkflowID], math.MaxUint32)) } // Check size if protoOpts.Size(obs) > maxObservationSize { // too large, remove this one obs.Events = obs.Events[:len(obs.Events)-1] if addedCap { - delete(obs.WorkflowCapacities, id) + delete(obs.WorkflowCapacities, m.WorkflowID) } + //TODO opt: remember the blobHandle to avoid rebroadcasting events break } } @@ -144,15 +180,73 @@ func (c *consensusQueuePlugin) Observation( func (c *consensusQueuePlugin) ValidateObservation( ctx context.Context, seqNr uint64, _ ocrtypes.AttributedQuery, ao ocrtypes.AttributedObservation, - _ ocr3_1types.KeyValueStateReader, _ ocr3_1types.BlobFetcher, + _ ocr3_1types.KeyValueStateReader, blobs ocr3_1types.BlobFetcher, ) error { var obs pb.ConsensusQueueObservation err := proto.Unmarshal(ao.Observation, &obs) if err != nil { return fmt.Errorf("failed to unmarshal observation: %w", err) } - //TODO ensure each event has single blob+deadline - //TODO ensure blobs exist? + var eg errgroup.Group + for i, event := range obs.Events { + eg.Go(func() error { + if err := validateObservedEvent(ctx, blobs, event); err != nil { + return fmt.Errorf("event %d failed validation: %w", i, err) + } + return nil + }) + } + return nil +} + +func validateObservedEvent(ctx context.Context, blobs ocr3_1types.BlobFetcher, event *pb.ConsensusQueueEvent) error { + if event.WorkflowID == "" { + return errors.New("event workflow id is missing") + } + if event.TriggerEventID == "" { + return errors.New("event trigger event id is missing") + } + if event.ObservedAt == nil { + return errors.New("event observation ts is missing") + } + if event.Deadline == nil { + return errors.New("event deadline is missing") + } + if event.BlobHash == nil { + return fmt.Errorf("event blob hash is missing") + } + + if len(event.Blobs) == 0 { + return fmt.Errorf("event blob is missing") + } + if len(event.Blobs) > 1 { + return fmt.Errorf("event has more than one blob") + } + + coordEvent, pbBytes, err := fetchFromBlob(ctx, blobs, event.Blobs[0].Handle, int(event.Blobs[0].Index)) + if err != nil { + return fmt.Errorf("failed to fetch event from blob: %w", err) + } + + if coordEvent.WorkflowID != event.WorkflowID { + return fmt.Errorf("blob workflow ID %s does not match event workflow ID %s", coordEvent.WorkflowID, event.WorkflowID) + } + if coordEvent.GetEvent().GetEvent().Id != event.TriggerEventID { + return fmt.Errorf("blob event ID %s does not match event trigger event ID %s", coordEvent.GetEvent().GetEvent().Id, event.TriggerEventID) + } + + 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) + } + + //TODO reduce allocations with a pool? + if shaSum := sha256.Sum256(pbBytes); !bytes.Equal(shaSum[:], event.BlobHash) { + return fmt.Errorf("blob hash %x does not match observation hash %x", shaSum, event.BlobHash) + } + return nil } @@ -167,78 +261,36 @@ func (c *consensusQueuePlugin) StateTransition( ctx context.Context, seqNr uint64, aq ocrtypes.AttributedQuery, aos []ocrtypes.AttributedObservation, kvState ocr3_1types.KeyValueStateReadWriter, fetcher ocr3_1types.BlobFetcher, ) (ocr3_1types.ReportsPlusPrecursor, error) { - var wg sync.WaitGroup + var done chan struct{} + var obs observations - //TODO is median only logical option for capacity? what if honest nodes have less, don't we ideally want execute min(honest)? - // consider some configurable x% - var medianCap uint32 - var medianCapPerWF map[string]uint32 // wf ID -> capacity - //TODO key on eventID+workflowID? - var newObservedEvents map[string]*pb.ConsensusQueueObservedEvent // trigger event ID -> event go func() { - defer wg.Done() - - capacities := make([]uint32, 0, len(aos)) - wfCapacities := make(map[string][]uint32) - for _, ao := range aos { - var obs pb.ConsensusQueueObservation - err := proto.Unmarshal(ao.Observation, &obs) - if err != nil { - c.lggr.Errorw("Failed to unmarshal observation", "err", err) - continue - } - capacities = append(capacities, obs.Capacity) - for wf, c := range obs.WorkflowCapacities { - wfCapacities[wf] = append(wfCapacities[wf], c) - } - for _, event := range obs.Events { - //TODO key=WFID+eventID? - mergedEvent, ok := newObservedEvents[event.TriggerEventID] - if !ok { - mergedEvent = &pb.ConsensusQueueObservedEvent{ - Deadlines: []*timestamppb.Timestamp{event.Deadline}, - NodeIds: []uint8{uint8(ao.Observer)}, - Blobs: []*pb.CoordinatedEventBlobHandle{event.Blobs[0]}, - } - } else { - mergedEvent.Deadlines = append(mergedEvent.Deadlines, event.Deadline) - mergedEvent.Blobs = append(mergedEvent.Blobs, event.Blobs...) - } - - newObservedEvents[event.TriggerEventID] = mergedEvent - } - } - medianCap = median(capacities) - for wf, c := range wfCapacities { - medianCapPerWF[wf] = median(c) + defer close(done) + if warn := obs.aggregate(ctx, aos); warn != nil { + c.lggr.Warnw("Failed to aggregate some observations", "err", warn) } }() - // Deserialize the KV store into memory - //TODO package in a constructor for observedAndQueued? - state := newStateReadWriter(kvState) - observedEvents, err := state.readObservedEvents() - if err != nil { - return nil, err - } - queuedEvents, err := state.readPriorityQueue() + stateRW := newStateReadWriter(kvState) + state, err := stateRW.readObservedAndQueued() if err != nil { return nil, err } - heap.Init(&queuedEvents) //TODO or can we trust it? - - //TODO prune expired events from proposed and priorityQueue - wg.Wait() // TODO also wait if we return early for error - - // Collect observed proposals and promote to priority queue on f+1 - observedAndQueued{ - observedEvents: observedEvents, - queuedEvents: &queuedEvents, - }.addObservedEvents(c.onchainCfg.F, newObservedEvents) + // wait for aggregation + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-done: + if err = ctx.Err(); err != nil { + return nil, err + } + } - // Select items from queue based on priority and capacity - consensusEvents, err := queuedEvents.PopCap(medianCap, medianCapPerWF) + // update state + state.pruneExpiredObservations(obs.medianExpiration) + state.addObservedEvents(c.onchainCfg.F, obs.newObservedEvents) + consensusEvents, err := state.queuedEvents.popLimited(obs.medianCap, obs.medianCapPerWF, obs.medianExpiration) if err != nil { return nil, err } @@ -246,15 +298,7 @@ func (c *consensusQueuePlugin) StateTransition( // Updated KV Store //TODO might we hit a KV size limit in the middle of these? then what? can't just drop proposals // alternative: proposals only valid when there is definitely enough space - err = state.writeObservedEvents(observedEvents) - if err != nil { - return nil, err - } - err = state.writePriorityQueue(queuedEvents) - if err != nil { - return nil, err - } - err = state.writeConsensusEvents(&pb.ConsensusQueueEventList{Events: consensusEvents}) + err = stateRW.update(state, consensusEvents) if err != nil { return nil, err } @@ -263,6 +307,66 @@ func (c *consensusQueuePlugin) StateTransition( return ocr3_1types.ReportsPlusPrecursor{}, nil } +type observations struct { + medianExpiration time.Time + medianCap uint32 + medianCapPerWF map[string]uint32 // wf ID -> capacity + newObservedEvents map[string]*pb.ConsensusQueueObservedEvent // key: blobHash +} + +// TODO consider some configurable x% of capacity since some honest nodes have less +func (res *observations) aggregate(ctx context.Context, aos []ocrtypes.AttributedObservation) (warn error) { + res.medianCapPerWF = make(map[string]uint32) + res.newObservedEvents = make(map[string]*pb.ConsensusQueueObservedEvent) + + expirations := make([]*timestamppb.Timestamp, 0, len(aos)) + capacities := make([]uint32, 0, len(aos)) + wfCapacities := make(map[string][]uint32) + for _, ao := range aos { + var obs pb.ConsensusQueueObservation + err := proto.Unmarshal(ao.Observation, &obs) + if err != nil { + warn = errors.Join(warn, fmt.Errorf("failed to unmarshal observation from oracle %d: %w", ao.Observation, err)) + continue + } + expirations = append(expirations, obs.Expiration) + capacities = append(capacities, obs.Capacity) + for wf, c := range obs.WorkflowCapacities { + wfCapacities[wf] = append(wfCapacities[wf], c) + } + for _, event := range obs.Events { + if ctx.Err() != nil { + return + } + aggregated, ok := res.newObservedEvents[string(event.BlobHash)] + if !ok { + aggregated = &pb.ConsensusQueueObservedEvent{ + TriggerEventID: event.TriggerEventID, + WorkflowID: event.WorkflowID, + NodeIds: []uint8{uint8(ao.Observer)}, + ObservedAts: []*timestamppb.Timestamp{event.ObservedAt}, + Deadlines: []*timestamppb.Timestamp{event.Deadline}, + Blobs: []*pb.CoordinatedEventBlobHandle{event.Blobs[0]}, + } + } else { + // note: trigger event and workflow ID alignment is ensured by ValidateObservation + aggregated.NodeIds = append(aggregated.NodeIds, uint8(ao.Observer)) + aggregated.ObservedAts = append(aggregated.ObservedAts, event.ObservedAt) + aggregated.Deadlines = append(aggregated.Deadlines, event.Deadline) + aggregated.Blobs = append(aggregated.Blobs, event.Blobs...) + } + + res.newObservedEvents[string(event.BlobHash)] = aggregated + } + } + res.medianExpiration = medianTimestamp(expirations).AsTime() + res.medianCap = median(capacities) + for wf, c := range wfCapacities { + res.medianCapPerWF[wf] = median(c) + } + return +} + func (c *consensusQueuePlugin) Committed(ctx context.Context, seqNr uint64, keyValueStateReader ocr3_1types.KeyValueStateReader) error { c.tryStartExecutions(keyValueStateReader) return nil @@ -271,63 +375,64 @@ func (c *consensusQueuePlugin) Committed(ctx context.Context, seqNr uint64, keyV // 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(reader ocr3_1types.KeyValueStateReader) { - state := stateReader{reader} - pbs, err := state.readConsensusEvents() + v, err := reader.Read([]byte(consensusEventsKey)) if err != nil { c.lggr.Errorw("Failed to read consensus events", "err", err) return } + var consensusEvents []*pb.ConsensusQueueEvent + if v != nil { + var pbs *pb.ConsensusQueueEventList + if err := proto.Unmarshal(v, pbs); err != nil { + c.lggr.Errorw("Failed to unmarshal consensus events", "err", err) + return + } + } var wg sync.WaitGroup - for _, pbEvent := range pbs.Events { - var event triggers.CoordinatedEvent + for _, consensusEvent := range consensusEvents { wg.Add(1) c.eng.Go(func(ctx context.Context) { defer wg.Done() - // fetch blobs with observed events - errGrp := new(errgroup.Group) - observedEvents := make([]*pb.CoordinatedEvent, len(pbEvent.Blobs)) - for i, blob := range pbEvent.Blobs { - errGrp.Go(func() error { - var handle ocr3_1types.BlobHandle - if err := handle.UnmarshalBinary(blob.Handle); err != nil { - return fmt.Errorf("failed to unmarshal blob handle: %w", err) - } - b, err := c.blobs.FetchBlob(ctx, handle) - if err != nil { - return fmt.Errorf("failed to fetch blob: %w", err) - } - //TODO allocate element first? - if err := proto.Unmarshal(b, observedEvents[i]); err != nil { - return fmt.Errorf("failed to unmarshal CoordinatedEvent from blob: %w", err) - } - return nil - }) - } - if err := errGrp.Wait(); err != nil { - c.lggr.Errorw("Failed to fetch blob for event; unable to execute", "eventID", pbEvent.TriggerEventID, "err", err) + if err2 := c.tryStartExecution(ctx, consensusEvent); err2 != nil { + c.lggr.Errorw("Failed to execute event", "eventID", consensusEvent.TriggerEventID, "err", err2) return } + }) + } + wg.Wait() +} - //TODO we don't always want a continuous median, e.g. IDs - // maybe mode if it exists, otherwise fallback to each node using its own observed value? - if err := event.FromProto(&pb.CoordinatedEvent{ - WorkflowID: pbEvent.WorkflowID, - TriggerCapID: "", //TODO from blob median? - TriggerIndex: 0, //TODO from blob median? - ObservedAt: nil, //TODO from blob median? - Deadline: pbEvent.Deadline, - Event: nil, //TODO from blob ....piecewise median? - }); err != nil { - c.lggr.Errorw("Failed to unmarshal CoordinatedEvent", "pb", pbEvent.String(), "err", err) - } +func (c *consensusQueuePlugin) tryStartExecution(ctx context.Context, consensusEvent *pb.ConsensusQueueEvent) error { + // any blob will do, first that exists + var pbEvent *pb.CoordinatedEvent + var errs []error + for _, blob := range consensusEvent.Blobs { + var err error + pbEvent, _, err = fetchFromBlob(ctx, c.blobs, blob.Handle, int(blob.Index)) + if err != nil { + errs = append(errs, fmt.Errorf("failed to fetch blob: %w", err)) + c.lggr.Warnw("Failed to fetch blob", "handle", blob.Handle, "index", blob.Index, "err", err) + continue // try next blob + } + break + } + if pbEvent == nil { + return fmt.Errorf("failed to fetch blob from all %d handles: %w", len(consensusEvent.Blobs), errors.Join(errs...)) + } + // fill in medianized timestamps + pbEvent.ObservedAt = consensusEvent.ObservedAt + pbEvent.Deadline = consensusEvent.Deadline - // TODO execute StartExecution - // c.triggerCoordinator.tryStartExecution(ctx, event) - }) + var event triggers.CoordinatedEvent + if err := event.FromProto(pbEvent); err != nil { + return fmt.Errorf("failed to convert CoordinatedEvent from proto: %w", err) } - wg.Wait() //TODO do we need to wait? + + // TODO execute StartExecution + // c.triggerCoordinator.tryStartExecution(ctx, event) + return nil } func (c *consensusQueuePlugin) Reports(ctx context.Context, seqNr uint64, reportsPlusPrecursor ocr3_1types.ReportsPlusPrecursor) ([]ocr3types.ReportPlus[[]byte], error) { diff --git a/deployment/go.mod b/deployment/go.mod index dd2995105e0..d3be9e9c97e 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-20260916222901-720a003dab50 github.com/smartcontractkit/chainlink-ccip/deployment v0.0.0-20261001213322-a2d686f610ca - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd github.com/smartcontractkit/chainlink-data-streams v1.1.2-0.20261009064810-68424c714170 github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 @@ -430,7 +430,7 @@ require ( github.com/smartcontractkit/chainlink-canton/authentication v1.0.0 // indirect github.com/smartcontractkit/chainlink-canton/contracts/v2 v2.1.0 // indirect github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37 // indirect - github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 // indirect + github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 // indirect github.com/smartcontractkit/chainlink-common/x/config v0.0.0-20260928140953-a9b0d3a04daa // indirect github.com/smartcontractkit/chainlink-feeds v0.1.2-0.20250227211209-7cd000095135 // indirect github.com/smartcontractkit/chainlink-framework/chains v0.0.0-20261009212658-df7dcfcb7a77 // indirect diff --git a/deployment/go.sum b/deployment/go.sum index 6e188fc630e..e1a6402cf6a 100644 --- a/deployment/go.sum +++ b/deployment/go.sum @@ -1411,12 +1411,12 @@ 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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 h1:2APdbnh8Uf/h/THKSZM3g2IW/10ah+ygqwMZltOlBqU= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360/go.mod h1:hdp2bQBzIDJt3UhXKnLz4OMHpsOW54Z9E9Txx4SVC8w= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 h1:nzm+zgN1C6kNVlQnlp3XlzqFl7g9K5h63mRyctvGNRE= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= -github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= -github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549/go.mod h1:Scyk7O80fde5rJF3Ty3fEE3xiS6j84eWbu8/2gl3pIY= +github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= +github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9/go.mod h1:Scyk7O80fde5rJF3Ty3fEE3xiS6j84eWbu8/2gl3pIY= github.com/smartcontractkit/chainlink-common/x/config v0.0.0-20260928140953-a9b0d3a04daa h1:7yIjZpk1mYYu630yXcGR7N+a+pcAHvn4OHlfhJK8GGY= github.com/smartcontractkit/chainlink-common/x/config v0.0.0-20260928140953-a9b0d3a04daa/go.mod h1:nfT8vdE44iAlhDWDV6PaBWucxZZAcDsgGkZ+D0kHpAI= github.com/smartcontractkit/chainlink-data-streams v1.1.2-0.20261009064810-68424c714170 h1:HeQlHO9MrUXTJmxYCNX4xPX14glLAdwIN3igc9Am/g8= diff --git a/go.mod b/go.mod index 833e8bd1f11..8485ebe8c95 100644 --- a/go.mod +++ b/go.mod @@ -82,9 +82,9 @@ 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.15.1-0.20261020204039-1a47492cdb37 - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260903141829-ef07b52a737d - github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 + github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 github.com/smartcontractkit/chainlink-data-streams v1.1.2-0.20261009064810-68424c714170 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261022195454-600e2b321c7a github.com/smartcontractkit/chainlink-evm/contracts/cre/gobindings v0.0.0-20260403151002-2c91155b5501 diff --git a/go.sum b/go.sum index 2b0279f5ca4..2bf1e20560a 100644 --- a/go.sum +++ b/go.sum @@ -1104,12 +1104,12 @@ 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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 h1:2APdbnh8Uf/h/THKSZM3g2IW/10ah+ygqwMZltOlBqU= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360/go.mod h1:hdp2bQBzIDJt3UhXKnLz4OMHpsOW54Z9E9Txx4SVC8w= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 h1:nzm+zgN1C6kNVlQnlp3XlzqFl7g9K5h63mRyctvGNRE= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260903141829-ef07b52a737d h1:M9xuiIvdiHtim4nlxCVajyC/Mk63tAg9ESWb/biAhNA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260903141829-ef07b52a737d/go.mod h1:rI2njmTlyTvh+xhmORmK6qX3+V1ycDAqGJLu8LS8WpU= -github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= -github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549/go.mod h1:Scyk7O80fde5rJF3Ty3fEE3xiS6j84eWbu8/2gl3pIY= +github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= +github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9/go.mod h1:Scyk7O80fde5rJF3Ty3fEE3xiS6j84eWbu8/2gl3pIY= github.com/smartcontractkit/chainlink-common/x/config v0.0.0-20260928140953-a9b0d3a04daa h1:7yIjZpk1mYYu630yXcGR7N+a+pcAHvn4OHlfhJK8GGY= github.com/smartcontractkit/chainlink-common/x/config v0.0.0-20260928140953-a9b0d3a04daa/go.mod h1:nfT8vdE44iAlhDWDV6PaBWucxZZAcDsgGkZ+D0kHpAI= github.com/smartcontractkit/chainlink-data-streams v1.1.2-0.20261009064810-68424c714170 h1:HeQlHO9MrUXTJmxYCNX4xPX14glLAdwIN3igc9Am/g8= diff --git a/integration-tests/go.mod b/integration-tests/go.mod index 490c471a243..3d443a8161e 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-20260916222901-720a003dab50 github.com/smartcontractkit/chainlink-ccip/chains/solana/gobindings v0.0.0-20260916222901-720a003dab50 - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261022195454-600e2b321c7a @@ -405,7 +405,7 @@ require ( github.com/smartcontractkit/chainlink-ccip/chains/solana/deployment v0.0.0-20260916222901-720a003dab50 // indirect github.com/smartcontractkit/chainlink-ccip/deployment v0.0.0-20261001213322-a2d686f610ca // indirect github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37 // indirect - github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 // indirect + github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 // indirect github.com/smartcontractkit/chainlink-common/x/config v0.0.0-20260928140953-a9b0d3a04daa // indirect github.com/smartcontractkit/chainlink-data-streams v1.1.2-0.20261009064810-68424c714170 // indirect github.com/smartcontractkit/chainlink-evm/contracts/cre/gobindings v0.0.0-20260403151002-2c91155b5501 // indirect diff --git a/integration-tests/go.sum b/integration-tests/go.sum index af21626863c..3bc11225002 100644 --- a/integration-tests/go.sum +++ b/integration-tests/go.sum @@ -1396,12 +1396,12 @@ 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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 h1:2APdbnh8Uf/h/THKSZM3g2IW/10ah+ygqwMZltOlBqU= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360/go.mod h1:hdp2bQBzIDJt3UhXKnLz4OMHpsOW54Z9E9Txx4SVC8w= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 h1:nzm+zgN1C6kNVlQnlp3XlzqFl7g9K5h63mRyctvGNRE= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= -github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= -github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549/go.mod h1:Scyk7O80fde5rJF3Ty3fEE3xiS6j84eWbu8/2gl3pIY= +github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= +github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9/go.mod h1:Scyk7O80fde5rJF3Ty3fEE3xiS6j84eWbu8/2gl3pIY= github.com/smartcontractkit/chainlink-common/x/config v0.0.0-20260928140953-a9b0d3a04daa h1:7yIjZpk1mYYu630yXcGR7N+a+pcAHvn4OHlfhJK8GGY= github.com/smartcontractkit/chainlink-common/x/config v0.0.0-20260928140953-a9b0d3a04daa/go.mod h1:nfT8vdE44iAlhDWDV6PaBWucxZZAcDsgGkZ+D0kHpAI= github.com/smartcontractkit/chainlink-data-streams v1.1.2-0.20261009064810-68424c714170 h1:HeQlHO9MrUXTJmxYCNX4xPX14glLAdwIN3igc9Am/g8= diff --git a/integration-tests/load/go.mod b/integration-tests/load/go.mod index 3a48b7ec505..2747299cb57 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-20260916222901-720a003dab50 github.com/smartcontractkit/chainlink-ccip/chains/solana/gobindings v0.0.0-20260916222901-720a003dab50 - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261022195454-600e2b321c7a github.com/smartcontractkit/chainlink-testing-framework/framework v0.16.9 @@ -476,7 +476,7 @@ require ( github.com/smartcontractkit/chainlink-ccip/deployment v0.0.0-20261001213322-a2d686f610ca // indirect github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37 // indirect github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd // indirect - github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 // indirect + github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 // indirect github.com/smartcontractkit/chainlink-common/x/config v0.0.0-20260928140953-a9b0d3a04daa // indirect github.com/smartcontractkit/chainlink-data-streams v1.1.2-0.20261009064810-68424c714170 // indirect github.com/smartcontractkit/chainlink-evm/contracts/cre/gobindings v0.0.0-20260403151002-2c91155b5501 // indirect diff --git a/integration-tests/load/go.sum b/integration-tests/load/go.sum index 96d4c66a9d8..57597143855 100644 --- a/integration-tests/load/go.sum +++ b/integration-tests/load/go.sum @@ -1636,12 +1636,12 @@ 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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 h1:2APdbnh8Uf/h/THKSZM3g2IW/10ah+ygqwMZltOlBqU= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360/go.mod h1:hdp2bQBzIDJt3UhXKnLz4OMHpsOW54Z9E9Txx4SVC8w= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 h1:nzm+zgN1C6kNVlQnlp3XlzqFl7g9K5h63mRyctvGNRE= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= -github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= -github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549/go.mod h1:Scyk7O80fde5rJF3Ty3fEE3xiS6j84eWbu8/2gl3pIY= +github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= +github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9/go.mod h1:Scyk7O80fde5rJF3Ty3fEE3xiS6j84eWbu8/2gl3pIY= github.com/smartcontractkit/chainlink-common/x/config v0.0.0-20260928140953-a9b0d3a04daa h1:7yIjZpk1mYYu630yXcGR7N+a+pcAHvn4OHlfhJK8GGY= github.com/smartcontractkit/chainlink-common/x/config v0.0.0-20260928140953-a9b0d3a04daa/go.mod h1:nfT8vdE44iAlhDWDV6PaBWucxZZAcDsgGkZ+D0kHpAI= github.com/smartcontractkit/chainlink-data-streams v1.1.2-0.20261009064810-68424c714170 h1:HeQlHO9MrUXTJmxYCNX4xPX14glLAdwIN3igc9Am/g8= diff --git a/system-tests/lib/go.mod b/system-tests/lib/go.mod index 4d2ec1df93b..1d0ce30854a 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-20260916222901-720a003dab50 - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd github.com/smartcontractkit/chainlink-confidential-compute v1.3.0 github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 @@ -486,7 +486,7 @@ require ( github.com/smartcontractkit/chainlink-ccip/chains/solana/gobindings v0.0.0-20260916222901-720a003dab50 // indirect github.com/smartcontractkit/chainlink-ccip/deployment v0.0.0-20261001213322-a2d686f610ca // indirect github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37 // indirect - github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 // indirect + github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 // indirect github.com/smartcontractkit/chainlink-common/x/config v0.0.0-20260928140953-a9b0d3a04daa // indirect github.com/smartcontractkit/chainlink-data-streams v1.1.2-0.20261009064810-68424c714170 // indirect github.com/smartcontractkit/chainlink-evm/contracts/cre/gobindings v0.0.0-20260403151002-2c91155b5501 // indirect diff --git a/system-tests/lib/go.sum b/system-tests/lib/go.sum index 48828ac54a2..203956afb5e 100644 --- a/system-tests/lib/go.sum +++ b/system-tests/lib/go.sum @@ -1657,12 +1657,12 @@ 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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 h1:2APdbnh8Uf/h/THKSZM3g2IW/10ah+ygqwMZltOlBqU= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360/go.mod h1:hdp2bQBzIDJt3UhXKnLz4OMHpsOW54Z9E9Txx4SVC8w= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 h1:nzm+zgN1C6kNVlQnlp3XlzqFl7g9K5h63mRyctvGNRE= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= -github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= -github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549/go.mod h1:Scyk7O80fde5rJF3Ty3fEE3xiS6j84eWbu8/2gl3pIY= +github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= +github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9/go.mod h1:Scyk7O80fde5rJF3Ty3fEE3xiS6j84eWbu8/2gl3pIY= github.com/smartcontractkit/chainlink-common/x/config v0.0.0-20260928140953-a9b0d3a04daa h1:7yIjZpk1mYYu630yXcGR7N+a+pcAHvn4OHlfhJK8GGY= github.com/smartcontractkit/chainlink-common/x/config v0.0.0-20260928140953-a9b0d3a04daa/go.mod h1:nfT8vdE44iAlhDWDV6PaBWucxZZAcDsgGkZ+D0kHpAI= github.com/smartcontractkit/chainlink-confidential-compute v1.3.0 h1:y64hOzM9H61E4EYRzQDtRwqunDBlKpsZc1SvFEUlSLE= diff --git a/system-tests/tests/go.mod b/system-tests/tests/go.mod index ad2b048379f..bf80ac8f49d 100644 --- a/system-tests/tests/go.mod +++ b/system-tests/tests/go.mod @@ -73,9 +73,9 @@ 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-20260916222901-720a003dab50 - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd - github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 + github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 github.com/smartcontractkit/chainlink-confidential-compute v1.3.0 github.com/smartcontractkit/chainlink-confidential-compute/tests/testhelpers v0.0.0-20260812145307-d77342c53d7d github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 diff --git a/system-tests/tests/go.sum b/system-tests/tests/go.sum index 997f758cb2d..0abf9c77984 100644 --- a/system-tests/tests/go.sum +++ b/system-tests/tests/go.sum @@ -1836,12 +1836,12 @@ 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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360 h1:2APdbnh8Uf/h/THKSZM3g2IW/10ah+ygqwMZltOlBqU= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261109132522-ceedd30df360/go.mod h1:hdp2bQBzIDJt3UhXKnLz4OMHpsOW54Z9E9Txx4SVC8w= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 h1:nzm+zgN1C6kNVlQnlp3XlzqFl7g9K5h63mRyctvGNRE= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= -github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= -github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549/go.mod h1:Scyk7O80fde5rJF3Ty3fEE3xiS6j84eWbu8/2gl3pIY= +github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= +github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9/go.mod h1:Scyk7O80fde5rJF3Ty3fEE3xiS6j84eWbu8/2gl3pIY= github.com/smartcontractkit/chainlink-common/x/config v0.0.0-20260928140953-a9b0d3a04daa h1:7yIjZpk1mYYu630yXcGR7N+a+pcAHvn4OHlfhJK8GGY= github.com/smartcontractkit/chainlink-common/x/config v0.0.0-20260928140953-a9b0d3a04daa/go.mod h1:nfT8vdE44iAlhDWDV6PaBWucxZZAcDsgGkZ+D0kHpAI= github.com/smartcontractkit/chainlink-confidential-compute v1.3.0 h1:y64hOzM9H61E4EYRzQDtRwqunDBlKpsZc1SvFEUlSLE= From 711d0547a2c27220849b4492f232be13add05f4e Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Fri, 13 Nov 2026 05:43:58 -0600 Subject: [PATCH 07/38] cleanup & fixes --- core/services/ocr2/delegate.go | 21 ++- core/services/ocr3_1/plugins/queue/blobs.go | 48 +++++- .../ocr3_1/plugins/queue/blobs_test.go | 80 ++++++++++ core/services/ocr3_1/plugins/queue/kvstate.go | 140 +++++++++--------- core/services/ocr3_1/plugins/queue/math.go | 52 +++++++ core/services/ocr3_1/plugins/queue/queue.go | 135 +++++++++-------- .../ocr3_1/plugins/queue/queue_test.go | 1 + .../ocr3_1/plugins/queue/transmitter.go | 45 +----- 8 files changed, 326 insertions(+), 196 deletions(-) create mode 100644 core/services/ocr3_1/plugins/queue/blobs_test.go create mode 100644 core/services/ocr3_1/plugins/queue/math.go create mode 100644 core/services/ocr3_1/plugins/queue/queue_test.go diff --git a/core/services/ocr2/delegate.go b/core/services/ocr2/delegate.go index fd6aaf65896..4d2bfb273c8 100644 --- a/core/services/ocr2/delegate.go +++ b/core/services/ocr2/delegate.go @@ -877,17 +877,16 @@ func (d *Delegate) newServicesConsensusQueue( BinaryNetworkEndpointFactory: d.peerWrapper.Peer3_1, V2Bootstrappers: bootstrapPeers, ContractConfigTracker: configTracker, - //TODO pass engine as EventSink - ContractTransmitter: queue.NewTransmitter(lggr, ocrtypes.Account(spec.TransmitterID.String), nil), - Database: ocrDB, - KeyValueDatabaseFactory: kvFactory, - LocalConfig: lc, - Logger: ocrLogger, - MonitoringEndpoint: oracleEndpoint, - OffchainConfigDigester: configDigester, - OffchainKeyring: kb, - OnchainKeyring: ocr3shims.OnchainKeyringAsOnchainKeyring2(onchainKeyringAdapter), - MetricsRegisterer: prometheus.WrapRegistererWith(map[string]string{"job_name": jb.Name.ValueOrZero()}, prometheus.DefaultRegisterer), + ContractTransmitter: queue.NewTransmitter(ocrtypes.Account(spec.TransmitterID.String)), + Database: ocrDB, + KeyValueDatabaseFactory: kvFactory, + LocalConfig: lc, + Logger: ocrLogger, + MonitoringEndpoint: oracleEndpoint, + OffchainConfigDigester: configDigester, + OffchainKeyring: kb, + OnchainKeyring: ocr3shims.OnchainKeyringAsOnchainKeyring2(onchainKeyringAdapter), + MetricsRegisterer: prometheus.WrapRegistererWith(map[string]string{"job_name": jb.Name.ValueOrZero()}, prometheus.DefaultRegisterer), } rpf, err := queue.NewConsensusQueuePluginFactory(lggr, cfg, d.limitsFactory, d.triggerCoordinator) diff --git a/core/services/ocr3_1/plugins/queue/blobs.go b/core/services/ocr3_1/plugins/queue/blobs.go index 492b0d2c9fb..df2ef7aa753 100644 --- a/core/services/ocr3_1/plugins/queue/blobs.go +++ b/core/services/ocr3_1/plugins/queue/blobs.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types" + "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/proto" "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb" @@ -20,16 +21,47 @@ func fetchFromBlob(ctx context.Context, fetcher ocr3_1types.BlobFetcher, handle if err != nil { return nil, nil, fmt.Errorf("failed to fetch blob: %w", err) } - //TODO optimize using protowire to avoid unmarshalling the entire blob - var coordEvents *pb.CoordinatedEventList - if err := proto.Unmarshal(b, coordEvents); err != nil { - return nil, nil, fmt.Errorf("failed to unmarshal blob: %w", err) + + coordEvent, err := extractEvent(b, idx) + if err != nil { + return nil, nil, err } - if idx >= len(coordEvents.Events) { - return nil, nil, fmt.Errorf("blob index %d is out of range for blob with %d events", idx, len(coordEvents.Events)) + return coordEvent, b, nil +} + +// extractEvent extracts the idx-th event from the blob, without unmarshaling any other events. +func extractEvent(b []byte, idx int) (*pb.CoordinatedEvent, error) { + //TODO can we lock this in with code? + const fieldNumber = 1 // pb.CoordinatedEventList.Events + i := 0 + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + if n < 0 { + return nil, protowire.ParseError(n) + } + b = b[n:] + if num == fieldNumber { + if typ != protowire.BytesType { + return nil, fmt.Errorf("expected bytes type for field %d, got %d", fieldNumber, typ) + } + v, m := protowire.ConsumeBytes(b) + if m < 0 { + return nil, protowire.ParseError(m) + } + if i == idx { + var event pb.CoordinatedEvent + if err := proto.Unmarshal(v, &event); err != nil { + return nil, fmt.Errorf("failed to unmarshal event: %w", err) + } + return &event, nil + } + // advance + i++ + b = b[m:] + continue + } } - coordEvent := coordEvents.Events[idx] - return coordEvent, nil, nil + return nil, fmt.Errorf("index %d out of range", idx) } // broadcastAsBlob broadcasts a list of coordinated events and returns a blob handle. 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..35e5b81028b --- /dev/null +++ b/core/services/ocr3_1/plugins/queue/blobs_test.go @@ -0,0 +1,80 @@ +package queue + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/anypb" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb" +) + +func Test_extractEvent(t *testing.T) { + 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) { + 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) + } + }) + } +} diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index 63c9ca955ac..d999b8edd26 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -16,46 +16,70 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb" ) -// KV store Keys +// KV store keys const ( - observedEventsKey = "observed_events::index" // observed events waiting for consensus (<2f+1 observers) - priorityQueueKey = "priority_queue::index" // priority queue of events waiting for capacity - consensusEventsKey = "consensus_events::index" // events the plugin committed to sending to nodes + // observed events waiting for consensus (<2f+1 observers) + observedEventsKey = "observed_events::index" // pb.ConsensusQueueObservedEvents { map[string]*pb.ConsensusQueueObservedEvent } + // priority queue of events waiting for capacity + priorityQueueKey = "priority_queue::index" // pb.ConsensusQueueEventList { []*pb.ConsensusQueueEvent } + // events the plugin committed to sending to nodes + consensusEventsKey = "consensus_events::index" // pb.ConsensusQueueEventList { []*pb.ConsensusQueueEvent } ) +type stateReader struct { + kv ocr3_1types.KeyValueStateReader +} + +type stateReadWriter struct { + stateReader + kv ocr3_1types.KeyValueStateReadWriter +} + +func newStateReadWriter(kv ocr3_1types.KeyValueStateReadWriter) stateReadWriter { + return stateReadWriter{stateReader: stateReader{kv: kv}, kv: kv} +} + +func (s stateReadWriter) 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) + } + return s.kv.Write([]byte(key), val) +} + // readObservedAndQueued reads both observed events and priority queue events from the KV store. func (s stateReader) readObservedAndQueued() (*observedAndQueued, error) { var obsQ observedAndQueued v, err := s.kv.Read([]byte(observedEventsKey)) if err != nil { - return nil, err + return nil, fmt.Errorf("failed to read observed events: %w", err) } if v != nil { - var queued *pb.ConsensusQueueObservedEvents - if err = proto.Unmarshal(v, queued); err != nil { + var observed *pb.ConsensusQueueObservedEvents + if err = proto.Unmarshal(v, observed); err != nil { return nil, err } - obsQ.observedEvents = queued.Observations + obsQ.observedEvents = observed.GetObservations() } else { obsQ.observedEvents = make(map[string]*pb.ConsensusQueueObservedEvent) } v, err = s.kv.Read([]byte(priorityQueueKey)) if err != nil { - return nil, err + return nil, fmt.Errorf("failed to read queued events: %w", err) } if v != nil { - var consensus *pb.ConsensusQueueEventList - if err = proto.Unmarshal(v, consensus); err != nil { + var queued *pb.ConsensusQueueEventList + if err = proto.Unmarshal(v, queued); err != nil { return nil, err } - obsQ.queuedEvents = new(priorityQueue(consensus.Events)) + obsQ.queuedEvents = new(priorityQueue(queued.GetEvents())) } return &obsQ, nil } -func (s stateReadWriter) update(state *observedAndQueued, consensus []*pb.ConsensusQueueEvent) error { +func (s stateReadWriter) writeAll(state *observedAndQueued, consensus []*pb.ConsensusQueueEvent) error { err := s.writeValue(observedEventsKey, &pb.ConsensusQueueObservedEvents{Observations: state.observedEvents}) if err != nil { return fmt.Errorf("failed to write observed events: %w", err) @@ -71,27 +95,6 @@ func (s stateReadWriter) update(state *observedAndQueued, consensus []*pb.Consen return nil } -type stateReader struct { - kv ocr3_1types.KeyValueStateReader -} - -type stateReadWriter struct { - stateReader - kv ocr3_1types.KeyValueStateReadWriter -} - -func newStateReadWriter(kv ocr3_1types.KeyValueStateReadWriter) stateReadWriter { - return stateReadWriter{stateReader: stateReader{kv: kv}, kv: kv} -} - -func (s stateReadWriter) writeValue[M proto.Message](key string, m M) error { - val, err := proto.MarshalOptions{Deterministic: true}.Marshal(m) - if err != nil { - return err - } - return s.kv.Write([]byte(key), val) -} - var _ heap.Interface = (*priorityQueue)(nil) // priorityQueue is a heap of coordinated events, ordered by deadline and then event ID. @@ -121,6 +124,19 @@ func (p *priorityQueue) Pop() any { func (p *priorityQueue) push(x *pb.ConsensusQueueEvent) { heap.Push(p, x) } +func (p *priorityQueue) pushObservations(blobHash string, event *pb.ConsensusQueueObservedEvent) { + p.push(&pb.ConsensusQueueEvent{ + WorkflowID: event.WorkflowID, + TriggerEventID: event.TriggerEventID, + ObservedAt: medianTimestamp(event.ObservedAts), + Deadline: medianTimestamp(event.Deadlines), + BlobHash: []byte(blobHash), + Blobs: event.Blobs, + }) +} + +// 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 len(*p) == 0 { return nil @@ -176,9 +192,10 @@ func (s *observedAndQueued) pruneExpiredObservations(expiration time.Time) { } } for _, i := range toDelete { - v.Deadlines = slices.Delete(v.Deadlines, i, i+1) - v.ObservedAts = slices.Delete(v.ObservedAts, i, i+1) v.NodeIds = slices.Delete(v.NodeIds, i, i+1) + v.ObservedAts = slices.Delete(v.ObservedAts, i, i+1) + v.Deadlines = slices.Delete(v.Deadlines, i, i+1) + v.Blobs = slices.Delete(v.Blobs, i, i+1) } return false @@ -186,54 +203,31 @@ func (s *observedAndQueued) pruneExpiredObservations(expiration time.Time) { } // TODO on promotion to priority queue, ack the trigger coordinator -func (s *observedAndQueued) addObservedEvents(f int, observedEvents map[string]*pb.ConsensusQueueObservedEvent) { - for blobHash, event := range observedEvents { - obs, ok := s.observedEvents[blobHash] - if !ok && len(event.NodeIds) >= 2*f+1 { +func (s *observedAndQueued) addObservedEvents(f int, toAdd map[string]*pb.ConsensusQueueObservedEvent) { + for blobHash, eventToAdd := range toAdd { + obsEvent, ok := s.observedEvents[blobHash] + if !ok && len(eventToAdd.NodeIds) >= 2*f+1 { // new proposal straight to priority queue - s.queuedEvents.push(&pb.ConsensusQueueEvent{ - WorkflowID: event.WorkflowID, - TriggerEventID: event.TriggerEventID, - ObservedAt: medianTimestamp(event.ObservedAts), - Deadline: medianTimestamp(event.Deadlines), - Blobs: event.Blobs, - }) + s.queuedEvents.pushObservations(blobHash, eventToAdd) } else if !ok { // new proposal < f + 1 - s.observedEvents[blobHash] = event + s.observedEvents[blobHash] = eventToAdd } else { // update proposal // TODO opt: build a map to avoid n^2? - for i, node := range event.NodeIds { - if !slices.Contains(obs.NodeIds, node) { - obs.NodeIds = append(obs.NodeIds, node) - obs.Deadlines = append(obs.Deadlines, event.Deadlines[i]) - obs.Blobs = append(obs.Blobs, event.Blobs[i]) + for i, node := range eventToAdd.NodeIds { + if !slices.Contains(obsEvent.NodeIds, node) { + obsEvent.NodeIds = append(obsEvent.NodeIds, node) + obsEvent.ObservedAts = append(obsEvent.ObservedAts, eventToAdd.ObservedAts[i]) + obsEvent.Deadlines = append(obsEvent.Deadlines, eventToAdd.Deadlines[i]) + obsEvent.Blobs = append(obsEvent.Blobs, eventToAdd.Blobs[i]) } //TODO what if a node reports twice with different deadline or nodeID? do we need to overwrite? } - if len(obs.NodeIds) >= 2*f+1 { + if len(obsEvent.NodeIds) >= 2*f+1 { // promote proposal to priority queue delete(s.observedEvents, blobHash) - s.queuedEvents.push(&pb.ConsensusQueueEvent{ - WorkflowID: event.WorkflowID, - TriggerEventID: event.TriggerEventID, - ObservedAt: medianTimestamp(event.ObservedAts), - Deadline: medianTimestamp(event.Deadlines), - Blobs: event.Blobs, - }) + s.queuedEvents.pushObservations(blobHash, obsEvent) } } } } - -func medianTimestamp(s []*timestamppb.Timestamp) *timestamppb.Timestamp { - var times []time.Time - for _, t := range s { - times = append(times, time.Unix(t.Seconds, int64(t.Nanos))) - } - slices.SortFunc(times, time.Time.Compare) - - a, b := times[len(times)/2], times[len(times)/2-1] - diff := a.Sub(b) - return timestamppb.New(a.Add(diff / 2)) -} 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..57962d67750 --- /dev/null +++ b/core/services/ocr3_1/plugins/queue/math.go @@ -0,0 +1,52 @@ +package queue + +import ( + "slices" + "time" + + "golang.org/x/exp/constraints" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// median returns the median value of a slice of integers. +// len must be greater than 0. +func median[N constraints.Integer, S []N](s S) N { + switch len(s) { + case 0: + panic("median: len must be greater than 0") + case 1: + return s[0] + } + slices.Sort(s) + if len(s)%2 == 1 { + return s[len(s)/2] + } + // avg of two + a, b := s[len(s)/2], s[len(s)/2-1] + diff := a - b + return b + diff/2 +} + +// 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/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index d248cb9a1c2..bbb27901ad4 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -7,11 +7,10 @@ import ( "errors" "fmt" "math" - "slices" "sync" "time" - "golang.org/x/exp/constraints" + "github.com/smartcontractkit/libocr/commontypes" "golang.org/x/sync/errgroup" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" @@ -26,7 +25,6 @@ import ( "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/v2/core/services/workflows/v2/triggers" ) @@ -45,6 +43,7 @@ func NewConsensusQueuePluginFactory(lggr logger.Logger, cfg *PluginConfig, limit cfg: cfg, triggerCoordinator: triggerCoordinator, expirationDur: func(ctx context.Context) (time.Duration, error) { + //TODO also allow this grace period in the trigger coordinator return cresettings.Default.ConsensusQueueExpirationInterval.GetOrDefault(ctx, limitsFactory.Settings) }, }, nil @@ -71,19 +70,20 @@ type consensusQueuePlugin struct { expirationDur func(context.Context) (time.Duration, error) } -func newConsensusQueuePlugin(lggr logger.Logger, onchainCfg ocr3types.ReportingPluginConfig, triggerCoordinator triggers.Coordinator, expirationGraceDur func(context.Context) (time.Duration, error), blobs ocr3_1types.BlobBroadcastFetcher) *consensusQueuePlugin { +func newConsensusQueuePlugin( + lggr logger.Logger, onchainCfg ocr3types.ReportingPluginConfig, triggerCoordinator triggers.Coordinator, + expirationGraceDur func(context.Context) (time.Duration, error), blobs ocr3_1types.BlobBroadcastFetcher, +) *consensusQueuePlugin { c := &consensusQueuePlugin{ lggr: logger.Named(lggr, "ConsensusQueuePlugin"), onchainCfg: onchainCfg, triggerCoordinator: triggerCoordinator, - expirationDur: expirationGraceDur, blobs: blobs, + expirationDur: expirationGraceDur, } c.Service, c.eng = services.Config{ - Name: "ConsensusQueueReportingPlugin", - Close: c.Close, + Name: "ConsensusQueueReportingPlugin", }.NewServiceEngine(lggr) - return c } @@ -92,7 +92,8 @@ func (c *consensusQueuePlugin) Query(_ context.Context, _ uint64, _ ocr3_1types. } func (c *consensusQueuePlugin) Observation( - ctx context.Context, seqNr uint64, _ ocrtypes.AttributedQuery, kvState ocr3_1types.KeyValueStateReader, blobs ocr3_1types.BlobBroadcastFetcher, + ctx context.Context, seqNr uint64, _ ocrtypes.AttributedQuery, kvState ocr3_1types.KeyValueStateReader, + blobs ocr3_1types.BlobBroadcastFetcher, ) (ocrtypes.Observation, error) { // Always attempt to start any executions from the KV Store in the event Committed was not called. // tryStartExecutions is idempotent. @@ -127,23 +128,25 @@ func (c *consensusQueuePlugin) Observation( const roundDur = 10 * time.Second //TODO dynamic calibration? expSeqNr := seqNr + uint64(expirationGraceDur/roundDur) //TODO pad extra time and/or rounds - pbEvents := make([]*pb.CoordinatedEvent, 0, len(events)) - for _, e := range events { - pbEvents = append(pbEvents, e.ToProto()) + pbEvents := make([]*pb.CoordinatedEvent, len(events)) + for i, e := range events { + pbEvents[i] = e.ToProto() } blobHandle, err := broadcastAsBlob(ctx, blobs, pbEvents, expSeqNr) if err != nil { return nil, err } - const maxObservationSize = 0 //TODO + const maxObservationSize = 0 //TODO from where? protoOpts := proto.MarshalOptions{Deterministic: true} for i, m := range pbEvents { // Try adding to batch - protoBytes, err := protoOpts.Marshal(m) //TODO opt: don't marshal again, get hash from broadcast helper - if err != nil { - //TODO log + observedAt, deadline := m.ObservedAt, m.Deadline + m.ObservedAt, m.Deadline = nil, nil // for consistent hashing + protoBytes, err2 := protoOpts.Marshal(m) //TODO opt: don't marshal again, get hash from broadcast helper + if err2 != nil { + c.lggr.Errorw("failed to marshal event", "eventID", m.Event.Event.Id, "err", err2) continue } blobHash := sha256.Sum256(protoBytes) @@ -151,7 +154,8 @@ func (c *consensusQueuePlugin) Observation( obs.Events = append(obs.Events, &pb.ConsensusQueueEvent{ WorkflowID: m.WorkflowID, TriggerEventID: m.Event.Event.Id, - Deadline: m.Deadline, + ObservedAt: observedAt, + Deadline: deadline, BlobHash: blobHash[:], Blobs: []*pb.CoordinatedEventBlobHandle{{ Handle: blobHandle, @@ -179,7 +183,7 @@ func (c *consensusQueuePlugin) Observation( } func (c *consensusQueuePlugin) ValidateObservation( - ctx context.Context, seqNr uint64, _ ocrtypes.AttributedQuery, ao ocrtypes.AttributedObservation, + ctx context.Context, _ uint64, _ ocrtypes.AttributedQuery, ao ocrtypes.AttributedObservation, _ ocr3_1types.KeyValueStateReader, blobs ocr3_1types.BlobFetcher, ) error { var obs pb.ConsensusQueueObservation @@ -196,7 +200,7 @@ func (c *consensusQueuePlugin) ValidateObservation( return nil }) } - return nil + return eg.Wait() } func validateObservedEvent(ctx context.Context, blobs ocr3_1types.BlobFetcher, event *pb.ConsensusQueueEvent) error { @@ -251,30 +255,28 @@ func validateObservedEvent(ctx context.Context, blobs ocr3_1types.BlobFetcher, e } 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, fetcher ocr3_1types.BlobFetcher, + ctx context.Context, _ uint64, _ ocrtypes.AttributedQuery, aos []ocrtypes.AttributedObservation, + kvState ocr3_1types.KeyValueStateReadWriter, _ ocr3_1types.BlobFetcher, ) (ocr3_1types.ReportsPlusPrecursor, error) { var done chan struct{} var obs observations go func() { defer close(done) - if warn := obs.aggregate(ctx, aos); warn != nil { - c.lggr.Warnw("Failed to aggregate some observations", "err", warn) - } + obs.aggregate(ctx, aos) }() stateRW := newStateReadWriter(kvState) state, err := stateRW.readObservedAndQueued() if err != nil { - return nil, err + return nil, fmt.Errorf("failed to read state: %w", err) } // wait for aggregation @@ -286,6 +288,12 @@ func (c *consensusQueuePlugin) StateTransition( return nil, err } } + if obs.err != nil { + return nil, fmt.Errorf("failed to aggregate observations: %w", obs.err) + } + if obs.warn != nil { + c.lggr.Warnw("Failed to aggregate some observations", "err", obs.warn) + } // update state state.pruneExpiredObservations(obs.medianExpiration) @@ -294,11 +302,9 @@ func (c *consensusQueuePlugin) StateTransition( if err != nil { return nil, err } - - // Updated KV Store //TODO might we hit a KV size limit in the middle of these? then what? can't just drop proposals // alternative: proposals only valid when there is definitely enough space - err = stateRW.update(state, consensusEvents) + err = stateRW.writeAll(state, consensusEvents) if err != nil { return nil, err } @@ -312,10 +318,12 @@ type observations struct { medianCap uint32 medianCapPerWF map[string]uint32 // wf ID -> capacity newObservedEvents map[string]*pb.ConsensusQueueObservedEvent // key: blobHash + warn error + err error } // TODO consider some configurable x% of capacity since some honest nodes have less -func (res *observations) aggregate(ctx context.Context, aos []ocrtypes.AttributedObservation) (warn error) { +func (res *observations) aggregate(ctx context.Context, aos []ocrtypes.AttributedObservation) { res.medianCapPerWF = make(map[string]uint32) res.newObservedEvents = make(map[string]*pb.ConsensusQueueObservedEvent) @@ -326,7 +334,7 @@ func (res *observations) aggregate(ctx context.Context, aos []ocrtypes.Attribute var obs pb.ConsensusQueueObservation err := proto.Unmarshal(ao.Observation, &obs) if err != nil { - warn = errors.Join(warn, fmt.Errorf("failed to unmarshal observation from oracle %d: %w", ao.Observation, err)) + res.warn = errors.Join(res.warn, fmt.Errorf("failed to unmarshal observation from oracle %d: %w", ao.Observation, err)) continue } expirations = append(expirations, obs.Expiration) @@ -338,44 +346,48 @@ func (res *observations) aggregate(ctx context.Context, aos []ocrtypes.Attribute if ctx.Err() != nil { return } - aggregated, ok := res.newObservedEvents[string(event.BlobHash)] - if !ok { - aggregated = &pb.ConsensusQueueObservedEvent{ - TriggerEventID: event.TriggerEventID, - WorkflowID: event.WorkflowID, - NodeIds: []uint8{uint8(ao.Observer)}, - ObservedAts: []*timestamppb.Timestamp{event.ObservedAt}, - Deadlines: []*timestamppb.Timestamp{event.Deadline}, - Blobs: []*pb.CoordinatedEventBlobHandle{event.Blobs[0]}, - } - } else { - // note: trigger event and workflow ID alignment is ensured by ValidateObservation - aggregated.NodeIds = append(aggregated.NodeIds, uint8(ao.Observer)) - aggregated.ObservedAts = append(aggregated.ObservedAts, event.ObservedAt) - aggregated.Deadlines = append(aggregated.Deadlines, event.Deadline) - aggregated.Blobs = append(aggregated.Blobs, event.Blobs...) - } - - res.newObservedEvents[string(event.BlobHash)] = aggregated + res.addEvent(ao.Observer, event) } } res.medianExpiration = medianTimestamp(expirations).AsTime() res.medianCap = median(capacities) - for wf, c := range wfCapacities { - res.medianCapPerWF[wf] = median(c) + for wf, caps := range wfCapacities { + res.medianCapPerWF[wf] = median(caps) } return } -func (c *consensusQueuePlugin) Committed(ctx context.Context, seqNr uint64, keyValueStateReader ocr3_1types.KeyValueStateReader) error { - c.tryStartExecutions(keyValueStateReader) +func (res *observations) addEvent(obs commontypes.OracleID, event *pb.ConsensusQueueEvent) { + aggregated, ok := res.newObservedEvents[string(event.BlobHash)] + if !ok { + aggregated = &pb.ConsensusQueueObservedEvent{ + TriggerEventID: event.TriggerEventID, + WorkflowID: event.WorkflowID, + NodeIds: []uint8{uint8(obs)}, + ObservedAts: []*timestamppb.Timestamp{event.ObservedAt}, + Deadlines: []*timestamppb.Timestamp{event.Deadline}, + Blobs: []*pb.CoordinatedEventBlobHandle{event.Blobs[0]}, + } + } 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) + aggregated.Blobs = append(aggregated.Blobs, event.Blobs...) + } + + res.newObservedEvents[string(event.BlobHash)] = aggregated +} + +func (c *consensusQueuePlugin) Committed(ctx context.Context, _ uint64, kvState ocr3_1types.KeyValueStateReader) error { + c.tryStartExecutions(kvState) return 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(reader ocr3_1types.KeyValueStateReader) { - v, err := reader.Read([]byte(consensusEventsKey)) +func (c *consensusQueuePlugin) tryStartExecutions(kvState ocr3_1types.KeyValueStateReader) { + v, err := kvState.Read([]byte(consensusEventsKey)) if err != nil { c.lggr.Errorw("Failed to read consensus events", "err", err) return @@ -435,19 +447,14 @@ func (c *consensusQueuePlugin) tryStartExecution(ctx context.Context, consensusE return nil } -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) { +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) { +func (c *consensusQueuePlugin) ShouldTransmitAcceptedReport(ctx context.Context, _ uint64, _ ocr3types.ReportWithInfo[[]byte]) (bool, error) { return false, nil } - -func median[N constraints.Integer, S []N](s S) N { - slices.Sort(s) - return (s[len(s)/2-1] + s[len(s)/2]) / 2 -} diff --git a/core/services/ocr3_1/plugins/queue/queue_test.go b/core/services/ocr3_1/plugins/queue/queue_test.go new file mode 100644 index 00000000000..c969bad24a4 --- /dev/null +++ b/core/services/ocr3_1/plugins/queue/queue_test.go @@ -0,0 +1 @@ +package queue diff --git a/core/services/ocr3_1/plugins/queue/transmitter.go b/core/services/ocr3_1/plugins/queue/transmitter.go index 42c3ddeae95..4c43d022f08 100644 --- a/core/services/ocr3_1/plugins/queue/transmitter.go +++ b/core/services/ocr3_1/plugins/queue/transmitter.go @@ -2,58 +2,23 @@ package queue import ( "context" - "fmt" "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" - "google.golang.org/protobuf/proto" - - "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb" - "github.com/smartcontractkit/chainlink-common/pkg/logger" - "github.com/smartcontractkit/chainlink/v2/core/services/workflows/v2/triggers" ) -type contractTransmitter struct { - lggr logger.Logger +type noopTransmitter struct { fromAccount ocrtypes.Account - eventSink triggers.EventSink } -func NewTransmitter(lggr logger.Logger, fromAccount ocrtypes.Account, eventSink triggers.EventSink) ocr3types.ContractTransmitter[[]byte] { - return &contractTransmitter{ - lggr: lggr, - fromAccount: fromAccount, - eventSink: eventSink, - } +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 { - //TODO relocate & replace with no-op? - var report pb.CoordinatedEventList - err := proto.Unmarshal(rpi.Report, &report) - if err != nil { - return fmt.Errorf("failed to unmarshal report: %w", err) - } - // Execute each event - for _, message := range report.Events { - var event triggers.CoordinatedEvent - if err := event.FromProto(message); err != nil { - c.lggr.Errorw("Failed to convert trigger event proto", "err", err) - continue - } - if c.eventSink == nil { - c.lggr.Warnw("Unable to execute trigger - no event sink configured", "event", event) - continue - } - err := c.eventSink.ExecuteTrigger(ctx, event) - if err != nil { - c.lggr.Errorw("Failed to execute trigger", "event", event, "err", err) - } - } - +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 } From 90768bd230e30e11f2395d9dc855922e011435ba Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Mon, 16 Nov 2026 20:40:10 -0600 Subject: [PATCH 08/38] dedupe blobs --- core/scripts/go.mod | 2 +- core/scripts/go.sum | 4 +- core/services/ocr3_1/plugins/queue/blobs.go | 71 +++- .../ocr3_1/plugins/queue/blobs_test.go | 7 + core/services/ocr3_1/plugins/queue/config.go | 11 + core/services/ocr3_1/plugins/queue/kvstate.go | 336 +++++++++++++----- core/services/ocr3_1/plugins/queue/queue.go | 234 +++++++----- deployment/go.mod | 2 +- deployment/go.sum | 4 +- go.mod | 2 +- go.sum | 4 +- integration-tests/go.mod | 2 +- integration-tests/go.sum | 4 +- integration-tests/load/go.mod | 2 +- integration-tests/load/go.sum | 4 +- system-tests/lib/go.mod | 2 +- system-tests/lib/go.sum | 4 +- system-tests/tests/go.mod | 2 +- system-tests/tests/go.sum | 4 +- 19 files changed, 487 insertions(+), 214 deletions(-) diff --git a/core/scripts/go.mod b/core/scripts/go.mod index 53e0b3320f5..27d8a774e65 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.20261112195848-86be69f83e49 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117023719-a7ac77a0c012 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261022195454-600e2b321c7a diff --git a/core/scripts/go.sum b/core/scripts/go.sum index d5cf426b16e..8bce6ac7ebb 100644 --- a/core/scripts/go.sum +++ b/core/scripts/go.sum @@ -1686,8 +1686,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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 h1:nzm+zgN1C6kNVlQnlp3XlzqFl7g9K5h63mRyctvGNRE= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117023719-a7ac77a0c012 h1:7GCOxs3dYlwdm1lW+SI8hPXH0BC/uyUHkX9l8twglcM= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117023719-a7ac77a0c012/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/core/services/ocr3_1/plugins/queue/blobs.go b/core/services/ocr3_1/plugins/queue/blobs.go index df2ef7aa753..b3516ab8832 100644 --- a/core/services/ocr3_1/plugins/queue/blobs.go +++ b/core/services/ocr3_1/plugins/queue/blobs.go @@ -3,21 +3,51 @@ package queue import ( "context" "fmt" + "sync" - "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types" "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" ) -func fetchFromBlob(ctx context.Context, fetcher ocr3_1types.BlobFetcher, handle []byte, idx int) (*pb.CoordinatedEvent, []byte, error) { - var blobHandle ocr3_1types.BlobHandle - if err := blobHandle.UnmarshalBinary(handle); err != nil { - return nil, nil, fmt.Errorf("failed to unmarshal blob handle: %w", err) +// blobCache is a short-lived cache for coordinating concurrent fetches of event blobs. +type blobCache struct { + fetcher ocr3_1types.BlobFetcher + + mu sync.RWMutex + cache map[string]func() ([]byte, error) // blob handle -> blob +} + +func (c *blobCache) fetchBlob(ctx context.Context, handle []byte) ([]byte, error) { + c.mu.RLock() + if fn, ok := c.cache[string(handle)]; ok { + c.mu.RUnlock() + return fn() } - //TODO cache to fetch just once - b, err := fetcher.FetchBlob(ctx, blobHandle) + 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 + return fn() +} + +// fetchCoordinatedEventFromBlob fetches and extracts the idx-th event from the blob, without unmarshaling any other events. +func fetchCoordinatedEventFromBlob(ctx context.Context, fetcher *blobCache, handle []byte, idx int) (*pb.CoordinatedEvent, []byte, error) { + b, err := fetcher.fetchBlob(ctx, handle) if err != nil { return nil, nil, fmt.Errorf("failed to fetch blob: %w", err) } @@ -29,10 +59,10 @@ func fetchFromBlob(ctx context.Context, fetcher ocr3_1types.BlobFetcher, handle return coordEvent, b, nil } +const coordinatedEventsFieldNumber = 1 // pb.CoordinatedEventList.Events + // extractEvent extracts the idx-th event from the blob, without unmarshaling any other events. func extractEvent(b []byte, idx int) (*pb.CoordinatedEvent, error) { - //TODO can we lock this in with code? - const fieldNumber = 1 // pb.CoordinatedEventList.Events i := 0 for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) @@ -40,9 +70,9 @@ func extractEvent(b []byte, idx int) (*pb.CoordinatedEvent, error) { return nil, protowire.ParseError(n) } b = b[n:] - if num == fieldNumber { + if num == coordinatedEventsFieldNumber { if typ != protowire.BytesType { - return nil, fmt.Errorf("expected bytes type for field %d, got %d", fieldNumber, typ) + return nil, fmt.Errorf("expected bytes type for field %d, got %d", coordinatedEventsFieldNumber, typ) } v, m := protowire.ConsumeBytes(b) if m < 0 { @@ -65,15 +95,20 @@ func extractEvent(b []byte, idx int) (*pb.CoordinatedEvent, error) { } // broadcastAsBlob broadcasts a list of coordinated events and returns a blob handle. -func broadcastAsBlob(ctx context.Context, broadcaster ocr3_1types.BlobBroadcastFetcher, events []*pb.CoordinatedEvent, expSeq uint64) ([]byte, error) { - // TODO return a slice of hashes too; encode list with protowire to hash them along the way - w/ ZERO timestamps - data, err := proto.MarshalOptions{Deterministic: true}.Marshal(&pb.CoordinatedEventList{Events: events}) +func broadcastAsBlob(ctx context.Context, broadcaster ocr3_1types.BlobBroadcastFetcher, events []*pb.CoordinatedEvent, expSeq uint64) (blobHandle []byte, n int, err error) { + protoOpts := proto.MarshalOptions{Deterministic: true} + for ; protoOpts.Size(&pb.CoordinatedEventList{Events: events}) > maxBlobPayloadBytes; events = events[:len(events)-1] { + //TODO opt: binary search for largest fit instead.... + } + n = len(events) + data, err := protoOpts.Marshal(&pb.CoordinatedEventList{Events: events}) if err != nil { - return nil, fmt.Errorf("failed to marshal blob: %w", err) + return nil, -1, fmt.Errorf("failed to marshal blob: %w", err) } - blobHandle, err := broadcaster.BroadcastBlob(ctx, data, ocr3_1types.BlobExpirationHintSequenceNumber{SeqNr: expSeq}) + bh, err := broadcaster.BroadcastBlob(ctx, data, ocr3_1types.BlobExpirationHintSequenceNumber{SeqNr: expSeq}) if err != nil { - return nil, fmt.Errorf("failed to broadcast blob: %w", err) + return nil, -1, fmt.Errorf("failed to broadcast blob: %w", err) } - return blobHandle.MarshalBinary() + blobHandle, err = bh.MarshalBinary() + return } diff --git a/core/services/ocr3_1/plugins/queue/blobs_test.go b/core/services/ocr3_1/plugins/queue/blobs_test.go index 35e5b81028b..8a9041e5cf4 100644 --- a/core/services/ocr3_1/plugins/queue/blobs_test.go +++ b/core/services/ocr3_1/plugins/queue/blobs_test.go @@ -5,6 +5,7 @@ import ( "time" "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" @@ -78,3 +79,9 @@ func Test_extractEvent(t *testing.T) { }) } } + +func Test_coordinatedEventsFieldNumber(t *testing.T) { + fd := (&pb.CoordinatedEventList{}).ProtoReflect().Descriptor().Fields().ByName("events") + require.NotNil(t, fd) + require.Equal(t, protowire.Number(coordinatedEventsFieldNumber), fd.Number()) +} diff --git a/core/services/ocr3_1/plugins/queue/config.go b/core/services/ocr3_1/plugins/queue/config.go index b63436ca646..66486a55afa 100644 --- a/core/services/ocr3_1/plugins/queue/config.go +++ b/core/services/ocr3_1/plugins/queue/config.go @@ -4,6 +4,17 @@ import ( "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types" ) +const ( + maxObservedBlobHandles = 10 // sanity check on blobs in an observation + maxObservedEvents = 1000 // sanity check events in an observation + + //TODO reduce these? connect to cre settings? + maxObservationBytes = ocr3_1types.MaxMaxObservationBytes + maxKeyValueValueBytes = ocr3_1types.MaxMaxKeyValueKeyBytes + maxKeyValueModifiedKeysPlusValuesBytes = ocr3_1types.MaxMaxKeyValueModifiedKeysPlusValuesBytes + maxBlobPayloadBytes = ocr3_1types.MaxMaxBlobPayloadBytes +) + type PluginConfig struct { Limits ocr3_1types.ReportingPluginLimits `json:"limits,omitzero"` } diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index d999b8edd26..1866b6d0472 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -19,27 +19,24 @@ import ( // KV store keys const ( // observed events waiting for consensus (<2f+1 observers) - observedEventsKey = "observed_events::index" // pb.ConsensusQueueObservedEvents { map[string]*pb.ConsensusQueueObservedEvent } + observedEventsKey = "observed_events::index" // pb.ConsensusQueueObservedEvents { map[string]*pb.ConsensusQueueObservedEvent; [][]byte } // priority queue of events waiting for capacity - priorityQueueKey = "priority_queue::index" // pb.ConsensusQueueEventList { []*pb.ConsensusQueueEvent } + 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 stateReader struct { kv ocr3_1types.KeyValueStateReader } -type stateReadWriter struct { - stateReader +type stateWriter struct { kv ocr3_1types.KeyValueStateReadWriter } -func newStateReadWriter(kv ocr3_1types.KeyValueStateReadWriter) stateReadWriter { - return stateReadWriter{stateReader: stateReader{kv: kv}, kv: kv} -} - -func (s stateReadWriter) writeValue[M proto.Message](key string, m M) error { +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) @@ -47,54 +44,6 @@ func (s stateReadWriter) writeValue[M proto.Message](key string, m M) error { return s.kv.Write([]byte(key), val) } -// readObservedAndQueued reads both observed events and priority queue events from the KV store. -func (s stateReader) readObservedAndQueued() (*observedAndQueued, error) { - var obsQ observedAndQueued - v, err := s.kv.Read([]byte(observedEventsKey)) - if err != nil { - return nil, fmt.Errorf("failed to read observed events: %w", err) - } - if v != nil { - var observed *pb.ConsensusQueueObservedEvents - if err = proto.Unmarshal(v, observed); err != nil { - return nil, err - } - obsQ.observedEvents = observed.GetObservations() - } else { - obsQ.observedEvents = make(map[string]*pb.ConsensusQueueObservedEvent) - } - - v, err = s.kv.Read([]byte(priorityQueueKey)) - 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, err - } - obsQ.queuedEvents = new(priorityQueue(queued.GetEvents())) - } - - return &obsQ, nil -} - -func (s stateReadWriter) writeAll(state *observedAndQueued, consensus []*pb.ConsensusQueueEvent) error { - err := s.writeValue(observedEventsKey, &pb.ConsensusQueueObservedEvents{Observations: state.observedEvents}) - if err != nil { - return fmt.Errorf("failed to write observed events: %w", err) - } - err = s.writeValue(priorityQueueKey, &pb.ConsensusQueueEventList{Events: *state.queuedEvents}) - if err != nil { - return fmt.Errorf("failed to write queued events: %w", err) - } - err = s.writeValue(consensusEventsKey, &pb.ConsensusQueueEventList{Events: consensus}) - if err != nil { - return fmt.Errorf("failed to write consensus events: %w", err) - } - return nil -} - var _ heap.Interface = (*priorityQueue)(nil) // priorityQueue is a heap of coordinated events, ordered by deadline and then event ID. @@ -104,10 +53,13 @@ func (p *priorityQueue) Len() int { return len(*p) } func (p *priorityQueue) Less(i, j int) bool { a, b := (*p)[i], (*p)[j] + return cmpConsensusQueueEvents(a, b) < 0 +} +func cmpConsensusQueueEvents(a, b *pb.ConsensusQueueEvent) int { return cmp.Or(cmp.Compare(a.Deadline.Seconds, b.Deadline.Seconds), cmp.Compare(a.Deadline.Nanos, b.Deadline.Nanos), - cmp.Compare(a.TriggerEventID, b.TriggerEventID)) < 0 + cmp.Compare(a.TriggerEventID, b.TriggerEventID)) } func (p *priorityQueue) Swap(i, j int) { @@ -124,15 +76,17 @@ func (p *priorityQueue) Pop() any { func (p *priorityQueue) push(x *pb.ConsensusQueueEvent) { heap.Push(p, x) } -func (p *priorityQueue) pushObservations(blobHash string, event *pb.ConsensusQueueObservedEvent) { - p.push(&pb.ConsensusQueueEvent{ - WorkflowID: event.WorkflowID, - TriggerEventID: event.TriggerEventID, - ObservedAt: medianTimestamp(event.ObservedAts), - Deadline: medianTimestamp(event.Deadlines), - BlobHash: []byte(blobHash), - Blobs: event.Blobs, - }) +func (p *priorityQueue) pushObservations(timelessHash string, obs *pb.ConsensusQueueObservedEvent) *pb.ConsensusQueueEvent { + event := &pb.ConsensusQueueEvent{ + WorkflowID: obs.WorkflowID, + TriggerEventID: obs.TriggerEventID, + ObservedAt: medianTimestamp(obs.ObservedAts), + Deadline: medianTimestamp(obs.Deadlines), + TimelessHash: []byte(timelessHash), + Blobs: obs.Blobs, + } + p.push(event) + return event } // mustPop pops the next event from the queue, or returns nil if the queue is empty. @@ -146,7 +100,7 @@ func (p *priorityQueue) mustPop() *pb.ConsensusQueueEvent { // popLimited pops up to capacity events from the queue, each of which must also have sufficient wf capacity. // Note: capPerWF is mutated. -func (p *priorityQueue) popLimited(capacity uint32, capPerWF map[string]uint32, expiration time.Time) ([]*pb.ConsensusQueueEvent, error) { +func (p *priorityQueue) popLimited(capacity uint32, capPerWF map[string]uint32, expiration time.Time) []*pb.ConsensusQueueEvent { var events []*pb.ConsensusQueueEvent var wfLimited []*pb.ConsensusQueueEvent // omitted due to workflow limit for len(events) < int(capacity) { @@ -169,15 +123,185 @@ func (p *priorityQueue) popLimited(capacity uint32, capPerWF map[string]uint32, for _, event := range wfLimited { p.push(event) } - return events, nil + return events +} + +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 } -type observedAndQueued struct { - observedEvents map[string]*pb.ConsensusQueueObservedEvent // key: blobHash - queuedEvents *priorityQueue +func (m blobHandleMap) addAll(eventHash string, blobHandles map[string]uint32) { + if _, ok := m[eventHash]; !ok { + m[eventHash] = make(map[string]uint32) + } + for blobHandle, elementIndex := range blobHandles { + m[eventHash][blobHandle] = elementIndex + } +} + +type kvState struct { + // observedEventsKey + observedEvents map[string]*pb.ConsensusQueueObservedEvent // key: timeless hash + observedBlobs blobHandleMap + observedBlobHandles [][]byte // only populated before write + + // priorityQueueKey + queuedEvents *priorityQueue + // consensusEventsKey + consensusEvents []*pb.ConsensusQueueEvent + // blobHandlesKey + queuedBlobs blobHandleMap + queuedBlobHandles [][]byte // only populated before write } -func (s *observedAndQueued) pruneExpiredObservations(expiration time.Time) { +// 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 { + v, err := kv.Read([]byte(observedEventsKey)) + if err != nil { + return fmt.Errorf("failed to read observed events: %w", err) + } + s.observedBlobs = make(blobHandleMap) + if v != nil { + var observed *pb.ConsensusQueueObservedEvents + if err = proto.Unmarshal(v, observed); err != nil { + return fmt.Errorf("failed to unmarshal observed events: %w", err) + } + s.observedEvents = observed.GetObservations() + blobHandles := observed.GetBlobHandles() + for eventHash, event := range s.observedEvents { + for _, b := range event.GetBlobs() { + s.observedBlobs.add(eventHash, string(blobHandles[b.Blob]), b.Element) + } + } + } else { + s.observedEvents = make(map[string]*pb.ConsensusQueueObservedEvent) + } + + v, err = kv.Read([]byte(queuedEventsKey)) + if err != nil { + return 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 fmt.Errorf("failed to unmarshal queued events: %w", err) + } + s.queuedEvents = new(priorityQueue(queued.GetEvents())) + } + + s.queuedBlobs = make(blobHandleMap) + queuedBlobs, err := readBlobHandles(kv) + if err != nil { + return err + } + for _, event := range []*pb.ConsensusQueueEvent(*s.queuedEvents) { + for _, blob := range event.GetBlobs() { + s.queuedBlobs.add(string(event.TimelessHash), string(queuedBlobs[blob.Blob]), blob.Element) + } + } + + return nil +} + +// sizeOf returns the size of the state when serialized and written to the KV store via writeAll. +func (s *kvState) sizeOf() (size int) { + s.prepareWrite() + + //TODO check maxKeyValueValueBytes too? + + protoOpts := proto.MarshalOptions{Deterministic: true} + size += len(observedEventsKey) + len(queuedEventsKey) + len(consensusEventsKey) + len(blobHandlesKey) + size += protoOpts.Size(&pb.ConsensusQueueObservedEvents{Observations: s.observedEvents, BlobHandles: s.observedBlobHandles}) + size += protoOpts.Size(&pb.ConsensusQueueEventList{Events: *s.queuedEvents}) + size += protoOpts.Size(&pb.ConsensusQueueEventList{Events: s.consensusEvents}) + size += protoOpts.Size(&pb.ConsensusQueueBlobHandleList{BlobHandles: s.queuedBlobHandles}) + + return +} + +// prepareWrite initializes observed and queued blob handles and updates the event references. +func (s *kvState) prepareWrite() { + // gather blob handles and update events + s.observedBlobHandles = nil + observedBlobIndexes := make(map[string]int) + for _, eventHash := range slices.Sorted(maps.Keys(s.observedEvents)) { + event := s.observedEvents[eventHash] + event.Blobs = nil // replace all + for blobHandle, ei := range s.observedBlobs[eventHash] { + idx, ok := observedBlobIndexes[blobHandle] + if !ok { + idx = len(s.observedBlobHandles) + observedBlobIndexes[blobHandle] = idx + s.observedBlobHandles = append(s.observedBlobHandles, []byte(blobHandle)) + } + event.Blobs = append(event.Blobs, &pb.CoordinatedEventBlobHandle{ + Blob: uint32(idx), + Element: ei, + }) + } + } + + // gather blob handles and update events + s.queuedBlobHandles = nil + queuedBlobIndexes := make(map[string]int) + addBlobs := func(blobs map[string]uint32) []*pb.CoordinatedEventBlobHandle { + var blobHandles []*pb.CoordinatedEventBlobHandle + for blobHandle, ei := range blobs { + 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), + Element: ei, + }) + } + return blobHandles + } + for _, event := range []*pb.ConsensusQueueEvent(*s.queuedEvents) { + event.Blobs = addBlobs(s.queuedBlobs[string(event.TimelessHash)]) + } + for _, event := range s.consensusEvents { + event.Blobs = addBlobs(s.queuedBlobs[string(event.TimelessHash)]) + } +} + +// 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 { + //TODO MarshalOptions{UseCachedSize}? + + err := w.writeValue(observedEventsKey, &pb.ConsensusQueueObservedEvents{Observations: s.observedEvents, 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 +} + +func (s *kvState) pruneExpiredObservations(expiration time.Time) { unexpiredFn := func(t *timestamppb.Timestamp) bool { return t.AsTime().After(expiration) } maps.DeleteFunc(s.observedEvents, func(k string, v *pb.ConsensusQueueObservedEvent) bool { if !slices.ContainsFunc(v.Deadlines, unexpiredFn) { @@ -202,16 +326,19 @@ func (s *observedAndQueued) pruneExpiredObservations(expiration time.Time) { }) } -// TODO on promotion to priority queue, ack the trigger coordinator -func (s *observedAndQueued) addObservedEvents(f int, toAdd map[string]*pb.ConsensusQueueObservedEvent) { - for blobHash, eventToAdd := range toAdd { - obsEvent, ok := s.observedEvents[blobHash] +// addObserved adds the observed events to the set, promoting to the priority queue on 2f+1 and calling onQueued. +func (s *kvState) addObservedEvents(f int, toAdd map[string]*pb.ConsensusQueueObservedEvent, observedBlobs blobHandleMap, onQueued func(event *pb.ConsensusQueueEvent)) { + for eventHash, eventToAdd := range toAdd { + obsEvent, ok := s.observedEvents[eventHash] if !ok && len(eventToAdd.NodeIds) >= 2*f+1 { // new proposal straight to priority queue - s.queuedEvents.pushObservations(blobHash, eventToAdd) + s.queuedBlobs.addAll(eventHash, observedBlobs[eventHash]) + event := s.queuedEvents.pushObservations(eventHash, eventToAdd) + onQueued(event) } else if !ok { // new proposal < f + 1 - s.observedEvents[blobHash] = eventToAdd + s.observedBlobs.addAll(eventHash, observedBlobs[eventHash]) + s.observedEvents[eventHash] = eventToAdd } else { // update proposal // TODO opt: build a map to avoid n^2? @@ -221,13 +348,58 @@ func (s *observedAndQueued) addObservedEvents(f int, toAdd map[string]*pb.Consen obsEvent.ObservedAts = append(obsEvent.ObservedAts, eventToAdd.ObservedAts[i]) obsEvent.Deadlines = append(obsEvent.Deadlines, eventToAdd.Deadlines[i]) obsEvent.Blobs = append(obsEvent.Blobs, eventToAdd.Blobs[i]) - } //TODO what if a node reports twice with different deadline or nodeID? do we need to overwrite? + } //TODO what if a node reports twice with different deadline or observation? do we need to overwrite? } + if len(obsEvent.NodeIds) >= 2*f+1 { // promote proposal to priority queue - delete(s.observedEvents, blobHash) - s.queuedEvents.pushObservations(blobHash, obsEvent) + delete(s.observedEvents, eventHash) + s.queuedBlobs[eventHash] = s.observedBlobs[eventHash] + delete(s.observedBlobs, eventHash) + event := s.queuedEvents.pushObservations(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/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index bbb27901ad4..295392b6a9f 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "math" + "slices" "sync" "time" @@ -62,12 +63,13 @@ var _ ocr3_1types.ReportingPlugin[[]byte] = &consensusQueuePlugin{} type consensusQueuePlugin struct { services.Service - eng *services.Engine - lggr logger.Logger - onchainCfg ocr3types.ReportingPluginConfig - triggerCoordinator triggers.Coordinator - blobs ocr3_1types.BlobBroadcastFetcher - expirationDur func(context.Context) (time.Duration, error) + eng *services.Engine + lggr logger.Logger + onchainCfg ocr3types.ReportingPluginConfig + blobHandleMarshalledBytesUpperBound int + triggerCoordinator triggers.Coordinator + blobBroadcastFetcher ocr3_1types.BlobBroadcastFetcher + expirationDur func(context.Context) (time.Duration, error) } func newConsensusQueuePlugin( @@ -75,11 +77,12 @@ func newConsensusQueuePlugin( expirationGraceDur func(context.Context) (time.Duration, error), blobs ocr3_1types.BlobBroadcastFetcher, ) *consensusQueuePlugin { c := &consensusQueuePlugin{ - lggr: logger.Named(lggr, "ConsensusQueuePlugin"), - onchainCfg: onchainCfg, - triggerCoordinator: triggerCoordinator, - blobs: blobs, - expirationDur: expirationGraceDur, + lggr: logger.Named(lggr, "ConsensusQueuePlugin"), + onchainCfg: onchainCfg, + blobHandleMarshalledBytesUpperBound: ocr3_1types.BlobHandleMarshalledBytesUpperBound(onchainCfg.F, onchainCfg.N), + triggerCoordinator: triggerCoordinator, + blobBroadcastFetcher: blobs, + expirationDur: expirationGraceDur, } c.Service, c.eng = services.Config{ Name: "ConsensusQueueReportingPlugin", @@ -92,31 +95,33 @@ func (c *consensusQueuePlugin) Query(_ context.Context, _ uint64, _ ocr3_1types. } func (c *consensusQueuePlugin) Observation( - ctx context.Context, seqNr uint64, _ ocrtypes.AttributedQuery, kvState ocr3_1types.KeyValueStateReader, - blobs ocr3_1types.BlobBroadcastFetcher, + ctx context.Context, seqNr uint64, _ ocrtypes.AttributedQuery, kvReader ocr3_1types.KeyValueStateReader, + blobBroadcaster ocr3_1types.BlobBroadcastFetcher, ) (ocrtypes.Observation, error) { // Always attempt to start any executions from the KV Store in the event Committed was not called. // tryStartExecutions is idempotent. - c.tryStartExecutions(kvState) + c.tryStartExecutions(kvReader) capacity, err := c.triggerCoordinator.AvailableCapacity(ctx) if err != nil { - //TODO or just log and make a best effort to observe events regardless? return nil, fmt.Errorf("failed to get available capacity: %w", err) } var events []triggers.CoordinatedEvent // TODO observe queue - but can't "take" - need to confirm during StateTransition + // ignore if observed in kv state already 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) + emptyBlobHandle := make([]byte, c.blobHandleMarshalledBytesUpperBound) obs := &pb.ConsensusQueueObservation{ - Events: make([]*pb.ConsensusQueueEvent, 0, len(events)), - Expiration: timestamppb.New(expiration), + Events: make([]*pb.ConsensusQueueEvent, 0, len(events)), + // placeholder for accurate size calculation + BlobHandles: slices.Repeat([][]byte{emptyBlobHandle}, maxObservedBlobHandles), + Expiration: timestamppb.New(time.Now().Add(-expirationGraceDur)), Capacity: uint32(min(capacity.Global, math.MaxUint32)), WorkflowCapacities: make(map[string]uint32), } @@ -125,76 +130,111 @@ func (c *consensusQueuePlugin) Observation( obs.WorkflowCapacities[wf] = uint32(min(wfCap, math.MaxUint32)) } - const roundDur = 10 * time.Second //TODO dynamic calibration? - expSeqNr := seqNr + uint64(expirationGraceDur/roundDur) //TODO pad extra time and/or rounds - - pbEvents := make([]*pb.CoordinatedEvent, len(events)) + coordEvents := make([]*pb.CoordinatedEvent, len(events)) for i, e := range events { - pbEvents[i] = e.ToProto() + coordEvents[i] = e.ToProto() } - blobHandle, err := broadcastAsBlob(ctx, blobs, pbEvents, expSeqNr) - if err != nil { - return nil, err - } - - const maxObservationSize = 0 //TODO from where? protoOpts := proto.MarshalOptions{Deterministic: true} - for i, m := range pbEvents { + for i, coord := range coordEvents { //TODO iter.Seq from trigger coordinator // Try adding to batch - observedAt, deadline := m.ObservedAt, m.Deadline - m.ObservedAt, m.Deadline = nil, nil // for consistent hashing - protoBytes, err2 := protoOpts.Marshal(m) //TODO opt: don't marshal again, get hash from broadcast helper + observedAt, deadline := coord.ObservedAt, coord.Deadline + coord.ObservedAt, coord.Deadline = nil, nil // for consistent hashing + protoBytes, err2 := protoOpts.Marshal(coord) // TODO opt: avoid remarshalling if err2 != nil { - c.lggr.Errorw("failed to marshal event", "eventID", m.Event.Event.Id, "err", err2) + c.lggr.Errorw("failed to marshal event", "eventID", coord.Event.Event.Id, "err", err2) continue } - blobHash := sha256.Sum256(protoBytes) + timelessHash := sha256.Sum256(protoBytes) obs.Events = append(obs.Events, &pb.ConsensusQueueEvent{ - WorkflowID: m.WorkflowID, - TriggerEventID: m.Event.Event.Id, + WorkflowID: coord.WorkflowID, + TriggerEventID: coord.Event.Event.Id, ObservedAt: observedAt, Deadline: deadline, - BlobHash: blobHash[:], + TimelessHash: timelessHash[:], Blobs: []*pb.CoordinatedEventBlobHandle{{ - Handle: blobHandle, - Index: uint32(i), + Blob: 0, + Element: uint32(i), }}, }) var addedCap bool - if _, ok := obs.WorkflowCapacities[m.WorkflowID]; !ok { + if _, ok := obs.WorkflowCapacities[coord.WorkflowID]; !ok { addedCap = true - obs.WorkflowCapacities[m.WorkflowID] = uint32(min(capacity.PerWorkflow[m.WorkflowID], math.MaxUint32)) + obs.WorkflowCapacities[coord.WorkflowID] = uint32(min(capacity.PerWorkflow[coord.WorkflowID], math.MaxUint32)) } + // Check size - if protoOpts.Size(obs) > maxObservationSize { + if protoOpts.Size(obs) > maxObservationBytes { // too large, remove this one obs.Events = obs.Events[:len(obs.Events)-1] if addedCap { - delete(obs.WorkflowCapacities, m.WorkflowID) + delete(obs.WorkflowCapacities, coord.WorkflowID) } - //TODO opt: remember the blobHandle to avoid rebroadcasting events break } } + + roundDur := c.onchainCfg.EstimatedRoundInterval //TODO OK? + expSeqNr := seqNr + uint64(expirationGraceDur/roundDur) //TODO pad extra time and/or rounds? + + obs.BlobHandles = nil // remove the placeholders + if len(coordEvents) > 0 { + blobHandle, n, err2 := broadcastAsBlob(ctx, blobBroadcaster, coordEvents, expSeqNr) + if err2 != nil { + return nil, err2 + } + obs.BlobHandles = append(obs.BlobHandles, blobHandle) + // note: elements already reference blob 0 and natural element index is aligned + + var offset int + for batch := 1; n < len(coordEvents); batch++ { + offset += n + coordEvents = coordEvents[n:] + blobHandle, n, err2 = broadcastAsBlob(ctx, blobBroadcaster, coordEvents, expSeqNr) + if err2 != nil { + return nil, err2 + } + obs.BlobHandles = append(obs.BlobHandles, blobHandle) + for i := n; i < n; i++ { // update indices + obs.Events[offset+i].Blobs[0].Blob = uint32(batch) + obs.Events[offset+i].Blobs[0].Element = uint32(i) + } + } + } + return protoOpts.Marshal(obs) } func (c *consensusQueuePlugin) ValidateObservation( ctx context.Context, _ uint64, _ ocrtypes.AttributedQuery, ao ocrtypes.AttributedObservation, - _ ocr3_1types.KeyValueStateReader, blobs ocr3_1types.BlobFetcher, + _ ocr3_1types.KeyValueStateReader, blobFetcher ocr3_1types.BlobFetcher, ) error { var obs pb.ConsensusQueueObservation err := proto.Unmarshal(ao.Observation, &obs) if err != nil { return fmt.Errorf("failed to unmarshal observation: %w", err) } + if len(obs.BlobHandles) > 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") + } + //TODO what do we expect from WF capacities? check KV state and insist 100% match? or subset - none extra? + + if len(obs.Events) > maxObservedEvents { + return fmt.Errorf("events are limited to %d but got %d", maxObservedEvents, len(obs.Events)) + } + if !slices.IsSortedFunc(obs.Events, cmpConsensusQueueEvents) { + return fmt.Errorf("events must be sorted") + } 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 err := validateObservedEvent(ctx, blobs, event); err != nil { + if err := validateObservedEvent(ctx, &fetcher, event, obs.BlobHandles); err != nil { return fmt.Errorf("event %d failed validation: %w", i, err) } return nil @@ -203,22 +243,22 @@ func (c *consensusQueuePlugin) ValidateObservation( return eg.Wait() } -func validateObservedEvent(ctx context.Context, blobs ocr3_1types.BlobFetcher, event *pb.ConsensusQueueEvent) error { +func validateObservedEvent(ctx context.Context, fetcher *blobCache, event *pb.ConsensusQueueEvent, blobHandles [][]byte) error { if event.WorkflowID == "" { return errors.New("event workflow id is missing") - } + } ///TODO check not too long - exact length? if event.TriggerEventID == "" { return errors.New("event trigger event id is missing") - } + } ///TODO check not too long - exact length? if event.ObservedAt == nil { return errors.New("event observation ts is missing") } if event.Deadline == nil { return errors.New("event deadline is missing") } - if event.BlobHash == nil { + if event.TimelessHash == nil { return fmt.Errorf("event blob hash is missing") - } + } ///TODO check not too long - exact length? if len(event.Blobs) == 0 { return fmt.Errorf("event blob is missing") @@ -227,7 +267,13 @@ func validateObservedEvent(ctx context.Context, blobs ocr3_1types.BlobFetcher, e return fmt.Errorf("event has more than one blob") } - coordEvent, pbBytes, err := fetchFromBlob(ctx, blobs, event.Blobs[0].Handle, int(event.Blobs[0].Index)) + 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) } @@ -246,9 +292,9 @@ func validateObservedEvent(ctx context.Context, blobs ocr3_1types.BlobFetcher, e return fmt.Errorf("blob deadline timestamp is not nil: %v", coordEvent.Deadline) } - //TODO reduce allocations with a pool? - if shaSum := sha256.Sum256(pbBytes); !bytes.Equal(shaSum[:], event.BlobHash) { - return fmt.Errorf("blob hash %x does not match observation hash %x", shaSum, event.BlobHash) + //TODO opt: reduce allocations with a pool + 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 @@ -263,7 +309,7 @@ func (c *consensusQueuePlugin) ObservationQuorum( func (c *consensusQueuePlugin) StateTransition( ctx context.Context, _ uint64, _ ocrtypes.AttributedQuery, aos []ocrtypes.AttributedObservation, - kvState ocr3_1types.KeyValueStateReadWriter, _ ocr3_1types.BlobFetcher, + kvReaderWriter ocr3_1types.KeyValueStateReadWriter, _ ocr3_1types.BlobFetcher, ) (ocr3_1types.ReportsPlusPrecursor, error) { var done chan struct{} var obs observations @@ -273,8 +319,8 @@ func (c *consensusQueuePlugin) StateTransition( obs.aggregate(ctx, aos) }() - stateRW := newStateReadWriter(kvState) - state, err := stateRW.readObservedAndQueued() + var state kvState + err := state.loadFrom(kvReaderWriter) if err != nil { return nil, fmt.Errorf("failed to read state: %w", err) } @@ -297,27 +343,32 @@ func (c *consensusQueuePlugin) StateTransition( // update state state.pruneExpiredObservations(obs.medianExpiration) - state.addObservedEvents(c.onchainCfg.F, obs.newObservedEvents) - consensusEvents, err := state.queuedEvents.popLimited(obs.medianCap, obs.medianCapPerWF, obs.medianExpiration) - if err != nil { - return nil, err + state.addObservedEvents(c.onchainCfg.F, obs.newObservedEvents, obs.observedBlobs, func(queued *pb.ConsensusQueueEvent) { + //TODO ack the trigger coordinator - no longer need to observe this event + }) + state.consensusEvents = state.queuedEvents.popLimited(obs.medianCap, obs.medianCapPerWF, obs.medianExpiration) + + // prune observations until we fit + for state.sizeOf() > maxKeyValueModifiedKeysPlusValuesBytes { + //TODO drop observations (must be deterministic, fair, efficient) + // prefer farthest future deadlines and fewest observations } - //TODO might we hit a KV size limit in the middle of these? then what? can't just drop proposals - // alternative: proposals only valid when there is definitely enough space - err = stateRW.writeAll(state, consensusEvents) + + err = state.writeTo(&stateWriter{kv: kvReaderWriter}) if err != nil { return nil, err } // no report to return, executions start when committed - return ocr3_1types.ReportsPlusPrecursor{}, nil + return nil, nil } type observations struct { medianExpiration time.Time medianCap uint32 medianCapPerWF map[string]uint32 // wf ID -> capacity - newObservedEvents map[string]*pb.ConsensusQueueObservedEvent // key: blobHash + newObservedEvents map[string]*pb.ConsensusQueueObservedEvent // key: timeless hash + observedBlobs blobHandleMap warn error err error } @@ -346,7 +397,7 @@ func (res *observations) aggregate(ctx context.Context, aos []ocrtypes.Attribute if ctx.Err() != nil { return } - res.addEvent(ao.Observer, event) + res.addEvent(ao.Observer, event, obs.BlobHandles) } } res.medianExpiration = medianTimestamp(expirations).AsTime() @@ -357,57 +408,49 @@ func (res *observations) aggregate(ctx context.Context, aos []ocrtypes.Attribute return } -func (res *observations) addEvent(obs commontypes.OracleID, event *pb.ConsensusQueueEvent) { - aggregated, ok := res.newObservedEvents[string(event.BlobHash)] +func (res *observations) addEvent(obs commontypes.OracleID, event *pb.ConsensusQueueEvent, blobHandles [][]byte) { + res.observedBlobs.add(string(event.TimelessHash), string(blobHandles[event.Blobs[0].Blob]), event.Blobs[0].Element) + aggregated, ok := res.newObservedEvents[string(event.TimelessHash)] if !ok { - aggregated = &pb.ConsensusQueueObservedEvent{ + res.newObservedEvents[string(event.TimelessHash)] = &pb.ConsensusQueueObservedEvent{ TriggerEventID: event.TriggerEventID, WorkflowID: event.WorkflowID, NodeIds: []uint8{uint8(obs)}, ObservedAts: []*timestamppb.Timestamp{event.ObservedAt}, Deadlines: []*timestamppb.Timestamp{event.Deadline}, - Blobs: []*pb.CoordinatedEventBlobHandle{event.Blobs[0]}, + 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) - aggregated.Blobs = append(aggregated.Blobs, event.Blobs...) + // note: res.observedBlobs tracks blobs while in memory } - - res.newObservedEvents[string(event.BlobHash)] = aggregated } -func (c *consensusQueuePlugin) Committed(ctx context.Context, _ uint64, kvState ocr3_1types.KeyValueStateReader) error { - c.tryStartExecutions(kvState) +func (c *consensusQueuePlugin) Committed(ctx context.Context, _ uint64, kvReader ocr3_1types.KeyValueStateReader) error { + c.tryStartExecutions(kvReader) return 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(kvState ocr3_1types.KeyValueStateReader) { - v, err := kvState.Read([]byte(consensusEventsKey)) +func (c *consensusQueuePlugin) tryStartExecutions(kvReader ocr3_1types.KeyValueStateReader) { + consensusEvents, blobHandles, err := readConsensusState(kvReader) if err != nil { - c.lggr.Errorw("Failed to read consensus events", "err", err) + c.lggr.Errorw("Failed to read consensus state. Unable to execute events", "err", err) return } - var consensusEvents []*pb.ConsensusQueueEvent - if v != nil { - var pbs *pb.ConsensusQueueEventList - if err := proto.Unmarshal(v, pbs); err != nil { - c.lggr.Errorw("Failed to unmarshal consensus events", "err", err) - return - } - } + fetcher := blobCache{fetcher: c.blobBroadcastFetcher, cache: make(map[string]func() ([]byte, error))} var wg sync.WaitGroup for _, consensusEvent := range consensusEvents { wg.Add(1) c.eng.Go(func(ctx context.Context) { defer wg.Done() - if err2 := c.tryStartExecution(ctx, consensusEvent); err2 != nil { + if err2 := c.tryStartExecution(ctx, &fetcher, consensusEvent, blobHandles); err2 != nil { c.lggr.Errorw("Failed to execute event", "eventID", consensusEvent.TriggerEventID, "err", err2) return } @@ -416,16 +459,21 @@ func (c *consensusQueuePlugin) tryStartExecutions(kvState ocr3_1types.KeyValueSt wg.Wait() } -func (c *consensusQueuePlugin) tryStartExecution(ctx context.Context, consensusEvent *pb.ConsensusQueueEvent) error { +func (c *consensusQueuePlugin) tryStartExecution(ctx context.Context, fetcher *blobCache, consensusEvent *pb.ConsensusQueueEvent, blobHandles [][]byte) error { // any blob will do, first that exists var pbEvent *pb.CoordinatedEvent var errs []error for _, blob := range consensusEvent.Blobs { var err error - pbEvent, _, err = fetchFromBlob(ctx, c.blobs, blob.Handle, int(blob.Index)) + if int(blob.Blob) > len(blobHandles) { + c.lggr.Errorw("Blob handle index out of bounds", "index", int(blob.Blob), "len", len(blobHandles)) + continue + } + blobHandle := blobHandles[int(blob.Blob)] + pbEvent, _, err = fetchCoordinatedEventFromBlob(ctx, fetcher, blobHandle, int(blob.Element)) if err != nil { errs = append(errs, fmt.Errorf("failed to fetch blob: %w", err)) - c.lggr.Warnw("Failed to fetch blob", "handle", blob.Handle, "index", blob.Index, "err", err) + c.lggr.Errorw("Failed to fetch blob", "handle", blobHandle, "index", blob.Element, "err", err) continue // try next blob } break diff --git a/deployment/go.mod b/deployment/go.mod index d3be9e9c97e..dd62620f2b2 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-20260916222901-720a003dab50 github.com/smartcontractkit/chainlink-ccip/deployment v0.0.0-20261001213322-a2d686f610ca - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117023719-a7ac77a0c012 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd github.com/smartcontractkit/chainlink-data-streams v1.1.2-0.20261009064810-68424c714170 github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 diff --git a/deployment/go.sum b/deployment/go.sum index e1a6402cf6a..24a7a64efeb 100644 --- a/deployment/go.sum +++ b/deployment/go.sum @@ -1411,8 +1411,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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 h1:nzm+zgN1C6kNVlQnlp3XlzqFl7g9K5h63mRyctvGNRE= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117023719-a7ac77a0c012 h1:7GCOxs3dYlwdm1lW+SI8hPXH0BC/uyUHkX9l8twglcM= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117023719-a7ac77a0c012/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/go.mod b/go.mod index 8485ebe8c95..45b546755e3 100644 --- a/go.mod +++ b/go.mod @@ -82,7 +82,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.15.1-0.20261020204039-1a47492cdb37 - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117023719-a7ac77a0c012 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260903141829-ef07b52a737d github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 github.com/smartcontractkit/chainlink-data-streams v1.1.2-0.20261009064810-68424c714170 diff --git a/go.sum b/go.sum index 2bf1e20560a..f290b59aaad 100644 --- a/go.sum +++ b/go.sum @@ -1104,8 +1104,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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 h1:nzm+zgN1C6kNVlQnlp3XlzqFl7g9K5h63mRyctvGNRE= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117023719-a7ac77a0c012 h1:7GCOxs3dYlwdm1lW+SI8hPXH0BC/uyUHkX9l8twglcM= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117023719-a7ac77a0c012/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260903141829-ef07b52a737d h1:M9xuiIvdiHtim4nlxCVajyC/Mk63tAg9ESWb/biAhNA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260903141829-ef07b52a737d/go.mod h1:rI2njmTlyTvh+xhmORmK6qX3+V1ycDAqGJLu8LS8WpU= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/integration-tests/go.mod b/integration-tests/go.mod index 3d443a8161e..9abd4744c11 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-20260916222901-720a003dab50 github.com/smartcontractkit/chainlink-ccip/chains/solana/gobindings v0.0.0-20260916222901-720a003dab50 - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117023719-a7ac77a0c012 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261022195454-600e2b321c7a diff --git a/integration-tests/go.sum b/integration-tests/go.sum index 3bc11225002..0388798fb35 100644 --- a/integration-tests/go.sum +++ b/integration-tests/go.sum @@ -1396,8 +1396,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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 h1:nzm+zgN1C6kNVlQnlp3XlzqFl7g9K5h63mRyctvGNRE= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117023719-a7ac77a0c012 h1:7GCOxs3dYlwdm1lW+SI8hPXH0BC/uyUHkX9l8twglcM= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117023719-a7ac77a0c012/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/integration-tests/load/go.mod b/integration-tests/load/go.mod index 2747299cb57..42e3c7558a4 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-20260916222901-720a003dab50 github.com/smartcontractkit/chainlink-ccip/chains/solana/gobindings v0.0.0-20260916222901-720a003dab50 - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117023719-a7ac77a0c012 github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261022195454-600e2b321c7a 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 57597143855..45bba0ba2c8 100644 --- a/integration-tests/load/go.sum +++ b/integration-tests/load/go.sum @@ -1636,8 +1636,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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 h1:nzm+zgN1C6kNVlQnlp3XlzqFl7g9K5h63mRyctvGNRE= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117023719-a7ac77a0c012 h1:7GCOxs3dYlwdm1lW+SI8hPXH0BC/uyUHkX9l8twglcM= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117023719-a7ac77a0c012/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/system-tests/lib/go.mod b/system-tests/lib/go.mod index 1d0ce30854a..475ce862d16 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-20260916222901-720a003dab50 - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117023719-a7ac77a0c012 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd 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 203956afb5e..47ec29cc611 100644 --- a/system-tests/lib/go.sum +++ b/system-tests/lib/go.sum @@ -1657,8 +1657,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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 h1:nzm+zgN1C6kNVlQnlp3XlzqFl7g9K5h63mRyctvGNRE= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117023719-a7ac77a0c012 h1:7GCOxs3dYlwdm1lW+SI8hPXH0BC/uyUHkX9l8twglcM= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117023719-a7ac77a0c012/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/system-tests/tests/go.mod b/system-tests/tests/go.mod index bf80ac8f49d..b0943c93185 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-20260916222901-720a003dab50 - github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117023719-a7ac77a0c012 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 github.com/smartcontractkit/chainlink-confidential-compute v1.3.0 diff --git a/system-tests/tests/go.sum b/system-tests/tests/go.sum index 0abf9c77984..64aef864d85 100644 --- a/system-tests/tests/go.sum +++ b/system-tests/tests/go.sum @@ -1836,8 +1836,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.15.1-0.20261020204039-1a47492cdb37 h1:eZj3cJUTFmbpuRMsUwAM99QYPRiD4udbfcuRLWZ2WWg= github.com/smartcontractkit/chainlink-ccv v0.15.1-0.20261020204039-1a47492cdb37/go.mod h1:A107VkPT8sqCjZJ/2GULxEQOaky70t5tkcE7hK9NDpI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49 h1:nzm+zgN1C6kNVlQnlp3XlzqFl7g9K5h63mRyctvGNRE= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261112195848-86be69f83e49/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117023719-a7ac77a0c012 h1:7GCOxs3dYlwdm1lW+SI8hPXH0BC/uyUHkX9l8twglcM= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117023719-a7ac77a0c012/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd h1:5pkLw8ZJwMPc27ccq335YullY+kHYiPCIqCvk6zJvBA= github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20260923164324-86cd57d9fdbd/go.mod h1:r8u2d+ZpMweYchIytSRmkRFR+aKQ5c7/HoNv2hzuoTY= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= From 0a0595caeca194aaf21accaccdf2b269d3230df3 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Tue, 17 Nov 2026 17:57:44 -0600 Subject: [PATCH 09/38] cleanup; medianization; swap map for entries --- core/scripts/go.mod | 2 +- core/scripts/go.sum | 4 +- core/services/ocr3_1/plugins/queue/kvstate.go | 64 ++++++++++------- core/services/ocr3_1/plugins/queue/math.go | 25 +++++-- core/services/ocr3_1/plugins/queue/queue.go | 69 ++++++++++++++----- deployment/go.mod | 2 +- deployment/go.sum | 4 +- go.mod | 2 +- go.sum | 4 +- integration-tests/go.mod | 2 +- integration-tests/go.sum | 4 +- integration-tests/load/go.mod | 2 +- integration-tests/load/go.sum | 4 +- .../lib/cre/environment/environment.go | 43 ------------ system-tests/lib/go.mod | 2 +- system-tests/lib/go.sum | 4 +- system-tests/tests/go.mod | 2 +- system-tests/tests/go.sum | 4 +- 18 files changed, 133 insertions(+), 110 deletions(-) diff --git a/core/scripts/go.mod b/core/scripts/go.mod index 833acd8fcd6..b1bee600bdd 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.20261117161043-d7bfae650337 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5 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.20261112211734-e640e1c12078 diff --git a/core/scripts/go.sum b/core/scripts/go.sum index 50ecabb3aef..fddbfc28b6b 100644 --- a/core/scripts/go.sum +++ b/core/scripts/go.sum @@ -1686,8 +1686,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.20261117161043-d7bfae650337 h1:pD5MmKg+G52nkA4ghoVFqUtkAtZsUyGOSBY+P3JFE+M= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117161043-d7bfae650337/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5 h1:V+IBcXmheTxfYQb8gX/2KFjcIwiPSz6hvJ5MmOh9hjI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index 1866b6d0472..0344ed52ddd 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -146,9 +146,10 @@ func (m blobHandleMap) addAll(eventHash string, blobHandles map[string]uint32) { type kvState struct { // observedEventsKey - observedEvents map[string]*pb.ConsensusQueueObservedEvent // key: timeless hash - observedBlobs blobHandleMap - observedBlobHandles [][]byte // only populated before write + observedEvents map[string]*pb.ConsensusQueueObservedEvent // key: timeless hash + observedEventEntries []*pb.ConsensusQueueObservedEventEntry // only populated before write + observedBlobs blobHandleMap + observedBlobHandles [][]byte // only populated before write // priorityQueueKey queuedEvents *priorityQueue @@ -161,28 +162,13 @@ type kvState struct { // 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 { - v, err := kv.Read([]byte(observedEventsKey)) + var err error + s.observedEvents, s.observedBlobs, err = readObservedEvents(kv) if err != nil { - return fmt.Errorf("failed to read observed events: %w", err) - } - s.observedBlobs = make(blobHandleMap) - if v != nil { - var observed *pb.ConsensusQueueObservedEvents - if err = proto.Unmarshal(v, observed); err != nil { - return fmt.Errorf("failed to unmarshal observed events: %w", err) - } - s.observedEvents = observed.GetObservations() - blobHandles := observed.GetBlobHandles() - for eventHash, event := range s.observedEvents { - for _, b := range event.GetBlobs() { - s.observedBlobs.add(eventHash, string(blobHandles[b.Blob]), b.Element) - } - } - } else { - s.observedEvents = make(map[string]*pb.ConsensusQueueObservedEvent) + return err } - v, err = kv.Read([]byte(queuedEventsKey)) + v, err := kv.Read([]byte(queuedEventsKey)) if err != nil { return fmt.Errorf("failed to read queued events: %w", err) } @@ -208,6 +194,33 @@ func (s *kvState) loadFrom(kv ocr3_1types.KeyValueStateReadWriter) error { return nil } +func readObservedEvents(kv ocr3_1types.KeyValueStateReader) (observedEvents map[string]*pb.ConsensusQueueObservedEvent, observedBlobs blobHandleMap, 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(blobHandleMap) + 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 { + for _, b := range event.GetBlobs() { + observedBlobs.add(eventHash, string(blobHandles[b.Blob]), b.Element) + } + } + } else { + observedEvents = make(map[string]*pb.ConsensusQueueObservedEvent) + } + return +} + // sizeOf returns the size of the state when serialized and written to the KV store via writeAll. func (s *kvState) sizeOf() (size int) { s.prepareWrite() @@ -216,7 +229,7 @@ func (s *kvState) sizeOf() (size int) { protoOpts := proto.MarshalOptions{Deterministic: true} size += len(observedEventsKey) + len(queuedEventsKey) + len(consensusEventsKey) + len(blobHandlesKey) - size += protoOpts.Size(&pb.ConsensusQueueObservedEvents{Observations: s.observedEvents, BlobHandles: s.observedBlobHandles}) + size += protoOpts.Size(&pb.ConsensusQueueObservedEvents{Observations: s.observedEventEntries, BlobHandles: s.observedBlobHandles}) size += protoOpts.Size(&pb.ConsensusQueueEventList{Events: *s.queuedEvents}) size += protoOpts.Size(&pb.ConsensusQueueEventList{Events: s.consensusEvents}) size += protoOpts.Size(&pb.ConsensusQueueBlobHandleList{BlobHandles: s.queuedBlobHandles}) @@ -229,6 +242,7 @@ func (s *kvState) prepareWrite() { // gather blob handles and update events s.observedBlobHandles = nil observedBlobIndexes := make(map[string]int) + s.observedEventEntries = nil for _, eventHash := range slices.Sorted(maps.Keys(s.observedEvents)) { event := s.observedEvents[eventHash] event.Blobs = nil // replace all @@ -244,6 +258,8 @@ func (s *kvState) prepareWrite() { Element: ei, }) } + s.observedEventEntries = append(s.observedEventEntries, &pb.ConsensusQueueObservedEventEntry{ + TimelessHash: []byte(eventHash), Event: event}) } // gather blob handles and update events @@ -278,7 +294,7 @@ func (s *kvState) prepareWrite() { func (s *kvState) writeTo(w *stateWriter) error { //TODO MarshalOptions{UseCachedSize}? - err := w.writeValue(observedEventsKey, &pb.ConsensusQueueObservedEvents{Observations: s.observedEvents, BlobHandles: s.observedBlobHandles}) + 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) } diff --git a/core/services/ocr3_1/plugins/queue/math.go b/core/services/ocr3_1/plugins/queue/math.go index 57962d67750..b67cd83cb08 100644 --- a/core/services/ocr3_1/plugins/queue/math.go +++ b/core/services/ocr3_1/plugins/queue/math.go @@ -8,23 +8,38 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" ) -// median returns the median value of a slice of integers. +// median returns the median value of a slice of integers, as well as a count of the number of occurrences of the median. // len must be greater than 0. -func median[N constraints.Integer, S []N](s S) N { +func median[N constraints.Integer, S []N](s S) (N, int) { switch len(s) { case 0: panic("median: len must be greater than 0") case 1: - return s[0] + return s[0], 1 } slices.Sort(s) if len(s)%2 == 1 { - return s[len(s)/2] + m := s[len(s)/2] + return m, count(s, m) } // avg of two a, b := s[len(s)/2], s[len(s)/2-1] diff := a - b - return b + diff/2 + m := b + diff/2 + return m, count(s, m) +} + +// count returns the number of occurrences of e in s, but s must be sorted. +func count[N comparable, S []N](s S, e N) int { + firstIndex := slices.Index(s, e) + if firstIndex == -1 { + return 0 + } + var c int + for i := firstIndex; i < len(s) && s[i] == e; i++ { + c++ + } + return c } // medianTimestamp returns the median value of a slice of timestamps. diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index 295392b6a9f..4f1d02f6d95 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -6,6 +6,7 @@ import ( "crypto/sha256" "errors" "fmt" + "iter" "math" "slices" "sync" @@ -107,10 +108,6 @@ func (c *consensusQueuePlugin) Observation( return nil, fmt.Errorf("failed to get available capacity: %w", err) } - var events []triggers.CoordinatedEvent - // TODO observe queue - but can't "take" - need to confirm during StateTransition - // ignore if observed in kv state already - expirationGraceDur, err := c.expirationDur(ctx) if err != nil { c.lggr.Warnw("Failed to get expiration grace duration - using default", "err", err) @@ -118,7 +115,6 @@ func (c *consensusQueuePlugin) Observation( emptyBlobHandle := make([]byte, c.blobHandleMarshalledBytesUpperBound) obs := &pb.ConsensusQueueObservation{ - Events: make([]*pb.ConsensusQueueEvent, 0, len(events)), // placeholder for accurate size calculation BlobHandles: slices.Repeat([][]byte{emptyBlobHandle}, maxObservedBlobHandles), Expiration: timestamppb.New(time.Now().Add(-expirationGraceDur)), @@ -130,12 +126,17 @@ func (c *consensusQueuePlugin) Observation( obs.WorkflowCapacities[wf] = uint32(min(wfCap, math.MaxUint32)) } - coordEvents := make([]*pb.CoordinatedEvent, len(events)) - for i, e := range events { - coordEvents[i] = e.ToProto() + var events iter.Seq[*triggers.CoordinatedEvent] + //TODO events iter from triggerCoordinator, to be acked later during StateTransition + + observedEvents, _, err := readObservedEvents(kvReader) + if err != nil { + return nil, err } + protoOpts := proto.MarshalOptions{Deterministic: true} - for i, coord := range coordEvents { //TODO iter.Seq from trigger coordinator + var coordEvents []*pb.CoordinatedEvent + for coord := range toProtoSeq(events) { // Try adding to batch observedAt, deadline := coord.ObservedAt, coord.Deadline @@ -147,6 +148,13 @@ func (c *consensusQueuePlugin) Observation( } timelessHash := sha256.Sum256(protoBytes) + // skip if kv observation exists already + if obsEvent, ok := observedEvents[string(timelessHash[:])]; ok { + if slices.Contains(obsEvent.NodeIds, uint8(c.onchainCfg.OracleID)) { + continue + } + } + obs.Events = append(obs.Events, &pb.ConsensusQueueEvent{ WorkflowID: coord.WorkflowID, TriggerEventID: coord.Event.Event.Id, @@ -155,9 +163,10 @@ func (c *consensusQueuePlugin) Observation( TimelessHash: timelessHash[:], Blobs: []*pb.CoordinatedEventBlobHandle{{ Blob: 0, - Element: uint32(i), + Element: uint32(len(coordEvents)), }}, }) + coordEvents = append(coordEvents, coord) var addedCap bool if _, ok := obs.WorkflowCapacities[coord.WorkflowID]; !ok { @@ -207,6 +216,16 @@ func (c *consensusQueuePlugin) Observation( return protoOpts.Marshal(obs) } +func toProtoSeq(in iter.Seq[*triggers.CoordinatedEvent]) iter.Seq[*pb.CoordinatedEvent] { + return func(yield func(*pb.CoordinatedEvent) bool) { + for event := range in { + if !yield(event.ToProto()) { + return + } + } + } +} + func (c *consensusQueuePlugin) ValidateObservation( ctx context.Context, _ uint64, _ ocrtypes.AttributedQuery, ao ocrtypes.AttributedObservation, _ ocr3_1types.KeyValueStateReader, blobFetcher ocr3_1types.BlobFetcher, @@ -316,7 +335,7 @@ func (c *consensusQueuePlugin) StateTransition( go func() { defer close(done) - obs.aggregate(ctx, aos) + obs.aggregate(ctx, c.onchainCfg.F, aos) }() var state kvState @@ -343,6 +362,7 @@ func (c *consensusQueuePlugin) StateTransition( // update state state.pruneExpiredObservations(obs.medianExpiration) + //TODO must not promote to PQ and ack until we are sure we can write the kv state.addObservedEvents(c.onchainCfg.F, obs.newObservedEvents, obs.observedBlobs, func(queued *pb.ConsensusQueueEvent) { //TODO ack the trigger coordinator - no longer need to observe this event }) @@ -373,8 +393,7 @@ type observations struct { err error } -// TODO consider some configurable x% of capacity since some honest nodes have less -func (res *observations) aggregate(ctx context.Context, aos []ocrtypes.AttributedObservation) { +func (res *observations) aggregate(ctx context.Context, f int, aos []ocrtypes.AttributedObservation) { res.medianCapPerWF = make(map[string]uint32) res.newObservedEvents = make(map[string]*pb.ConsensusQueueObservedEvent) @@ -401,9 +420,18 @@ func (res *observations) aggregate(ctx context.Context, aos []ocrtypes.Attribute } } res.medianExpiration = medianTimestamp(expirations).AsTime() - res.medianCap = median(capacities) + + // Medianize capacities, and when there is disagreement among honest nodes, scale back to 90%. + var medianCount int + res.medianCap, medianCount = median(capacities) + if medianCount < 2*f+1 { + res.medianCap = (res.medianCap * 9) / 10 + } for wf, caps := range wfCapacities { - res.medianCapPerWF[wf] = median(caps) + res.medianCapPerWF[wf], medianCount = median(caps) + if medianCount < 2*f+1 { + res.medianCapPerWF[wf] = (res.medianCapPerWF[wf] * 9) / 10 + } } return } @@ -490,8 +518,15 @@ func (c *consensusQueuePlugin) tryStartExecution(ctx context.Context, fetcher *b return fmt.Errorf("failed to convert CoordinatedEvent from proto: %w", err) } - // TODO execute StartExecution - // c.triggerCoordinator.tryStartExecution(ctx, event) + // TODO c.triggerCoordinator.tryStartExecution(ctx, event) + + // only log metadata, not outputs and payload + event.Event.Event.Outputs = nil + event.Event.Event.Payload = nil + latency := time.Since(event.ObservedAt) + c.lggr.Infow("Consensus event dry run completed", "observedAt", event.ObservedAt, "latency", latency, "event", event) + //TODO emit latency metric + return nil } diff --git a/deployment/go.mod b/deployment/go.mod index 6ed8052da22..54f75a1bbf0 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.20261117161043-d7bfae650337 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5 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 e006400c0cc..d0629af5562 100644 --- a/deployment/go.sum +++ b/deployment/go.sum @@ -1411,8 +1411,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.20261117161043-d7bfae650337 h1:pD5MmKg+G52nkA4ghoVFqUtkAtZsUyGOSBY+P3JFE+M= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117161043-d7bfae650337/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5 h1:V+IBcXmheTxfYQb8gX/2KFjcIwiPSz6hvJ5MmOh9hjI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/go.mod b/go.mod index 8d1d041d86f..e3738e1879a 100644 --- a/go.mod +++ b/go.mod @@ -82,7 +82,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.20261117161043-d7bfae650337 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 github.com/smartcontractkit/chainlink-data-streams v1.1.3 diff --git a/go.sum b/go.sum index 0c95cce576b..49f1a8f32e4 100644 --- a/go.sum +++ b/go.sum @@ -1102,8 +1102,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.20261117161043-d7bfae650337 h1:pD5MmKg+G52nkA4ghoVFqUtkAtZsUyGOSBY+P3JFE+M= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117161043-d7bfae650337/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5 h1:V+IBcXmheTxfYQb8gX/2KFjcIwiPSz6hvJ5MmOh9hjI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/integration-tests/go.mod b/integration-tests/go.mod index 3d19f9ed0fe..c81ab483f74 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.20261117161043-d7bfae650337 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5 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.20261112211734-e640e1c12078 diff --git a/integration-tests/go.sum b/integration-tests/go.sum index c5b5399c9fb..3e5085b8781 100644 --- a/integration-tests/go.sum +++ b/integration-tests/go.sum @@ -1396,8 +1396,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.20261117161043-d7bfae650337 h1:pD5MmKg+G52nkA4ghoVFqUtkAtZsUyGOSBY+P3JFE+M= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117161043-d7bfae650337/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5 h1:V+IBcXmheTxfYQb8gX/2KFjcIwiPSz6hvJ5MmOh9hjI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/integration-tests/load/go.mod b/integration-tests/load/go.mod index 33d0953e1ad..45f92ef98e1 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.20261117161043-d7bfae650337 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5 github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261112211734-e640e1c12078 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 04d7bf8de40..c39f1ee6333 100644 --- a/integration-tests/load/go.sum +++ b/integration-tests/load/go.sum @@ -1636,8 +1636,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.20261117161043-d7bfae650337 h1:pD5MmKg+G52nkA4ghoVFqUtkAtZsUyGOSBY+P3JFE+M= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117161043-d7bfae650337/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5 h1:V+IBcXmheTxfYQb8gX/2KFjcIwiPSz6hvJ5MmOh9hjI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/system-tests/lib/cre/environment/environment.go b/system-tests/lib/cre/environment/environment.go index 43b16cbfde6..e0fe5a5a420 100644 --- a/system-tests/lib/cre/environment/environment.go +++ b/system-tests/lib/cre/environment/environment.go @@ -291,49 +291,6 @@ func SetupTestEnvironment( // allow to pass custom job spec factories for extensibility jobSpecFactoryFunctions = append(jobSpecFactoryFunctions, input.JobSpecFactoryFunctions...) - // ConsensusQueue - //TODO remove - replaced by feature - //jobSpecFactoryFunctions = append(jobSpecFactoryFunctions, func(input *cre.JobSpecInput) (cre.DonJobs, error) { - // chainID, err := chainselectors.GetChainIDFromSelector(deployedBlockchains.RegistryChain().ChainSelector()) - // if err != nil { - // return nil, fmt.Errorf("failed to get chain ID from selector: %w", err) - // } - // evmChainID, err := strconv.ParseUint(chainID, 10, 64) - // if err != nil { - // return nil, fmt.Errorf("non-integer chain ID: %s: %w", chainID, err) - // } - // - // don := dons.MustWorkflowDON() - // - // bs, ok := dons.Bootstrap() - // if !ok { - // return nil, fmt.Errorf("failed to look up bootstrap node") - // } - // jobConfig := pkg.OCR3JobConfig{ - // JobName: "consensus-queue-test", - // ChainID: chainID, - // ContractID: "0x0000000000000000000000000000000000000000", // TODO - // P2Pv2Bootstrappers: []string{bs.Keys.P2PKey.PeerID.Raw() + "@" + bs.Host + ":" + strconv.Itoa(cre.OCRPeeringPort)}, - // ExternalJobID: uuid.NewV4().String(), // TODO deterministic? - // TemplateName: "consensus-queue", - // } - // - // var donJobs cre.DonJobs - // for _, node := range don.Nodes { - // jobConfig.P2PID = node.PeerID() - // jobConfig.OCR2EVMKeyBundleID = node.Keys.OCR2BundleIDs["evm"] - // jobConfig.TransmitterID = node.Keys.EVM[evmChainID].PublicAddress.String() - // - // jobSpec, err := jobConfig.ResolveJob() - // if err != nil { - // return nil, fmt.Errorf("failed to resolve OCR3 job spec: %w", err) - // } - // nodeID := node.JobDistributorDetails.NodeID - // donJobs = append(donJobs, &job.ProposeJobRequest{NodeId: nodeID, Spec: jobSpec}) - // } - // return donJobs, nil - //}) - createJobsDeps := CreateJobsWithJdOpDeps{ Logger: testLogger, SingleFileLogger: singleFileLogger, diff --git a/system-tests/lib/go.mod b/system-tests/lib/go.mod index 754057b3aeb..e43c92856e0 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.20261117161043-d7bfae650337 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5 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 e5685f2b0e1..cf457822624 100644 --- a/system-tests/lib/go.sum +++ b/system-tests/lib/go.sum @@ -1657,8 +1657,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.20261117161043-d7bfae650337 h1:pD5MmKg+G52nkA4ghoVFqUtkAtZsUyGOSBY+P3JFE+M= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117161043-d7bfae650337/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5 h1:V+IBcXmheTxfYQb8gX/2KFjcIwiPSz6hvJ5MmOh9hjI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/system-tests/tests/go.mod b/system-tests/tests/go.mod index ada4371cb0c..097a1c9e70a 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.20261117161043-d7bfae650337 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 github.com/smartcontractkit/chainlink-confidential-compute v1.3.0 diff --git a/system-tests/tests/go.sum b/system-tests/tests/go.sum index 80afe63ceaa..6b9a4b494b3 100644 --- a/system-tests/tests/go.sum +++ b/system-tests/tests/go.sum @@ -1836,8 +1836,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.20261117161043-d7bfae650337 h1:pD5MmKg+G52nkA4ghoVFqUtkAtZsUyGOSBY+P3JFE+M= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117161043-d7bfae650337/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5 h1:V+IBcXmheTxfYQb8gX/2KFjcIwiPSz6hvJ5MmOh9hjI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= From 51c55f96fe707d2570f9eb5ab3de3175c1786d04 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Tue, 17 Nov 2026 22:45:19 -0600 Subject: [PATCH 10/38] wire trigger.Queue; implement SortedFunc & Remove --- core/services/chainlink/application.go | 1 + core/services/cre/cre.go | 41 ++++----- core/services/ocr2/delegate.go | 5 +- core/services/ocr3_1/plugins/queue/kvstate.go | 5 +- core/services/ocr3_1/plugins/queue/queue.go | 42 ++++++---- .../workflows/v2/triggers/coordinator.go | 2 + core/services/workflows/v2/triggers/queue.go | 83 +++++++++++++++++++ 7 files changed, 141 insertions(+), 38 deletions(-) diff --git a/core/services/chainlink/application.go b/core/services/chainlink/application.go index 8270739b91f..855f6313efb 100644 --- a/core/services/chainlink/application.go +++ b/core/services/chainlink/application.go @@ -842,6 +842,7 @@ func NewApplication(ctx context.Context, opts ApplicationOpts) (Application, err LimitsFactory: limitsFactory, OCRConfigService: creServices.OCRConfigService, TriggerCoordinator: creServices.TriggerCoordinator, + TriggerQueue: creServices.TriggerQueue, DefaultBootstrappers: safeDefaultBootstrappers(cfg), CapRegistryAddress: safeExternalRegistryAddress(cfg), CapRegistryChainID: safeExternalRegistryChainID(cfg), diff --git a/core/services/cre/cre.go b/core/services/cre/cre.go index 065cdbe5df8..8bff553b1eb 100644 --- a/core/services/cre/cre.go +++ b/core/services/cre/cre.go @@ -137,6 +137,8 @@ type Services struct { TriggerCoordinator triggers.Coordinator + TriggerQueue triggers.Queue + OrgResolver orgresolver.OrgResolver OCRConfigService capregconfig.OCRConfigService @@ -299,7 +301,7 @@ func (s *Services) newSubservices( wfSyncerLggr.Infof("failed to create billing client: %s", err) } - wfSyncer, triggerCoordinator, wfSyncerSrvcs, err := newWorkflowRegistrySyncerV2( + wfSyncer, triggerCoordinator, triggerQueue, wfSyncerSrvcs, err := newWorkflowRegistrySyncerV2( cfg, relayerChainInterops, billingClient, @@ -323,6 +325,7 @@ func (s *Services) newSubservices( s.BillingClient = billingClient s.WorkflowRegistrySyncer = wfSyncer s.TriggerCoordinator = triggerCoordinator + s.TriggerQueue = triggerQueue srvs = append(srvs, wfSyncerSrvcs...) return srvs, nil @@ -803,14 +806,14 @@ func newWorkflowRegistrySyncerV2( meterIdentity resourcemanager.ResourceIdentity, dispatcher remotetypes.Dispatcher, shardIndexMapper *shardownership.ShardIndexMapper, -) (syncerV2.WorkflowRegistrySyncer, triggers.Coordinator, []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, nil, err + return nil, nil, nil, nil, err } artifactsStore, err := artifactsV2.NewStore( @@ -827,29 +830,29 @@ func newWorkflowRegistrySyncerV2( }), ) if err != nil { - return nil, 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, 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, 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, nil, err + return nil, nil, nil, nil, err } crFactory, err := newContractReaderFactory(capCfg, relayerChainInterops) if err != nil { - return nil, 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 @@ -858,7 +861,7 @@ func newWorkflowRegistrySyncerV2( } else { c, clientErr := newShardOrchestratorClient(cfg, lggr) if clientErr != nil { - return nil, nil, nil, clientErr + return nil, nil, nil, nil, clientErr } if c != nil { shardOrchestratorClient = c @@ -905,15 +908,15 @@ func newWorkflowRegistrySyncerV2( coordinatorMetrics, err := wfmonitoring.InitMonitoringResources() if err != nil { - return nil, 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, 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, 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() @@ -974,7 +977,7 @@ func newWorkflowRegistrySyncerV2( }) specMeter, smErr := syncerV2.NewSpecMeter(lggr, rm, meterIdentity, artifactsStore, orgResolver) if smErr != nil { - return nil, 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)) } @@ -995,7 +998,7 @@ func newWorkflowRegistrySyncerV2( if diskMonitorEnabled { fileStore, fsErr := artifactsV2.NewFileModuleStore(mc.CacheDir(), cacheEnabled) if fsErr != nil { - return nil, 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( @@ -1004,7 +1007,7 @@ func newWorkflowRegistrySyncerV2( syncerV2.WorkflowModuleCacheDiskMonitorTickInterval, ) if dmErr != nil { - return nil, 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) @@ -1013,7 +1016,7 @@ func newWorkflowRegistrySyncerV2( if cacheEnabled { cm, cmErr := syncerV2.NewCacheMetrics() if cmErr != nil { - return nil, 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 @@ -1063,7 +1066,7 @@ func newWorkflowRegistrySyncerV2( handlerOpts..., ) if err != nil { - return nil, 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() @@ -1116,12 +1119,12 @@ func newWorkflowRegistrySyncerV2( registryOpts..., ) if err != nil { - return nil, 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, triggerCoordinator, 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 eee9f2a56c7..3f55eee07b8 100644 --- a/core/services/ocr2/delegate.go +++ b/core/services/ocr2/delegate.go @@ -160,6 +160,7 @@ type Delegate struct { limitsFactory limits.Factory ocrConfigService capregconfig.OCRConfigService triggerCoordinator triggers.Coordinator + triggerQueue triggers.Queue // Registry-driven launch support: when the delegate is used via // LocalCapabilityManager (no job spec), these fields provide the @@ -314,6 +315,7 @@ type DelegateOpts struct { LimitsFactory limits.Factory OCRConfigService capregconfig.OCRConfigService TriggerCoordinator triggers.Coordinator + TriggerQueue triggers.Queue // Registry-driven launch support: defaults for capabilities launched // via LocalCapabilityManager (no job spec). @@ -364,6 +366,7 @@ func NewDelegate( limitsFactory: opts.LimitsFactory, ocrConfigService: opts.OCRConfigService, triggerCoordinator: opts.TriggerCoordinator, + triggerQueue: opts.TriggerQueue, defaultBootstrappers: opts.DefaultBootstrappers, capRegistryAddress: opts.CapRegistryAddress, capRegistryChainID: opts.CapRegistryChainID, @@ -912,7 +915,7 @@ func (d *Delegate) newServicesConsensusQueue( MetricsRegisterer: prometheus.WrapRegistererWith(map[string]string{"job_name": jb.Name.ValueOrZero()}, prometheus.DefaultRegisterer), } - rpf, err := queue.NewConsensusQueuePluginFactory(lggr, cfg, d.limitsFactory, d.triggerCoordinator) + rpf, err := queue.NewConsensusQueuePluginFactory(lggr, cfg, d.limitsFactory, d.triggerCoordinator, d.triggerQueue) if err != nil { return nil, err } diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index 0344ed52ddd..25dcddd18c9 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -28,10 +28,6 @@ const ( blobHandlesKey = "blob_handles::index" // pb.ConsensusQueueBlobHandleList{ [][]byte } ) -type stateReader struct { - kv ocr3_1types.KeyValueStateReader -} - type stateWriter struct { kv ocr3_1types.KeyValueStateReadWriter } @@ -243,6 +239,7 @@ func (s *kvState) prepareWrite() { s.observedBlobHandles = nil observedBlobIndexes := make(map[string]int) s.observedEventEntries = nil + //TODO deadline order so that we can drop efficiently for _, eventHash := range slices.Sorted(maps.Keys(s.observedEvents)) { event := s.observedEvents[eventHash] event.Blobs = nil // replace all diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index 4f1d02f6d95..06040b1a131 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -2,6 +2,7 @@ package queue import ( "bytes" + "cmp" "context" "crypto/sha256" "errors" @@ -36,14 +37,22 @@ type consensusQueuePluginFactory struct { lggr logger.Logger cfg *PluginConfig triggerCoordinator triggers.Coordinator + triggerQueue triggers.Queue expirationDur func(context.Context) (time.Duration, error) } -func NewConsensusQueuePluginFactory(lggr logger.Logger, cfg *PluginConfig, limitsFactory limits.Factory, triggerCoordinator triggers.Coordinator) (ocr3_1types.ReportingPluginFactory[[]byte], error) { +func NewConsensusQueuePluginFactory( + lggr logger.Logger, + cfg *PluginConfig, + limitsFactory limits.Factory, + triggerCoordinator triggers.Coordinator, + triggerQueue triggers.Queue, +) (ocr3_1types.ReportingPluginFactory[[]byte], error) { return &consensusQueuePluginFactory{ lggr: lggr, cfg: cfg, triggerCoordinator: triggerCoordinator, + triggerQueue: triggerQueue, expirationDur: func(ctx context.Context) (time.Duration, error) { //TODO also allow this grace period in the trigger coordinator return cresettings.Default.ConsensusQueueExpirationInterval.GetOrDefault(ctx, limitsFactory.Settings) @@ -52,7 +61,7 @@ func NewConsensusQueuePluginFactory(lggr logger.Logger, cfg *PluginConfig, limit } func (c *consensusQueuePluginFactory) NewReportingPlugin(ctx context.Context, config ocr3types.ReportingPluginConfig, blobs ocr3_1types.BlobBroadcastFetcher) (ocr3_1types.ReportingPlugin[[]byte], ocr3_1types.ReportingPluginInfo, error) { - plugin := newConsensusQueuePlugin(c.lggr, config, c.triggerCoordinator, c.expirationDur, blobs) + plugin := newConsensusQueuePlugin(c.lggr, config, c.triggerCoordinator, c.triggerQueue, c.expirationDur, blobs) pluginInfo := ocr3_1types.ReportingPluginInfo1{ Name: "ConsensusQueueReportingPlugin", Limits: c.cfg.Limits, @@ -69,19 +78,22 @@ type consensusQueuePlugin struct { onchainCfg ocr3types.ReportingPluginConfig blobHandleMarshalledBytesUpperBound int triggerCoordinator triggers.Coordinator + triggerQueue triggers.Queue blobBroadcastFetcher ocr3_1types.BlobBroadcastFetcher expirationDur func(context.Context) (time.Duration, error) } func newConsensusQueuePlugin( lggr logger.Logger, onchainCfg ocr3types.ReportingPluginConfig, triggerCoordinator triggers.Coordinator, - expirationGraceDur func(context.Context) (time.Duration, error), blobs ocr3_1types.BlobBroadcastFetcher, + triggerQueue triggers.Queue, expirationGraceDur func(context.Context) (time.Duration, error), + blobs ocr3_1types.BlobBroadcastFetcher, ) *consensusQueuePlugin { c := &consensusQueuePlugin{ lggr: logger.Named(lggr, "ConsensusQueuePlugin"), onchainCfg: onchainCfg, blobHandleMarshalledBytesUpperBound: ocr3_1types.BlobHandleMarshalledBytesUpperBound(onchainCfg.F, onchainCfg.N), triggerCoordinator: triggerCoordinator, + triggerQueue: triggerQueue, blobBroadcastFetcher: blobs, expirationDur: expirationGraceDur, } @@ -126,19 +138,18 @@ func (c *consensusQueuePlugin) Observation( obs.WorkflowCapacities[wf] = uint32(min(wfCap, math.MaxUint32)) } - var events iter.Seq[*triggers.CoordinatedEvent] - //TODO events iter from triggerCoordinator, to be acked later during StateTransition - observedEvents, _, err := readObservedEvents(kvReader) if err != nil { return nil, err } protoOpts := proto.MarshalOptions{Deterministic: true} - var coordEvents []*pb.CoordinatedEvent - for coord := range toProtoSeq(events) { - // Try adding to batch + // Assemble an observation up to maxObservationBytes + var coordEvents []*pb.CoordinatedEvent + for coord := range toProtoSeq(c.triggerQueue.SortedFunc(func(a, b triggers.CoordinatedEvent) int { + return cmp.Or(a.Deadline.Compare(b.Deadline), cmp.Compare(a.Event.Event.ID, b.Event.Event.ID)) + })) { observedAt, deadline := coord.ObservedAt, coord.Deadline coord.ObservedAt, coord.Deadline = nil, nil // for consistent hashing protoBytes, err2 := protoOpts.Marshal(coord) // TODO opt: avoid remarshalling @@ -216,7 +227,7 @@ func (c *consensusQueuePlugin) Observation( return protoOpts.Marshal(obs) } -func toProtoSeq(in iter.Seq[*triggers.CoordinatedEvent]) iter.Seq[*pb.CoordinatedEvent] { +func toProtoSeq(in iter.Seq[triggers.CoordinatedEvent]) iter.Seq[*pb.CoordinatedEvent] { return func(yield func(*pb.CoordinatedEvent) bool) { for event := range in { if !yield(event.ToProto()) { @@ -362,9 +373,9 @@ func (c *consensusQueuePlugin) StateTransition( // update state state.pruneExpiredObservations(obs.medianExpiration) - //TODO must not promote to PQ and ack until we are sure we can write the kv - state.addObservedEvents(c.onchainCfg.F, obs.newObservedEvents, obs.observedBlobs, func(queued *pb.ConsensusQueueEvent) { - //TODO ack the trigger coordinator - no longer need to observe this event + var queuedTriggerEventIDs []string // to be removed from the trigger.Queue + state.addObservedEvents(c.onchainCfg.F, obs.newObservedEvents, obs.observedBlobs, func(event *pb.ConsensusQueueEvent) { + queuedTriggerEventIDs = append(queuedTriggerEventIDs, event.TriggerEventID) }) state.consensusEvents = state.queuedEvents.popLimited(obs.medianCap, obs.medianCapPerWF, obs.medianExpiration) @@ -372,12 +383,14 @@ func (c *consensusQueuePlugin) StateTransition( for state.sizeOf() > maxKeyValueModifiedKeysPlusValuesBytes { //TODO drop observations (must be deterministic, fair, efficient) // prefer farthest future deadlines and fewest observations + //TODO use sorted state.observedEventEntries } err = state.writeTo(&stateWriter{kv: kvReaderWriter}) if err != nil { return nil, err } + c.triggerQueue.Remove(ctx, queuedTriggerEventIDs) // no report to return, executions start when committed return nil, nil @@ -436,6 +449,7 @@ func (res *observations) aggregate(ctx context.Context, f int, aos []ocrtypes.At return } +// 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), string(blobHandles[event.Blobs[0].Blob]), event.Blobs[0].Element) aggregated, ok := res.newObservedEvents[string(event.TimelessHash)] @@ -518,7 +532,7 @@ func (c *consensusQueuePlugin) tryStartExecution(ctx context.Context, fetcher *b return fmt.Errorf("failed to convert CoordinatedEvent from proto: %w", err) } - // TODO c.triggerCoordinator.tryStartExecution(ctx, event) + // TODO c.triggerCoordinator.Deliver(ctx, event) // only log metadata, not outputs and payload event.Event.Event.Outputs = nil diff --git a/core/services/workflows/v2/triggers/coordinator.go b/core/services/workflows/v2/triggers/coordinator.go index 02ecf62a528..27a7691ac74 100644 --- a/core/services/workflows/v2/triggers/coordinator.go +++ b/core/services/workflows/v2/triggers/coordinator.go @@ -83,6 +83,8 @@ type Coordinator interface { // Returns ErrCapacityNotSupported if the shared ExecutionConcurrency // limiter does not break down by scope. AvailableCapacity(ctx context.Context) (Capacity, error) + + //TODO Deliver(context.Context, CoordinatedEvent } // RegisteredEngine is what EngineRegistry.Get returns: a sink the coordinator diff --git a/core/services/workflows/v2/triggers/queue.go b/core/services/workflows/v2/triggers/queue.go index cfa3d0089cd..e7b85e8fafc 100644 --- a/core/services/workflows/v2/triggers/queue.go +++ b/core/services/workflows/v2/triggers/queue.go @@ -1,9 +1,12 @@ package triggers import ( + "container/heap" "context" "errors" + "iter" "maps" + "slices" "sync" "github.com/smartcontractkit/chainlink-common/pkg/logger" @@ -29,6 +32,13 @@ type Queue interface { // Stats reports current length, capacity, and cumulative drops. Stats(context.Context) (Stats, error) + + // SortedFunc returns an iterator over all events sorted with cmp. + // It does not drain the queue. Events remain but can be removed via Remove. + SortedFunc(cmp func(a, b CoordinatedEvent) int) iter.Seq[CoordinatedEvent] + + // Remove removes events from the queue. + Remove(ctx context.Context, triggerEventIDs []string) } // Stats is a point-in-time view of a Queue. @@ -113,6 +123,79 @@ func (q *CentralQueue) Drain(ctx context.Context) ([]CoordinatedEvent, error) { return events, nil } +func (q *CentralQueue) Remove(ctx context.Context, triggerEventIDs []string) { + triggerEventIDSet := map[string]struct{}{} + for _, triggerEventID := range triggerEventIDs { + triggerEventIDSet[triggerEventID] = struct{}{} + } + + capacity := q.capacity(ctx) + + q.mu.Lock() + defer q.mu.Unlock() + + var deleted int + q.events = slices.DeleteFunc(q.events, func(e CoordinatedEvent) bool { + _, ok := triggerEventIDSet[e.Event.Event.ID] + if ok { + deleted++ + q.depthByWorkflow[e.WorkflowID]-- + q.depthByTriggerType[e.TriggerCapID]-- + } + return ok + }) + q.metrics.IncrementDrainedEventsCounter(ctx, deleted) + q.metrics.RecordDepth(ctx, len(q.events)) + q.metrics.RecordCapacity(ctx, q.effectiveCapacity(capacity)) + return +} + +// SortedFunc returns an iterator over all events sorted by cmp. +func (q *CentralQueue) SortedFunc(cmp func(a, b CoordinatedEvent) int) iter.Seq[CoordinatedEvent] { + q.mu.Lock() + events := slices.Clone(q.events) + q.mu.Unlock() + + eventHeap := &coordinatedEventHeap{events: events, cmp: cmp} + heap.Init(eventHeap) + + return func(yield func(CoordinatedEvent) bool) { + for eventHeap.Len() > 0 { + if !yield(eventHeap.events[0]) { + return + } + heap.Pop(eventHeap) + } + } +} + +type coordinatedEventHeap struct { + events []CoordinatedEvent + cmp func(a, b CoordinatedEvent) int +} + +func (c *coordinatedEventHeap) Len() int { + return len(c.events) +} + +func (c *coordinatedEventHeap) Less(i, j int) bool { + return c.cmp(c.events[i], c.events[j]) < 0 +} + +func (c *coordinatedEventHeap) Swap(i, j int) { + c.events[i], c.events[j] = c.events[j], c.events[i] +} + +func (c *coordinatedEventHeap) Push(x any) { + c.events = append(c.events, x.(CoordinatedEvent)) +} + +func (c *coordinatedEventHeap) Pop() any { + e := c.events[len(c.events)-1] + c.events = c.events[:len(c.events)-1] + return e +} + // 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) From e7bc3da5351fbe70e4c9664055e3db089f76d6a6 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Wed, 18 Nov 2026 08:48:35 -0600 Subject: [PATCH 11/38] docs --- core/services/ocr3_1/plugins/queue/kvstate.go | 2 +- core/services/ocr3_1/plugins/queue/queue.go | 6 ++++++ core/services/workflows/v2/triggers/queue.go | 1 + 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index 25dcddd18c9..63119c41987 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -42,7 +42,7 @@ func (s *stateWriter) writeValue[M proto.Message](key string, m M) error { var _ heap.Interface = (*priorityQueue)(nil) -// priorityQueue is a heap of coordinated events, ordered by deadline and then event ID. +// priorityQueue is a heap of coordinated events, ordered by deadline and then trigger event ID. type priorityQueue []*pb.ConsensusQueueEvent func (p *priorityQueue) Len() int { return len(*p) } diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index 06040b1a131..8b045d6cfe3 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -1,3 +1,9 @@ +// Package queue contains the consensus queue OCR 3.1 reporting plugin, for coordinating execution of triggered events. +// Each node has a local [triggers.Queue] of [triggers.CoordinatedEvent], which are observed (and broadcast) by the plugin. +// When consensus is reached, events are put in to the KeyValueState priority queue (and removed from the [triggers.Queue]). +// The priority queue is ordered by deadline (with nanosecond precision) and then by trigger event ID. +// Each round, as many events as possible are popped from the priority queue and then (fetched and) executed via [triggers.Coordinator.Deliver]. +// Capacity, both overall and per-workflow, limits what may execute. Capacities are observed and medianized. package queue import ( diff --git a/core/services/workflows/v2/triggers/queue.go b/core/services/workflows/v2/triggers/queue.go index e7b85e8fafc..08f1c0a6505 100644 --- a/core/services/workflows/v2/triggers/queue.go +++ b/core/services/workflows/v2/triggers/queue.go @@ -141,6 +141,7 @@ func (q *CentralQueue) Remove(ctx context.Context, triggerEventIDs []string) { deleted++ q.depthByWorkflow[e.WorkflowID]-- q.depthByTriggerType[e.TriggerCapID]-- + //TODO emit metric for time.Since(e.ObservedAt) } return ok }) From 0fcadd79099157f0b35cd7b843a8821428a194db Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Wed, 18 Nov 2026 09:17:15 -0600 Subject: [PATCH 12/38] CompareDeadline methods and cleanup --- core/scripts/go.mod | 2 +- core/scripts/go.sum | 4 +- core/services/ocr3_1/plugins/queue/kvstate.go | 9 +- core/services/ocr3_1/plugins/queue/queue.go | 7 +- .../ocr3_1/plugins/queue/queue_test.go | 2 +- .../v2/triggers/coordinator_shadow_test.go | 7 ++ .../workflows/v2/triggers/drainer_test.go | 82 +++++++++++++------ core/services/workflows/v2/triggers/queue.go | 28 +++---- .../workflows/v2/triggers/triggers.go | 5 ++ deployment/go.mod | 2 +- deployment/go.sum | 4 +- go.mod | 2 +- go.sum | 4 +- integration-tests/go.mod | 2 +- integration-tests/go.sum | 4 +- integration-tests/load/go.mod | 2 +- integration-tests/load/go.sum | 4 +- system-tests/lib/go.mod | 2 +- system-tests/lib/go.sum | 4 +- system-tests/tests/go.mod | 2 +- system-tests/tests/go.sum | 4 +- 21 files changed, 108 insertions(+), 74 deletions(-) diff --git a/core/scripts/go.mod b/core/scripts/go.mod index b1bee600bdd..c394aed57b8 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.20261117234947-4423d67da5d5 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087 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.20261112211734-e640e1c12078 diff --git a/core/scripts/go.sum b/core/scripts/go.sum index fddbfc28b6b..a6f2331b734 100644 --- a/core/scripts/go.sum +++ b/core/scripts/go.sum @@ -1686,8 +1686,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.20261117234947-4423d67da5d5 h1:V+IBcXmheTxfYQb8gX/2KFjcIwiPSz6hvJ5MmOh9hjI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087 h1:QQpXxddXoJi7b200xLaTI8yO8iKOukebi8WctQotQmY= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index 63119c41987..8354cd96ff0 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -1,7 +1,6 @@ package queue import ( - "cmp" "container/heap" "fmt" "maps" @@ -49,13 +48,7 @@ func (p *priorityQueue) Len() int { return len(*p) } func (p *priorityQueue) Less(i, j int) bool { a, b := (*p)[i], (*p)[j] - return cmpConsensusQueueEvents(a, b) < 0 -} - -func cmpConsensusQueueEvents(a, b *pb.ConsensusQueueEvent) int { - return cmp.Or(cmp.Compare(a.Deadline.Seconds, b.Deadline.Seconds), - cmp.Compare(a.Deadline.Nanos, b.Deadline.Nanos), - cmp.Compare(a.TriggerEventID, b.TriggerEventID)) + return a.CompareDeadline(b) < 0 } func (p *priorityQueue) Swap(i, j int) { diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index 8b045d6cfe3..04c9676021a 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -8,7 +8,6 @@ package queue import ( "bytes" - "cmp" "context" "crypto/sha256" "errors" @@ -153,9 +152,7 @@ func (c *consensusQueuePlugin) Observation( // Assemble an observation up to maxObservationBytes var coordEvents []*pb.CoordinatedEvent - for coord := range toProtoSeq(c.triggerQueue.SortedFunc(func(a, b triggers.CoordinatedEvent) int { - return cmp.Or(a.Deadline.Compare(b.Deadline), cmp.Compare(a.Event.Event.ID, b.Event.Event.ID)) - })) { + for coord := range toProtoSeq(c.triggerQueue.Sorted()) { observedAt, deadline := coord.ObservedAt, coord.Deadline coord.ObservedAt, coord.Deadline = nil, nil // for consistent hashing protoBytes, err2 := protoOpts.Marshal(coord) // TODO opt: avoid remarshalling @@ -263,7 +260,7 @@ func (c *consensusQueuePlugin) ValidateObservation( if len(obs.Events) > maxObservedEvents { return fmt.Errorf("events are limited to %d but got %d", maxObservedEvents, len(obs.Events)) } - if !slices.IsSortedFunc(obs.Events, cmpConsensusQueueEvents) { + if !slices.IsSortedFunc(obs.Events, (*pb.ConsensusQueueEvent).CompareDeadline) { return fmt.Errorf("events must be sorted") } var eg errgroup.Group diff --git a/core/services/ocr3_1/plugins/queue/queue_test.go b/core/services/ocr3_1/plugins/queue/queue_test.go index c986ab517ac..5f5173eca06 100644 --- a/core/services/ocr3_1/plugins/queue/queue_test.go +++ b/core/services/ocr3_1/plugins/queue/queue_test.go @@ -18,7 +18,7 @@ func TestConsensusQueuePluginFactory_NewReportingPlugin(t *testing.T) { t.Parallel() cfg := &PluginConfig{Limits: ocr3_1types.ReportingPluginLimits{MaxKeyValueModifiedKeys: 1}} - factory, err := NewConsensusQueuePluginFactory(logger.Test(t), cfg, limits.Factory{}, nil) + factory, err := NewConsensusQueuePluginFactory(logger.Test(t), cfg, limits.Factory{}, nil, nil) require.NoError(t, err) plugin, info, err := factory.NewReportingPlugin(t.Context(), ocr3types.ReportingPluginConfig{N: 4, F: 1}, nil) diff --git a/core/services/workflows/v2/triggers/coordinator_shadow_test.go b/core/services/workflows/v2/triggers/coordinator_shadow_test.go index a05d1c804c7..960ec5e8e73 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" @@ -333,6 +334,12 @@ type failingQueue struct { puts atomic.Int32 } +func (q *failingQueue) Sorted() iter.Seq[CoordinatedEvent] { + return func(yield func(CoordinatedEvent) bool) {} +} + +func (q *failingQueue) Remove(ctx context.Context, triggerEventIDs []string) {} + func (q *failingQueue) Put(context.Context, CoordinatedEvent) error { q.puts.Add(1) return errors.New("boom") diff --git a/core/services/workflows/v2/triggers/drainer_test.go b/core/services/workflows/v2/triggers/drainer_test.go index c499af946b7..03c6f990094 100644 --- a/core/services/workflows/v2/triggers/drainer_test.go +++ b/core/services/workflows/v2/triggers/drainer_test.go @@ -1,8 +1,11 @@ package triggers import ( + "container/heap" "context" "errors" + "iter" + "slices" "sync" "sync/atomic" "testing" @@ -53,9 +56,42 @@ 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() iter.Seq[CoordinatedEvent] { + q.mu.Lock() + events := slices.Clone(q.results[0].events) + q.mu.Unlock() + + eventHeap := new(coordinatedEventHeap(events)) + heap.Init(eventHeap) + return func(yield func(CoordinatedEvent) bool) { + for eventHeap.Len() > 0 { + e := heap.Pop(eventHeap).(CoordinatedEvent) + if !yield(e) { + return + } + } + } +} + +func (q *fakeQueue) Remove(ctx context.Context, triggerEventIDs []string) { + triggerEventIDSet := map[string]struct{}{} + for _, triggerEventID := range triggerEventIDs { + triggerEventIDSet[triggerEventID] = struct{}{} + } + q.mu.Lock() + defer q.mu.Unlock() + for _, r := range q.results { + r.events = slices.DeleteFunc(r.events, func(e CoordinatedEvent) bool { + _, ok := triggerEventIDSet[e.Event.Event.ID] + return ok + }) + // note: empty results remain + } } type observeResult struct { @@ -70,7 +106,7 @@ 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 } @@ -79,10 +115,10 @@ func (q *fakeQueue) Drain(context.Context) ([]CoordinatedEvent, error) { return r.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 { @@ -115,25 +151,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: 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: 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: batchOf("a")}, {events: batchOf("b")}}, want: [][]CoordinatedEvent{batchOf("a")}, }, } @@ -151,7 +187,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,7 +200,7 @@ func TestDrainer_DroppedEventsMetric(t *testing.T) { t.Parallel() dm, reader := testDrainerMetrics(t) - q := &fakeQueue{results: []observeResult{ + q := &fakeQueue{results: []*observeResult{ {events: batchOf("a")}, {events: append(batchOf("b"), batchOf("c")...)}, // dropped: the buffer holds "a" }} @@ -188,7 +224,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: 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 +245,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: 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: batchOf("a")}}, want: []string{"a"}, }, } @@ -269,9 +305,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: batchOf("x")} } q := &fakeQueue{results: results} @@ -349,12 +385,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,7 +426,7 @@ 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: batch}}} dm, _ := testDrainerMetrics(t) lggr, logs := logger.TestObserved(t, zapcore.DebugLevel) d := NewCentralQueueDrainer(q, limits.NewUpperBoundLimiter(minDrainInterval), dm, clock, lggr) diff --git a/core/services/workflows/v2/triggers/queue.go b/core/services/workflows/v2/triggers/queue.go index 08f1c0a6505..a8f9585ef0f 100644 --- a/core/services/workflows/v2/triggers/queue.go +++ b/core/services/workflows/v2/triggers/queue.go @@ -33,9 +33,9 @@ type Queue interface { // Stats reports current length, capacity, and cumulative drops. Stats(context.Context) (Stats, error) - // SortedFunc returns an iterator over all events sorted with cmp. + // Sorted returns an iterator over all events, ordered by deadline and then trigger event ID. // It does not drain the queue. Events remain but can be removed via Remove. - SortedFunc(cmp func(a, b CoordinatedEvent) int) iter.Seq[CoordinatedEvent] + Sorted() iter.Seq[CoordinatedEvent] // Remove removes events from the queue. Remove(ctx context.Context, triggerEventIDs []string) @@ -151,18 +151,17 @@ func (q *CentralQueue) Remove(ctx context.Context, triggerEventIDs []string) { return } -// SortedFunc returns an iterator over all events sorted by cmp. -func (q *CentralQueue) SortedFunc(cmp func(a, b CoordinatedEvent) int) iter.Seq[CoordinatedEvent] { +func (q *CentralQueue) Sorted() iter.Seq[CoordinatedEvent] { q.mu.Lock() events := slices.Clone(q.events) q.mu.Unlock() - eventHeap := &coordinatedEventHeap{events: events, cmp: cmp} + eventHeap := new(coordinatedEventHeap(events)) heap.Init(eventHeap) return func(yield func(CoordinatedEvent) bool) { for eventHeap.Len() > 0 { - if !yield(eventHeap.events[0]) { + if !yield((*eventHeap)[0]) { return } heap.Pop(eventHeap) @@ -170,30 +169,27 @@ func (q *CentralQueue) SortedFunc(cmp func(a, b CoordinatedEvent) int) iter.Seq[ } } -type coordinatedEventHeap struct { - events []CoordinatedEvent - cmp func(a, b CoordinatedEvent) int -} +type coordinatedEventHeap []CoordinatedEvent func (c *coordinatedEventHeap) Len() int { - return len(c.events) + return len(*c) } func (c *coordinatedEventHeap) Less(i, j int) bool { - return c.cmp(c.events[i], c.events[j]) < 0 + return (*c)[i].CompareDeadline(&(*c)[j]) < 0 } func (c *coordinatedEventHeap) Swap(i, j int) { - c.events[i], c.events[j] = c.events[j], c.events[i] + (*c)[i], (*c)[j] = (*c)[j], (*c)[i] } func (c *coordinatedEventHeap) Push(x any) { - c.events = append(c.events, x.(CoordinatedEvent)) + *c = append(*c, x.(CoordinatedEvent)) } func (c *coordinatedEventHeap) Pop() any { - e := c.events[len(c.events)-1] - c.events = c.events[:len(c.events)-1] + e := (*c)[len(*c)-1] + *c = (*c)[:len(*c)-1] return e } diff --git a/core/services/workflows/v2/triggers/triggers.go b/core/services/workflows/v2/triggers/triggers.go index 665c0d106d4..b653de95539 100644 --- a/core/services/workflows/v2/triggers/triggers.go +++ b/core/services/workflows/v2/triggers/triggers.go @@ -1,6 +1,7 @@ package triggers import ( + "cmp" "context" "errors" "fmt" @@ -185,6 +186,10 @@ type CoordinatedEvent struct { Event capabilities.TriggerResponse } +func (e *CoordinatedEvent) CompareDeadline(o *CoordinatedEvent) int { + return cmp.Or(e.Deadline.Compare(o.Deadline), cmp.Compare(e.Event.Event.ID, o.Event.Event.ID)) +} + func (e *CoordinatedEvent) ToProto() *pb.CoordinatedEvent { return &pb.CoordinatedEvent{ WorkflowID: e.WorkflowID, diff --git a/deployment/go.mod b/deployment/go.mod index 54f75a1bbf0..52fcdcb2041 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.20261117234947-4423d67da5d5 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087 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 d0629af5562..52da3f4f005 100644 --- a/deployment/go.sum +++ b/deployment/go.sum @@ -1411,8 +1411,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.20261117234947-4423d67da5d5 h1:V+IBcXmheTxfYQb8gX/2KFjcIwiPSz6hvJ5MmOh9hjI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087 h1:QQpXxddXoJi7b200xLaTI8yO8iKOukebi8WctQotQmY= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/go.mod b/go.mod index e3738e1879a..f8de929717a 100644 --- a/go.mod +++ b/go.mod @@ -82,7 +82,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.20261117234947-4423d67da5d5 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 github.com/smartcontractkit/chainlink-data-streams v1.1.3 diff --git a/go.sum b/go.sum index 49f1a8f32e4..e5ba383d77a 100644 --- a/go.sum +++ b/go.sum @@ -1102,8 +1102,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.20261117234947-4423d67da5d5 h1:V+IBcXmheTxfYQb8gX/2KFjcIwiPSz6hvJ5MmOh9hjI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087 h1:QQpXxddXoJi7b200xLaTI8yO8iKOukebi8WctQotQmY= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/integration-tests/go.mod b/integration-tests/go.mod index c81ab483f74..404dddb6f4b 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.20261117234947-4423d67da5d5 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087 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.20261112211734-e640e1c12078 diff --git a/integration-tests/go.sum b/integration-tests/go.sum index 3e5085b8781..fb9330cb328 100644 --- a/integration-tests/go.sum +++ b/integration-tests/go.sum @@ -1396,8 +1396,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.20261117234947-4423d67da5d5 h1:V+IBcXmheTxfYQb8gX/2KFjcIwiPSz6hvJ5MmOh9hjI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087 h1:QQpXxddXoJi7b200xLaTI8yO8iKOukebi8WctQotQmY= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/integration-tests/load/go.mod b/integration-tests/load/go.mod index 45f92ef98e1..e6c25a18c78 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.20261117234947-4423d67da5d5 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087 github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261112211734-e640e1c12078 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 c39f1ee6333..591c6c77cb0 100644 --- a/integration-tests/load/go.sum +++ b/integration-tests/load/go.sum @@ -1636,8 +1636,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.20261117234947-4423d67da5d5 h1:V+IBcXmheTxfYQb8gX/2KFjcIwiPSz6hvJ5MmOh9hjI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087 h1:QQpXxddXoJi7b200xLaTI8yO8iKOukebi8WctQotQmY= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/system-tests/lib/go.mod b/system-tests/lib/go.mod index e43c92856e0..2ab485d707f 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.20261117234947-4423d67da5d5 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087 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 cf457822624..bd08182f238 100644 --- a/system-tests/lib/go.sum +++ b/system-tests/lib/go.sum @@ -1657,8 +1657,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.20261117234947-4423d67da5d5 h1:V+IBcXmheTxfYQb8gX/2KFjcIwiPSz6hvJ5MmOh9hjI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087 h1:QQpXxddXoJi7b200xLaTI8yO8iKOukebi8WctQotQmY= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/system-tests/tests/go.mod b/system-tests/tests/go.mod index 097a1c9e70a..f4cbd125a58 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.20261117234947-4423d67da5d5 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 github.com/smartcontractkit/chainlink-confidential-compute v1.3.0 diff --git a/system-tests/tests/go.sum b/system-tests/tests/go.sum index 6b9a4b494b3..4616835de7d 100644 --- a/system-tests/tests/go.sum +++ b/system-tests/tests/go.sum @@ -1836,8 +1836,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.20261117234947-4423d67da5d5 h1:V+IBcXmheTxfYQb8gX/2KFjcIwiPSz6hvJ5MmOh9hjI= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261117234947-4423d67da5d5/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087 h1:QQpXxddXoJi7b200xLaTI8yO8iKOukebi8WctQotQmY= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= From 60e3b4d84876d42756cb4623e3aa13fc33c26de1 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Thu, 19 Nov 2026 15:39:53 -0600 Subject: [PATCH 13/38] review feedback; reorder StateTransition to limit KV data; fill gaps --- core/services/ocr3_1/plugins/queue/blobs.go | 45 ++++-- .../ocr3_1/plugins/queue/blobs_test.go | 2 +- core/services/ocr3_1/plugins/queue/kvstate.go | 126 +++++++++++----- core/services/ocr3_1/plugins/queue/math.go | 35 ----- core/services/ocr3_1/plugins/queue/queue.go | 141 ++++++++++++------ .../ocr3_1/plugins/queue/queue_test.go | 67 ++++++++- .../workflows/v2/triggers/coordinator.go | 34 ++++- core/services/workflows/v2/triggers/queue.go | 3 + 8 files changed, 316 insertions(+), 137 deletions(-) diff --git a/core/services/ocr3_1/plugins/queue/blobs.go b/core/services/ocr3_1/plugins/queue/blobs.go index b3516ab8832..1bde88bc86c 100644 --- a/core/services/ocr3_1/plugins/queue/blobs.go +++ b/core/services/ocr3_1/plugins/queue/blobs.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "sync" + "time" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/proto" @@ -42,70 +43,88 @@ func (c *blobCache) fetchBlob(ctx context.Context, handle []byte) ([]byte, error return c.fetcher.FetchBlob(ctx, blobHandle) }) c.cache[string(handle)] = fn + c.mu.Unlock() return fn() } // fetchCoordinatedEventFromBlob fetches and extracts the idx-th event from the blob, without unmarshaling any other events. func fetchCoordinatedEventFromBlob(ctx context.Context, fetcher *blobCache, handle []byte, idx int) (*pb.CoordinatedEvent, []byte, error) { - b, err := fetcher.fetchBlob(ctx, handle) + bb, err := fetcher.fetchBlob(ctx, handle) if err != nil { return nil, nil, fmt.Errorf("failed to fetch blob: %w", err) } - coordEvent, err := extractEvent(b, idx) + coordEvent, eb, err := extractEvent(bb, idx) if err != nil { return nil, nil, err } - return coordEvent, b, nil + return coordEvent, eb, nil } const coordinatedEventsFieldNumber = 1 // pb.CoordinatedEventList.Events // extractEvent extracts the idx-th event from the blob, without unmarshaling any other events. -func extractEvent(b []byte, idx int) (*pb.CoordinatedEvent, error) { +func extractEvent(b []byte, idx int) (*pb.CoordinatedEvent, []byte, error) { i := 0 for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) if n < 0 { - return nil, protowire.ParseError(n) + return nil, nil, protowire.ParseError(n) } b = b[n:] if num == coordinatedEventsFieldNumber { if typ != protowire.BytesType { - return nil, fmt.Errorf("expected bytes type for field %d, got %d", coordinatedEventsFieldNumber, typ) + return nil, 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) + return nil, nil, protowire.ParseError(m) } if i == idx { var event pb.CoordinatedEvent if err := proto.Unmarshal(v, &event); err != nil { - return nil, fmt.Errorf("failed to unmarshal event: %w", err) + return nil, v, fmt.Errorf("failed to unmarshal event: %w", err) } - return &event, nil + return &event, v, nil } // advance i++ b = b[m:] continue + } else { + n := protowire.ConsumeFieldValue(num, typ, b) + if n < 0 { + return nil, nil, protowire.ParseError(n) + } + b = b[n:] } } - return nil, fmt.Errorf("index %d out of range", idx) + return nil, nil, fmt.Errorf("index %d out of range", idx) } -// broadcastAsBlob broadcasts a list of coordinated events and returns a blob handle. -func broadcastAsBlob(ctx context.Context, broadcaster ocr3_1types.BlobBroadcastFetcher, events []*pb.CoordinatedEvent, expSeq uint64) (blobHandle []byte, n int, err error) { +// broadcastAsBlob broadcasts a blob with as many coordinated events as possible, returning the blob handle and count of events included. +func broadcastAsBlob(ctx context.Context, broadcaster ocr3_1types.BlobBroadcastFetcher, events []*pb.CoordinatedEvent, + seqNr uint64, estimatedRoundInterval time.Duration) (blobHandle []byte, n int, err error) { protoOpts := proto.MarshalOptions{Deterministic: true} for ; protoOpts.Size(&pb.CoordinatedEventList{Events: events}) > maxBlobPayloadBytes; events = events[:len(events)-1] { //TODO opt: binary search for largest fit instead.... } n = len(events) + var maxDeadline time.Time + for _, event := range events { + if t := event.Deadline.AsTime(); t.After(maxDeadline) { + maxDeadline = t + } + } + roundDur := estimatedRoundInterval //TODO OK? pad? + //TODO pad extra time and/or rounds? + expSeqNr := seqNr + uint64(time.Until(maxDeadline)/roundDur) + data, err := protoOpts.Marshal(&pb.CoordinatedEventList{Events: events}) if err != nil { return nil, -1, fmt.Errorf("failed to marshal blob: %w", err) } - bh, err := broadcaster.BroadcastBlob(ctx, data, ocr3_1types.BlobExpirationHintSequenceNumber{SeqNr: expSeq}) + bh, err := broadcaster.BroadcastBlob(ctx, data, ocr3_1types.BlobExpirationHintSequenceNumber{SeqNr: expSeqNr}) if err != nil { return nil, -1, fmt.Errorf("failed to broadcast blob: %w", err) } diff --git a/core/services/ocr3_1/plugins/queue/blobs_test.go b/core/services/ocr3_1/plugins/queue/blobs_test.go index 8a9041e5cf4..eaa8e74fb50 100644 --- a/core/services/ocr3_1/plugins/queue/blobs_test.go +++ b/core/services/ocr3_1/plugins/queue/blobs_test.go @@ -70,7 +70,7 @@ func Test_extractEvent(t *testing.T) { } b, err := proto.MarshalOptions{Deterministic: true}.Marshal(&pb.CoordinatedEventList{Events: events}) require.NoError(t, err) - got, err := extractEvent(b, tt.idx) + got, _, err := extractEvent(b, tt.idx) if tt.idx < tt.len { require.True(t, proto.Equal(event, got)) } else { diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index 8354cd96ff0..dbdea067ed4 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -1,6 +1,7 @@ package queue import ( + "cmp" "container/heap" "fmt" "maps" @@ -44,7 +45,12 @@ 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 { return len(*p) } +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] @@ -60,7 +66,9 @@ func (p *priorityQueue) Push(x any) { } func (p *priorityQueue) Pop() any { - return (*p)[len(*p)-1] + e := (*p)[len(*p)-1] + *p = (*p)[:len(*p)-1] + return e } func (p *priorityQueue) push(x *pb.ConsensusQueueEvent) { heap.Push(p, x) } @@ -89,30 +97,39 @@ func (p *priorityQueue) mustPop() *pb.ConsensusQueueEvent { // popLimited pops up to capacity events from the queue, each of which must also have sufficient wf capacity. // Note: capPerWF is mutated. -func (p *priorityQueue) popLimited(capacity uint32, capPerWF map[string]uint32, expiration time.Time) []*pb.ConsensusQueueEvent { - var events []*pb.ConsensusQueueEvent +func (p *priorityQueue) popLimited(capPerWF map[string]uint32, expiration time.Time) (event *pb.ConsensusQueueEvent) { var wfLimited []*pb.ConsensusQueueEvent // omitted due to workflow limit - for len(events) < int(capacity) { - next := p.mustPop() - if next == nil { + for { + event = p.mustPop() + if event == nil { break } - if next.Deadline.AsTime().Before(expiration) { + if event.Deadline.AsTime().Before(expiration) { // drop expired continue } - if capPerWF[next.WorkflowID] == 0 { - wfLimited = append(wfLimited, next) + if capPerWF[event.WorkflowID] == 0 { + // ignore but restore after + wfLimited = append(wfLimited, event) continue } - capPerWF[next.WorkflowID]-- - events = append(events, next) + capPerWF[event.WorkflowID]-- + break } // restore omitted for next time - for _, event := range wfLimited { - p.push(event) + for _, limited := range wfLimited { + p.push(limited) } - return events + return +} + +type revPriorityQueue struct { + *priorityQueue +} + +func (r *revPriorityQueue) Less(i, j int) bool { + a, b := (*r.priorityQueue)[i], (*r.priorityQueue)[j] + return b.CompareDeadline(a) < 0 } type blobHandleMap map[string]map[string]uint32 // eventHash -> blobHandle -> idx @@ -162,8 +179,8 @@ func (s *kvState) loadFrom(kv ocr3_1types.KeyValueStateReadWriter) error { return fmt.Errorf("failed to read queued events: %w", err) } if v != nil { - var queued *pb.ConsensusQueueEventList - if err = proto.Unmarshal(v, queued); err != nil { + var queued pb.ConsensusQueueEventList + if err = proto.Unmarshal(v, &queued); err != nil { return fmt.Errorf("failed to unmarshal queued events: %w", err) } s.queuedEvents = new(priorityQueue(queued.GetEvents())) @@ -190,8 +207,8 @@ func readObservedEvents(kv ocr3_1types.KeyValueStateReader) (observedEvents map[ } observedBlobs = make(blobHandleMap) if v != nil { - var observed *pb.ConsensusQueueObservedEvents - if err = proto.Unmarshal(v, observed); err != 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) @@ -212,31 +229,49 @@ func readObservedEvents(kv ocr3_1types.KeyValueStateReader) (observedEvents map[ // sizeOf returns the size of the state when serialized and written to the KV store via writeAll. func (s *kvState) sizeOf() (size int) { - s.prepareWrite() - - //TODO check maxKeyValueValueBytes too? - protoOpts := proto.MarshalOptions{Deterministic: true} size += len(observedEventsKey) + len(queuedEventsKey) + len(consensusEventsKey) + len(blobHandlesKey) - size += protoOpts.Size(&pb.ConsensusQueueObservedEvents{Observations: s.observedEventEntries, BlobHandles: s.observedBlobHandles}) - size += protoOpts.Size(&pb.ConsensusQueueEventList{Events: *s.queuedEvents}) - size += protoOpts.Size(&pb.ConsensusQueueEventList{Events: s.consensusEvents}) - size += protoOpts.Size(&pb.ConsensusQueueBlobHandleList{BlobHandles: s.queuedBlobHandles}) - + size += s.sizeOfObservedEvents() + s.sizeOfQueuedEvents() + s.sizeOfConsensusEvents() + s.sizeOfBlobHandles() + //TODO opt: proto.MarshalOptions.UseCachedSize return } -// prepareWrite initializes observed and queued blob handles and updates the event references. -func (s *kvState) prepareWrite() { +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 { + return proto.MarshalOptions{Deterministic: true}.Size(&pb.ConsensusQueueEventList{Events: *s.queuedEvents}) +} + +func (s *kvState) sizeOfConsensusEvents() int { + 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 - //TODO deadline order so that we can drop efficiently - for _, eventHash := range slices.Sorted(maps.Keys(s.observedEvents)) { + + // 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] + //TODO can we use deadline here? is median valid & best option? + return cmp.Or(cmp.Compare(len(ea.NodeIds), len(eb.NodeIds)), + cmp.Compare(ea.TriggerEventID, eb.TriggerEventID)) + }) { event := s.observedEvents[eventHash] event.Blobs = nil // replace all - for blobHandle, ei := range s.observedBlobs[eventHash] { + for _, blobHandle := range slices.Sorted(maps.Keys(s.observedBlobs[eventHash])) { + ei := s.observedBlobs[eventHash][blobHandle] idx, ok := observedBlobIndexes[blobHandle] if !ok { idx = len(s.observedBlobHandles) @@ -251,13 +286,17 @@ func (s *kvState) prepareWrite() { 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 { var blobHandles []*pb.CoordinatedEventBlobHandle - for blobHandle, ei := range blobs { + for _, blobHandle := range slices.Sorted(maps.Keys(blobs)) { + ei := blobs[blobHandle] idx, ok := queuedBlobIndexes[blobHandle] if !ok { idx = len(s.queuedBlobHandles) @@ -334,7 +373,8 @@ func (s *kvState) pruneExpiredObservations(expiration time.Time) { // addObserved adds the observed events to the set, promoting to the priority queue on 2f+1 and calling onQueued. func (s *kvState) addObservedEvents(f int, toAdd map[string]*pb.ConsensusQueueObservedEvent, observedBlobs blobHandleMap, onQueued func(event *pb.ConsensusQueueEvent)) { - for eventHash, eventToAdd := range toAdd { + for _, eventHash := range slices.Sorted(maps.Keys(toAdd)) { + eventToAdd := toAdd[eventHash] obsEvent, ok := s.observedEvents[eventHash] if !ok && len(eventToAdd.NodeIds) >= 2*f+1 { // new proposal straight to priority queue @@ -349,12 +389,16 @@ func (s *kvState) addObservedEvents(f int, toAdd map[string]*pb.ConsensusQueueOb // update proposal // TODO opt: build a map to avoid n^2? for i, node := range eventToAdd.NodeIds { - if !slices.Contains(obsEvent.NodeIds, node) { + 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]) obsEvent.Blobs = append(obsEvent.Blobs, eventToAdd.Blobs[i]) - } //TODO what if a node reports twice with different deadline or observation? do we need to overwrite? + } else { // overwrite previous observation + obsEvent.ObservedAts[prev] = eventToAdd.ObservedAts[i] + obsEvent.Deadlines[prev] = eventToAdd.Deadlines[i] + obsEvent.Blobs[prev] = eventToAdd.Blobs[i] + } } if len(obsEvent.NodeIds) >= 2*f+1 { @@ -378,8 +422,8 @@ func readConsensusState(kvReader ocr3_1types.KeyValueStateReader) ([]*pb.Consens var consensusEvents []*pb.ConsensusQueueEvent if v != nil { - var pbs *pb.ConsensusQueueEventList - if err := proto.Unmarshal(v, pbs); err != 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() @@ -401,8 +445,8 @@ func readBlobHandles(kvReader ocr3_1types.KeyValueStateReader) ([][]byte, error) var blobHandles [][]byte if v != nil { - var bs *pb.ConsensusQueueBlobHandleList - if err := proto.Unmarshal(v, bs); err != 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() diff --git a/core/services/ocr3_1/plugins/queue/math.go b/core/services/ocr3_1/plugins/queue/math.go index b67cd83cb08..400276f25df 100644 --- a/core/services/ocr3_1/plugins/queue/math.go +++ b/core/services/ocr3_1/plugins/queue/math.go @@ -4,44 +4,9 @@ import ( "slices" "time" - "golang.org/x/exp/constraints" "google.golang.org/protobuf/types/known/timestamppb" ) -// median returns the median value of a slice of integers, as well as a count of the number of occurrences of the median. -// len must be greater than 0. -func median[N constraints.Integer, S []N](s S) (N, int) { - switch len(s) { - case 0: - panic("median: len must be greater than 0") - case 1: - return s[0], 1 - } - slices.Sort(s) - if len(s)%2 == 1 { - m := s[len(s)/2] - return m, count(s, m) - } - // avg of two - a, b := s[len(s)/2], s[len(s)/2-1] - diff := a - b - m := b + diff/2 - return m, count(s, m) -} - -// count returns the number of occurrences of e in s, but s must be sorted. -func count[N comparable, S []N](s S, e N) int { - firstIndex := slices.Index(s, e) - if firstIndex == -1 { - return 0 - } - var c int - for i := firstIndex; i < len(s) && s[i] == e; i++ { - c++ - } - return c -} - // medianTimestamp returns the median value of a slice of timestamps. // len must be greater than 0. func medianTimestamp(s []*timestamppb.Timestamp) *timestamppb.Timestamp { diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index 04c9676021a..895c19d9a50 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -8,6 +8,7 @@ package queue import ( "bytes" + "container/heap" "context" "crypto/sha256" "errors" @@ -53,6 +54,15 @@ func NewConsensusQueuePluginFactory( triggerCoordinator triggers.Coordinator, triggerQueue triggers.Queue, ) (ocr3_1types.ReportingPluginFactory[[]byte], error) { + if cfg == nil { + return nil, errors.New("cfg cannot be nil") + } + if triggerCoordinator == nil { + return nil, errors.New("triggerCoordinator cannot be nil") + } + if triggerQueue == nil { + return nil, errors.New("triggerQueue cannot be nil") + } return &consensusQueuePluginFactory{ lggr: lggr, cfg: cfg, @@ -96,7 +106,7 @@ func newConsensusQueuePlugin( c := &consensusQueuePlugin{ lggr: logger.Named(lggr, "ConsensusQueuePlugin"), onchainCfg: onchainCfg, - blobHandleMarshalledBytesUpperBound: ocr3_1types.BlobHandleMarshalledBytesUpperBound(onchainCfg.F, onchainCfg.N), + blobHandleMarshalledBytesUpperBound: ocr3_1types.BlobHandleMarshalledBytesUpperBound(onchainCfg.N, onchainCfg.F), triggerCoordinator: triggerCoordinator, triggerQueue: triggerQueue, blobBroadcastFetcher: blobs, @@ -199,12 +209,9 @@ func (c *consensusQueuePlugin) Observation( } } - roundDur := c.onchainCfg.EstimatedRoundInterval //TODO OK? - expSeqNr := seqNr + uint64(expirationGraceDur/roundDur) //TODO pad extra time and/or rounds? - obs.BlobHandles = nil // remove the placeholders if len(coordEvents) > 0 { - blobHandle, n, err2 := broadcastAsBlob(ctx, blobBroadcaster, coordEvents, expSeqNr) + blobHandle, n, err2 := broadcastAsBlob(ctx, blobBroadcaster, coordEvents, seqNr, c.onchainCfg.EstimatedRoundInterval) if err2 != nil { return nil, err2 } @@ -212,15 +219,16 @@ func (c *consensusQueuePlugin) Observation( // note: elements already reference blob 0 and natural element index is aligned var offset int + //TODO stop after batch maxObservedBlobHandles for batch := 1; n < len(coordEvents); batch++ { offset += n coordEvents = coordEvents[n:] - blobHandle, n, err2 = broadcastAsBlob(ctx, blobBroadcaster, coordEvents, expSeqNr) + blobHandle, n, err2 = broadcastAsBlob(ctx, blobBroadcaster, coordEvents, seqNr, c.onchainCfg.EstimatedRoundInterval) if err2 != nil { return nil, err2 } obs.BlobHandles = append(obs.BlobHandles, blobHandle) - for i := n; i < n; i++ { // update indices + for i := offset; i < n; i++ { // update indices obs.Events[offset+i].Blobs[0].Blob = uint32(batch) obs.Events[offset+i].Blobs[0].Element = uint32(i) } @@ -260,9 +268,6 @@ func (c *consensusQueuePlugin) ValidateObservation( if len(obs.Events) > maxObservedEvents { return fmt.Errorf("events are limited to %d but got %d", maxObservedEvents, len(obs.Events)) } - if !slices.IsSortedFunc(obs.Events, (*pb.ConsensusQueueEvent).CompareDeadline) { - return fmt.Errorf("events must be sorted") - } var eg errgroup.Group fetcher := blobCache{fetcher: blobFetcher, cache: make(map[string]func() ([]byte, error))} for i, event := range obs.Events { @@ -273,7 +278,16 @@ func (c *consensusQueuePlugin) ValidateObservation( return nil }) } - return eg.Wait() + if err = eg.Wait(); err != nil { + return err + } + + // wait to do this since we depend on every event being valid + if !slices.IsSortedFunc(obs.Events, (*pb.ConsensusQueueEvent).CompareDeadline) { + return fmt.Errorf("events must be sorted") + } + + return nil } func validateObservedEvent(ctx context.Context, fetcher *blobCache, event *pb.ConsensusQueueEvent, blobHandles [][]byte) error { @@ -344,7 +358,7 @@ func (c *consensusQueuePlugin) StateTransition( ctx context.Context, _ uint64, _ ocrtypes.AttributedQuery, aos []ocrtypes.AttributedObservation, kvReaderWriter ocr3_1types.KeyValueStateReadWriter, _ ocr3_1types.BlobFetcher, ) (ocr3_1types.ReportsPlusPrecursor, error) { - var done chan struct{} + done := make(chan struct{}) var obs observations go func() { @@ -370,9 +384,6 @@ func (c *consensusQueuePlugin) StateTransition( if obs.err != nil { return nil, fmt.Errorf("failed to aggregate observations: %w", obs.err) } - if obs.warn != nil { - c.lggr.Warnw("Failed to aggregate some observations", "err", obs.warn) - } // update state state.pruneExpiredObservations(obs.medianExpiration) @@ -380,20 +391,71 @@ func (c *consensusQueuePlugin) StateTransition( state.addObservedEvents(c.onchainCfg.F, obs.newObservedEvents, obs.observedBlobs, func(event *pb.ConsensusQueueEvent) { queuedTriggerEventIDs = append(queuedTriggerEventIDs, event.TriggerEventID) }) - state.consensusEvents = state.queuedEvents.popLimited(obs.medianCap, obs.medianCapPerWF, obs.medianExpiration) + // pop as many queuedEvents as possible in to consensusEvents (up to capacity or KV limits) + for len(*state.queuedEvents) > 0 && len(state.consensusEvents) < int(obs.medianCap) { + event := state.queuedEvents.popLimited(obs.medianCapPerWF, obs.medianExpiration) + if event == nil { + break + } + state.consensusEvents = append(state.consensusEvents, event) + // stop when either value or the overall size is too large + if events, blobs := state.sizeOfConsensusEvents(), state.sizeOfBlobHandles(); events > maxKeyValueValueBytes || + blobs > maxKeyValueValueBytes || events+blobs > maxKeyValueModifiedKeysPlusValuesBytes/2 { + state.consensusEvents = state.consensusEvents[:len(state.consensusEvents)-1] + break + } + } - // prune observations until we fit - for state.sizeOf() > maxKeyValueModifiedKeysPlusValuesBytes { - //TODO drop observations (must be deterministic, fair, efficient) - // prefer farthest future deadlines and fewest observations - //TODO use sorted state.observedEventEntries + // prune observations if that value or the overall size is too large + for len(state.observedEventEntries) > 0 && + (state.sizeOfObservedEvents() > maxKeyValueValueBytes || + state.sizeOf() > maxKeyValueModifiedKeysPlusValuesBytes) { + // sorted by decreasing priority, so prune the last + toRemove := state.observedEventEntries[len(state.observedEventEntries)-1] + delete(state.observedEvents, toRemove.Event.TriggerEventID) + //TODO opt: drop more than one each time? + } + + // prune queuedEvents if that value, blob handles, or the overall size is too large + if len(*state.queuedEvents) > 0 && + (state.sizeOfQueuedEvents() > maxKeyValueValueBytes || + state.sizeOfBlobHandles() > maxKeyValueValueBytes || + state.sizeOf() > maxKeyValueModifiedKeysPlusValuesBytes) { + // prune lowest priority queuedEvents from newly added queuedTriggerEventIDs + queuedTriggerEventIDSet := map[string]struct{}{} + for _, id := range queuedTriggerEventIDs { + queuedTriggerEventIDSet[id] = struct{}{} + } + eligibleEvents := make([]*pb.ConsensusQueueEvent, 0, len(*state.queuedEvents)) + for _, e := range *state.queuedEvents { + if _, ok := queuedTriggerEventIDSet[e.TriggerEventID]; ok { + eligibleEvents = append(eligibleEvents, e) + } + } + backwardsQueuedEvents := &revPriorityQueue{priorityQueue: new(priorityQueue(eligibleEvents))} + heap.Init(backwardsQueuedEvents) + + // prune until we fit + for backwardsQueuedEvents.Len() > 0 && + (state.sizeOfQueuedEvents() > maxKeyValueValueBytes || + state.sizeOfBlobHandles() > maxKeyValueValueBytes || + state.sizeOf() > maxKeyValueModifiedKeysPlusValuesBytes) { + toRemove := heap.Pop(backwardsQueuedEvents).(*pb.ConsensusQueueEvent) + //TODO opt: faster delete...but need to maintain state.queuedEvents (though not order)...map indices? + *state.queuedEvents = slices.DeleteFunc(*state.queuedEvents, func(e *pb.ConsensusQueueEvent) bool { return e.TriggerEventID == toRemove.TriggerEventID }) + //TODO opt: drop more than one each time? + } + // rebuild the priority queue + heap.Init(state.queuedEvents) } + // note: no need to prune consensus events, since already limited what we collected + err = state.writeTo(&stateWriter{kv: kvReaderWriter}) if err != nil { return nil, err } - c.triggerQueue.Remove(ctx, queuedTriggerEventIDs) + c.triggerQueue.Remove(ctx, queuedTriggerEventIDs) //TODO move to committed - do we need to write it through KV? or can we Remove the whole PQ every time? // no report to return, executions start when committed return nil, nil @@ -405,8 +467,8 @@ type observations struct { medianCapPerWF map[string]uint32 // wf ID -> capacity newObservedEvents map[string]*pb.ConsensusQueueObservedEvent // key: timeless hash observedBlobs blobHandleMap - warn error - err error + + err error } func (res *observations) aggregate(ctx context.Context, f int, aos []ocrtypes.AttributedObservation) { @@ -420,8 +482,8 @@ func (res *observations) aggregate(ctx context.Context, f int, aos []ocrtypes.At var obs pb.ConsensusQueueObservation err := proto.Unmarshal(ao.Observation, &obs) if err != nil { - res.warn = errors.Join(res.warn, fmt.Errorf("failed to unmarshal observation from oracle %d: %w", ao.Observation, err)) - continue + res.err = fmt.Errorf("failed to unmarshal observation from oracle %d: %w", ao.Observer, err) + return } expirations = append(expirations, obs.Expiration) capacities = append(capacities, obs.Capacity) @@ -437,16 +499,16 @@ func (res *observations) aggregate(ctx context.Context, f int, aos []ocrtypes.At } res.medianExpiration = medianTimestamp(expirations).AsTime() - // Medianize capacities, and when there is disagreement among honest nodes, scale back to 90%. + // 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. var medianCount int - res.medianCap, medianCount = median(capacities) - if medianCount < 2*f+1 { - res.medianCap = (res.medianCap * 9) / 10 - } + res.medianCap = slices.Sorted(slices.Values(capacities))[f] for wf, caps := range wfCapacities { - res.medianCapPerWF[wf], medianCount = median(caps) - if medianCount < 2*f+1 { - res.medianCapPerWF[wf] = (res.medianCapPerWF[wf] * 9) / 10 + if len(caps) > 2*f+1 { + res.medianCapPerWF[wf] = slices.Sorted(slices.Values(caps))[f] + if medianCount < 2*f+1 { + res.medianCapPerWF[wf] = (res.medianCapPerWF[wf] * 9) / 10 + } } } return @@ -535,16 +597,7 @@ func (c *consensusQueuePlugin) tryStartExecution(ctx context.Context, fetcher *b return fmt.Errorf("failed to convert CoordinatedEvent from proto: %w", err) } - // TODO c.triggerCoordinator.Deliver(ctx, event) - - // only log metadata, not outputs and payload - event.Event.Event.Outputs = nil - event.Event.Event.Payload = nil - latency := time.Since(event.ObservedAt) - c.lggr.Infow("Consensus event dry run completed", "observedAt", event.ObservedAt, "latency", latency, "event", event) - //TODO emit latency metric - - return nil + return c.triggerCoordinator.StartExecution(ctx, event) } func (c *consensusQueuePlugin) Reports(ctx context.Context, _ uint64, _ ocr3_1types.ReportsPlusPrecursor) ([]ocr3types.ReportPlus[[]byte], error) { diff --git a/core/services/ocr3_1/plugins/queue/queue_test.go b/core/services/ocr3_1/plugins/queue/queue_test.go index 5f5173eca06..9ce9228d4fa 100644 --- a/core/services/ocr3_1/plugins/queue/queue_test.go +++ b/core/services/ocr3_1/plugins/queue/queue_test.go @@ -1,6 +1,8 @@ package queue import ( + "context" + "iter" "testing" "github.com/stretchr/testify/require" @@ -10,6 +12,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/settings/limits" + "github.com/smartcontractkit/chainlink/v2/core/services/workflows/v2/triggers" ) // libocr calls NewReportingPlugin with no recover, so a panic here takes down @@ -18,7 +21,7 @@ func TestConsensusQueuePluginFactory_NewReportingPlugin(t *testing.T) { t.Parallel() cfg := &PluginConfig{Limits: ocr3_1types.ReportingPluginLimits{MaxKeyValueModifiedKeys: 1}} - factory, err := NewConsensusQueuePluginFactory(logger.Test(t), cfg, limits.Factory{}, nil, nil) + factory, err := NewConsensusQueuePluginFactory(logger.Test(t), cfg, limits.Factory{}, noopCoordinator{}, noopQueue{}) require.NoError(t, err) plugin, info, err := factory.NewReportingPlugin(t.Context(), ocr3types.ReportingPluginConfig{N: 4, F: 1}, nil) @@ -32,3 +35,65 @@ func TestConsensusQueuePluginFactory_NewReportingPlugin(t *testing.T) { require.NoError(t, plugin.Close()) } + +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 +} + +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() iter.Seq[triggers.CoordinatedEvent] { + return func(yield func(triggers.CoordinatedEvent) bool) {} +} + +func (n noopQueue) Remove(ctx context.Context, triggerEventIDs []string) {} diff --git a/core/services/workflows/v2/triggers/coordinator.go b/core/services/workflows/v2/triggers/coordinator.go index 27a7691ac74..f12ced66992 100644 --- a/core/services/workflows/v2/triggers/coordinator.go +++ b/core/services/workflows/v2/triggers/coordinator.go @@ -84,7 +84,8 @@ type Coordinator interface { // limiter does not break down by scope. AvailableCapacity(ctx context.Context) (Capacity, error) - //TODO Deliver(context.Context, CoordinatedEvent + // StartExecution starts execution of the triggered event or returns an error. + StartExecution(context.Context, CoordinatedEvent) error } // RegisteredEngine is what EngineRegistry.Get returns: a sink the coordinator @@ -478,6 +479,35 @@ func (c *coordinator) Ack(ctx context.Context, triggerCapID, triggerRegistration return Ack(ctx, lggr, wfMetrics, triggerCapID, triggerRegistrationID, eventID, handle) } +func (c *coordinator) StartExecution(ctx context.Context, event CoordinatedEvent) error { + wfID, err := types.WorkflowIDFromHex(event.WorkflowID) + if err != nil { + return err + } + + //TODO share code with admitEvent? + + eng, ok := c.engines.Get(wfID) + if !ok { + return fmt.Errorf("workflow %s: engine not found", wfID) + } + if !eng.IsCoordinated() { + return fmt.Errorf("workflow %s: engine not coordinated", wfID) + } + + //TODO more admission checks? + // c.admission.ExecutionConcurrency.Wait(ctx, 1)? + + _ = time.Since(event.ObservedAt) //TODO emit latency metric + + if err = eng.ExecuteTrigger(ctx, event); err != nil { + //TODO handle errors, ack? + return fmt.Errorf("workflow %s: failed to execute trigger %s: %w", wfID, event.Event.Event.ID, err) + } + + 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 { @@ -634,7 +664,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) { //TODO grace period 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) diff --git a/core/services/workflows/v2/triggers/queue.go b/core/services/workflows/v2/triggers/queue.go index a8f9585ef0f..35643d60577 100644 --- a/core/services/workflows/v2/triggers/queue.go +++ b/core/services/workflows/v2/triggers/queue.go @@ -172,6 +172,9 @@ func (q *CentralQueue) Sorted() iter.Seq[CoordinatedEvent] { type coordinatedEventHeap []CoordinatedEvent func (c *coordinatedEventHeap) Len() int { + if c == nil { + return 0 + } return len(*c) } From d9b007e774cce02cc98877372d75077550d077c5 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Fri, 20 Nov 2026 08:09:25 -0600 Subject: [PATCH 14/38] drop observations < f+1; limit workflowCapacities; remove from queue during commit; validate no dupe event IDs or hashes; nil checks --- core/services/ocr3_1/plugins/queue/kvstate.go | 66 +++++++---- core/services/ocr3_1/plugins/queue/queue.go | 112 +++++++++++++----- .../ocr3_1/plugins/queue/queue_test.go | 2 +- core/services/workflows/v2/triggers/queue.go | 9 +- 4 files changed, 132 insertions(+), 57 deletions(-) diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index dbdea067ed4..9a1fa0585db 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -66,6 +66,9 @@ func (p *priorityQueue) Push(x any) { } func (p *priorityQueue) Pop() any { + if p.Len() == 0 { + return nil + } e := (*p)[len(*p)-1] *p = (*p)[:len(*p)-1] return e @@ -89,7 +92,7 @@ func (p *priorityQueue) pushObservations(timelessHash string, obs *pb.ConsensusQ // 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 len(*p) == 0 { + if p.Len() == 0 { return nil } return heap.Pop(p).(*pb.ConsensusQueueEvent) @@ -158,7 +161,7 @@ type kvState struct { observedBlobHandles [][]byte // only populated before write // priorityQueueKey - queuedEvents *priorityQueue + queuedEvents priorityQueue // consensusEventsKey consensusEvents []*pb.ConsensusQueueEvent // blobHandlesKey @@ -174,24 +177,18 @@ func (s *kvState) loadFrom(kv ocr3_1types.KeyValueStateReadWriter) error { return err } - v, err := kv.Read([]byte(queuedEventsKey)) + queuedEvents, err := readQueuedEvents(kv) if err != nil { - return 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 fmt.Errorf("failed to unmarshal queued events: %w", err) - } - s.queuedEvents = new(priorityQueue(queued.GetEvents())) + return err } + s.queuedEvents = queuedEvents s.queuedBlobs = make(blobHandleMap) queuedBlobs, err := readBlobHandles(kv) if err != nil { return err } - for _, event := range []*pb.ConsensusQueueEvent(*s.queuedEvents) { + for _, event := range s.queuedEvents { for _, blob := range event.GetBlobs() { s.queuedBlobs.add(string(event.TimelessHash), string(queuedBlobs[blob.Blob]), blob.Element) } @@ -200,6 +197,21 @@ func (s *kvState) loadFrom(kv ocr3_1types.KeyValueStateReadWriter) error { 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 blobHandleMap, err error) { v, err := kv.Read([]byte(observedEventsKey)) if err != nil { @@ -242,7 +254,7 @@ func (s *kvState) sizeOfObservedEvents() int { } func (s *kvState) sizeOfQueuedEvents() int { - return proto.MarshalOptions{Deterministic: true}.Size(&pb.ConsensusQueueEventList{Events: *s.queuedEvents}) + return proto.MarshalOptions{Deterministic: true}.Size(&pb.ConsensusQueueEventList{Events: s.queuedEvents}) } func (s *kvState) sizeOfConsensusEvents() int { @@ -310,7 +322,7 @@ func (s *kvState) prepareWriteBlobHandles() { } return blobHandles } - for _, event := range []*pb.ConsensusQueueEvent(*s.queuedEvents) { + for _, event := range s.queuedEvents { event.Blobs = addBlobs(s.queuedBlobs[string(event.TimelessHash)]) } for _, event := range s.consensusEvents { @@ -328,7 +340,7 @@ func (s *kvState) writeTo(w *stateWriter) error { return fmt.Errorf("failed to write observed events: %w", err) } - err = w.writeValue(queuedEventsKey, &pb.ConsensusQueueEventList{Events: *s.queuedEvents}) + err = w.writeValue(queuedEventsKey, &pb.ConsensusQueueEventList{Events: s.queuedEvents}) if err != nil { return fmt.Errorf("failed to write queued events: %w", err) } @@ -372,19 +384,25 @@ func (s *kvState) pruneExpiredObservations(expiration time.Time) { } // addObserved adds the observed events to the set, promoting to the priority queue on 2f+1 and calling onQueued. +// Events with fewer than f+1 observations are ignored. func (s *kvState) addObservedEvents(f int, toAdd map[string]*pb.ConsensusQueueObservedEvent, observedBlobs blobHandleMap, onQueued func(event *pb.ConsensusQueueEvent)) { for _, eventHash := range slices.Sorted(maps.Keys(toAdd)) { eventToAdd := toAdd[eventHash] obsEvent, ok := s.observedEvents[eventHash] - if !ok && len(eventToAdd.NodeIds) >= 2*f+1 { - // new proposal straight to priority queue - s.queuedBlobs.addAll(eventHash, observedBlobs[eventHash]) - event := s.queuedEvents.pushObservations(eventHash, eventToAdd) - onQueued(event) - } else if !ok { - // new proposal < f + 1 - s.observedBlobs.addAll(eventHash, observedBlobs[eventHash]) - s.observedEvents[eventHash] = eventToAdd + if !ok { + switch { + case len(eventToAdd.NodeIds) >= 2*f+1: + // new proposal straight to priority queue + s.queuedBlobs.addAll(eventHash, observedBlobs[eventHash]) + event := s.queuedEvents.pushObservations(eventHash, eventToAdd) + onQueued(event) + case len(eventToAdd.NodeIds) >= f+1: + // new proposal to the observation set + s.observedBlobs.addAll(eventHash, observedBlobs[eventHash]) + s.observedEvents[eventHash] = eventToAdd + default: + // new proposal without enough observations < f + 1 + } } else { // update proposal // TODO opt: build a map to avoid n^2? diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index 895c19d9a50..636a3e69a51 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -126,9 +126,16 @@ func (c *consensusQueuePlugin) Observation( ctx context.Context, seqNr uint64, _ ocrtypes.AttributedQuery, kvReader ocr3_1types.KeyValueStateReader, blobBroadcaster ocr3_1types.BlobBroadcastFetcher, ) (ocrtypes.Observation, error) { - // Always attempt to start any executions from the KV Store in the event Committed was not called. - // tryStartExecutions is idempotent. - c.tryStartExecutions(kvReader) + // 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 { @@ -148,14 +155,15 @@ func (c *consensusQueuePlugin) Observation( Capacity: uint32(min(capacity.Global, math.MaxUint32)), WorkflowCapacities: make(map[string]uint32), } - for wf, wfCap := range capacity.PerWorkflow { - //TODO only for events proposed and queued in the KV store? - obs.WorkflowCapacities[wf] = uint32(min(wfCap, math.MaxUint32)) + for _, e := range observedEvents { + if wfCap, ok := capacity.PerWorkflow[e.WorkflowID]; ok { + obs.WorkflowCapacities[e.WorkflowID] = uint32(min(wfCap, math.MaxUint32)) + } } - - observedEvents, _, err := readObservedEvents(kvReader) - if err != nil { - return nil, err + for _, e := range queuedEvents { + if wfCap, ok := capacity.PerWorkflow[e.WorkflowID]; ok { + obs.WorkflowCapacities[e.WorkflowID] = uint32(min(wfCap, math.MaxUint32)) + } } protoOpts := proto.MarshalOptions{Deterministic: true} @@ -167,7 +175,8 @@ func (c *consensusQueuePlugin) Observation( coord.ObservedAt, coord.Deadline = nil, nil // for consistent hashing protoBytes, err2 := protoOpts.Marshal(coord) // TODO opt: avoid remarshalling if err2 != nil { - c.lggr.Errorw("failed to marshal event", "eventID", coord.Event.Event.Id, "err", err2) + c.lggr.Errorw("Failed to marshal event. Excluding from observation", "eventID", coord.Event.Event.Id, "err", err2) + //TODO remove from triggerQueue? continue } timelessHash := sha256.Sum256(protoBytes) @@ -218,9 +227,9 @@ func (c *consensusQueuePlugin) Observation( obs.BlobHandles = append(obs.BlobHandles, blobHandle) // note: elements already reference blob 0 and natural element index is aligned + // we verified space for up to maxObservedBlobHandles blobs var offset int - //TODO stop after batch maxObservedBlobHandles - for batch := 1; n < len(coordEvents); batch++ { + for batch := 1; batch < maxObservedBlobHandles && n < len(coordEvents); batch++ { offset += n coordEvents = coordEvents[n:] blobHandle, n, err2 = broadcastAsBlob(ctx, blobBroadcaster, coordEvents, seqNr, c.onchainCfg.EstimatedRoundInterval) @@ -282,6 +291,23 @@ func (c *consensusQueuePlugin) ValidateObservation( return err } + //TODO ensure capacity map is only observations and KV observed & queued events + + // ensure no duplicated trigger event ID or timelessHash + triggerEventIDs, timelessHashes := make(map[string]struct{}), make(map[string]struct{}) + for _, event := range obs.Events { + if _, ok := triggerEventIDs[event.TriggerEventID]; ok { + return fmt.Errorf("duplicate trigger event ID: %s", event.TriggerEventID) + } + triggerEventIDs[event.TriggerEventID] = struct{}{} + + timelessHash := string(event.TimelessHash) + if _, ok := timelessHashes[timelessHash]; ok { + return fmt.Errorf("duplicate timeless hash: %x", event.TimelessHash) + } + timelessHashes[timelessHash] = struct{}{} + } + // wait to do this since we depend on every event being valid if !slices.IsSortedFunc(obs.Events, (*pb.ConsensusQueueEvent).CompareDeadline) { return fmt.Errorf("events must be sorted") @@ -392,7 +418,7 @@ func (c *consensusQueuePlugin) StateTransition( queuedTriggerEventIDs = append(queuedTriggerEventIDs, event.TriggerEventID) }) // pop as many queuedEvents as possible in to consensusEvents (up to capacity or KV limits) - for len(*state.queuedEvents) > 0 && len(state.consensusEvents) < int(obs.medianCap) { + for len(state.queuedEvents) > 0 && len(state.consensusEvents) < int(obs.medianCap) { event := state.queuedEvents.popLimited(obs.medianCapPerWF, obs.medianExpiration) if event == nil { break @@ -416,8 +442,8 @@ func (c *consensusQueuePlugin) StateTransition( //TODO opt: drop more than one each time? } - // prune queuedEvents if that value, blob handles, or the overall size is too large - if len(*state.queuedEvents) > 0 && + // prune (newly) queuedEvents if that value, blob handles, or the overall size is too large + if len(queuedTriggerEventIDs) > 0 && (state.sizeOfQueuedEvents() > maxKeyValueValueBytes || state.sizeOfBlobHandles() > maxKeyValueValueBytes || state.sizeOf() > maxKeyValueModifiedKeysPlusValuesBytes) { @@ -426,8 +452,8 @@ func (c *consensusQueuePlugin) StateTransition( for _, id := range queuedTriggerEventIDs { queuedTriggerEventIDSet[id] = struct{}{} } - eligibleEvents := make([]*pb.ConsensusQueueEvent, 0, len(*state.queuedEvents)) - for _, e := range *state.queuedEvents { + eligibleEvents := make([]*pb.ConsensusQueueEvent, 0, len(state.queuedEvents)) + for _, e := range state.queuedEvents { if _, ok := queuedTriggerEventIDSet[e.TriggerEventID]; ok { eligibleEvents = append(eligibleEvents, e) } @@ -442,11 +468,11 @@ func (c *consensusQueuePlugin) StateTransition( state.sizeOf() > maxKeyValueModifiedKeysPlusValuesBytes) { toRemove := heap.Pop(backwardsQueuedEvents).(*pb.ConsensusQueueEvent) //TODO opt: faster delete...but need to maintain state.queuedEvents (though not order)...map indices? - *state.queuedEvents = slices.DeleteFunc(*state.queuedEvents, func(e *pb.ConsensusQueueEvent) bool { return e.TriggerEventID == toRemove.TriggerEventID }) + state.queuedEvents = slices.DeleteFunc(state.queuedEvents, func(e *pb.ConsensusQueueEvent) bool { return e.TriggerEventID == toRemove.TriggerEventID }) //TODO opt: drop more than one each time? } // rebuild the priority queue - heap.Init(state.queuedEvents) + heap.Init(&state.queuedEvents) } // note: no need to prune consensus events, since already limited what we collected @@ -455,7 +481,6 @@ func (c *consensusQueuePlugin) StateTransition( if err != nil { return nil, err } - c.triggerQueue.Remove(ctx, queuedTriggerEventIDs) //TODO move to committed - do we need to write it through KV? or can we Remove the whole PQ every time? // no report to return, executions start when committed return nil, nil @@ -537,24 +562,51 @@ func (res *observations) addEvent(obs commontypes.OracleID, event *pb.ConsensusQ } func (c *consensusQueuePlugin) Committed(ctx context.Context, _ uint64, kvReader ocr3_1types.KeyValueStateReader) error { - c.tryStartExecutions(kvReader) - return nil + _, err := c.commitState(ctx, kvReader) + return err } -// 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(kvReader ocr3_1types.KeyValueStateReader) { +// commitState executes the consensus events, and remove events from the trigger queue that have been queued or executed. +func (c *consensusQueuePlugin) commitState(ctx context.Context, kvReader ocr3_1types.KeyValueStateReader) ([]*pb.ConsensusQueueEvent, error) { consensusEvents, blobHandles, err := readConsensusState(kvReader) if err != nil { - c.lggr.Errorw("Failed to read consensus state. Unable to execute events", "err", err) - return + 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.TriggerEventID) { + 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.TriggerEventID) { + 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) - c.eng.Go(func(ctx context.Context) { + c.eng.GoCtx(ctx, func(ctx context.Context) { defer wg.Done() if err2 := c.tryStartExecution(ctx, &fetcher, consensusEvent, blobHandles); err2 != nil { @@ -563,7 +615,9 @@ func (c *consensusQueuePlugin) tryStartExecutions(kvReader ocr3_1types.KeyValueS } }) } + wg.Wait() + return } func (c *consensusQueuePlugin) tryStartExecution(ctx context.Context, fetcher *blobCache, consensusEvent *pb.ConsensusQueueEvent, blobHandles [][]byte) error { diff --git a/core/services/ocr3_1/plugins/queue/queue_test.go b/core/services/ocr3_1/plugins/queue/queue_test.go index 9ce9228d4fa..ec7729bc56f 100644 --- a/core/services/ocr3_1/plugins/queue/queue_test.go +++ b/core/services/ocr3_1/plugins/queue/queue_test.go @@ -96,4 +96,4 @@ func (n noopQueue) Sorted() iter.Seq[triggers.CoordinatedEvent] { return func(yield func(triggers.CoordinatedEvent) bool) {} } -func (n noopQueue) Remove(ctx context.Context, triggerEventIDs []string) {} +func (n noopQueue) Remove(ctx context.Context, triggerEventIDs iter.Seq[string]) {} diff --git a/core/services/workflows/v2/triggers/queue.go b/core/services/workflows/v2/triggers/queue.go index 35643d60577..552f37b3a14 100644 --- a/core/services/workflows/v2/triggers/queue.go +++ b/core/services/workflows/v2/triggers/queue.go @@ -38,7 +38,7 @@ type Queue interface { Sorted() iter.Seq[CoordinatedEvent] // Remove removes events from the queue. - Remove(ctx context.Context, triggerEventIDs []string) + Remove(ctx context.Context, triggerEventIDs iter.Seq[string]) } // Stats is a point-in-time view of a Queue. @@ -123,9 +123,9 @@ func (q *CentralQueue) Drain(ctx context.Context) ([]CoordinatedEvent, error) { return events, nil } -func (q *CentralQueue) Remove(ctx context.Context, triggerEventIDs []string) { +func (q *CentralQueue) Remove(ctx context.Context, triggerEventIDs iter.Seq[string]) { triggerEventIDSet := map[string]struct{}{} - for _, triggerEventID := range triggerEventIDs { + for triggerEventID := range triggerEventIDs { triggerEventIDSet[triggerEventID] = struct{}{} } @@ -191,6 +191,9 @@ func (c *coordinatedEventHeap) Push(x any) { } func (c *coordinatedEventHeap) Pop() any { + if c.Len() == 0 { + return nil + } e := (*c)[len(*c)-1] *c = (*c)[:len(*c)-1] return e From 8111c5938648839ca28905eb0bdc05d1c93935fd Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Fri, 20 Nov 2026 12:12:49 -0600 Subject: [PATCH 15/38] fixes; swap out trigger event ID for execution ID --- core/scripts/go.mod | 2 +- core/scripts/go.sum | 4 +- core/services/ocr3_1/plugins/queue/config.go | 2 +- core/services/ocr3_1/plugins/queue/kvstate.go | 35 +++-- core/services/ocr3_1/plugins/queue/queue.go | 132 +++++++++--------- .../ocr3_1/plugins/queue/queue_test.go | 4 +- .../v2/triggers/coordinator_shadow_test.go | 6 +- .../workflows/v2/triggers/drainer_test.go | 31 ++-- core/services/workflows/v2/triggers/queue.go | 72 +++------- .../workflows/v2/triggers/triggers.go | 13 +- deployment/go.mod | 2 +- deployment/go.sum | 4 +- go.mod | 2 +- go.sum | 4 +- integration-tests/go.mod | 2 +- integration-tests/go.sum | 4 +- integration-tests/load/go.mod | 2 +- integration-tests/load/go.sum | 4 +- system-tests/lib/go.mod | 2 +- system-tests/lib/go.sum | 4 +- system-tests/tests/go.mod | 2 +- system-tests/tests/go.sum | 4 +- 22 files changed, 147 insertions(+), 190 deletions(-) diff --git a/core/scripts/go.mod b/core/scripts/go.mod index c394aed57b8..7732a6d12c9 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.20261118150912-05caa74bd087 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b 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.20261112211734-e640e1c12078 diff --git a/core/scripts/go.sum b/core/scripts/go.sum index a6f2331b734..0bbf9098e56 100644 --- a/core/scripts/go.sum +++ b/core/scripts/go.sum @@ -1686,8 +1686,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.20261118150912-05caa74bd087 h1:QQpXxddXoJi7b200xLaTI8yO8iKOukebi8WctQotQmY= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b h1:XHlQnqb1I6fMHkwvCXMqKnWdLGLHRElhSrXLSMVwuv8= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/core/services/ocr3_1/plugins/queue/config.go b/core/services/ocr3_1/plugins/queue/config.go index 3e2d7501cfb..32269111a18 100644 --- a/core/services/ocr3_1/plugins/queue/config.go +++ b/core/services/ocr3_1/plugins/queue/config.go @@ -10,7 +10,7 @@ const ( //TODO reduce these? connect to cre settings? maxObservationBytes = ocr3_1types.MaxMaxObservationBytes - maxKeyValueValueBytes = ocr3_1types.MaxMaxKeyValueKeyBytes + maxKeyValueValueBytes = ocr3_1types.MaxMaxKeyValueValueBytes maxKeyValueModifiedKeysPlusValuesBytes = ocr3_1types.MaxMaxKeyValueModifiedKeysPlusValuesBytes maxBlobPayloadBytes = ocr3_1types.MaxMaxBlobPayloadBytes ) diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index 9a1fa0585db..718477ddecc 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -78,12 +78,12 @@ func (p *priorityQueue) push(x *pb.ConsensusQueueEvent) { heap.Push(p, x) } func (p *priorityQueue) pushObservations(timelessHash string, obs *pb.ConsensusQueueObservedEvent) *pb.ConsensusQueueEvent { event := &pb.ConsensusQueueEvent{ - WorkflowID: obs.WorkflowID, - TriggerEventID: obs.TriggerEventID, - ObservedAt: medianTimestamp(obs.ObservedAts), - Deadline: medianTimestamp(obs.Deadlines), - TimelessHash: []byte(timelessHash), - Blobs: obs.Blobs, + WorkflowID: obs.WorkflowID, + ExecutionID: obs.ExecutionID, + ObservedAt: medianTimestamp(obs.ObservedAts), + Deadline: medianTimestamp(obs.Deadlines), + TimelessHash: []byte(timelessHash), + Blobs: obs.Blobs, } p.push(event) return event @@ -276,9 +276,8 @@ func (s *kvState) prepareWriteObservedEvents() { // 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] - //TODO can we use deadline here? is median valid & best option? - return cmp.Or(cmp.Compare(len(ea.NodeIds), len(eb.NodeIds)), - cmp.Compare(ea.TriggerEventID, eb.TriggerEventID)) + //TODO can we use deadline here? is median valid & best option? (only have f+1) + return cmp.Or(cmp.Compare(len(ea.NodeIds), len(eb.NodeIds)), cmp.Compare(ea.ExecutionID, eb.ExecutionID)) }) { event := s.observedEvents[eventHash] event.Blobs = nil // replace all @@ -366,18 +365,16 @@ func (s *kvState) pruneExpiredObservations(expiration time.Time) { } // some expired, so prune them - var toDelete []int - for i, d := range v.Deadlines { - if !unexpiredFn(d) { - toDelete = append(toDelete, i) + for i := 0; i < len(v.Deadlines); { + if !unexpiredFn(v.Deadlines[i]) { + v.NodeIds = slices.Delete(v.NodeIds, i, i+1) + v.ObservedAts = slices.Delete(v.ObservedAts, i, i+1) + v.Deadlines = slices.Delete(v.Deadlines, i, i+1) + v.Blobs = slices.Delete(v.Blobs, i, i+1) + } else { + i++ } } - for _, i := range toDelete { - v.NodeIds = slices.Delete(v.NodeIds, i, i+1) - v.ObservedAts = slices.Delete(v.ObservedAts, i, i+1) - v.Deadlines = slices.Delete(v.Deadlines, i, i+1) - v.Blobs = slices.Delete(v.Blobs, i, i+1) - } return false }) diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index 636a3e69a51..15b68b848c0 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -13,7 +13,6 @@ import ( "crypto/sha256" "errors" "fmt" - "iter" "math" "slices" "sync" @@ -34,6 +33,7 @@ import ( "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/workflows/v2/triggers" ) @@ -169,15 +169,14 @@ func (c *consensusQueuePlugin) Observation( protoOpts := proto.MarshalOptions{Deterministic: true} // Assemble an observation up to maxObservationBytes - var coordEvents []*pb.CoordinatedEvent - for coord := range toProtoSeq(c.triggerQueue.Sorted()) { - observedAt, deadline := coord.ObservedAt, coord.Deadline - coord.ObservedAt, coord.Deadline = nil, nil // for consistent hashing - protoBytes, err2 := protoOpts.Marshal(coord) // TODO opt: avoid remarshalling + var events []*pb.CoordinatedEvent + for _, event := range c.triggerQueue.Peek(maxObservedEvents) { + pbEvent := event.ToProto() + observedAt, deadline := pbEvent.ObservedAt, pbEvent.Deadline + pbEvent.ObservedAt, pbEvent.Deadline = nil, nil // for consistent hashing + protoBytes, err2 := protoOpts.Marshal(pbEvent) // TODO opt: avoid remarshalling if err2 != nil { - c.lggr.Errorw("Failed to marshal event. Excluding from observation", "eventID", coord.Event.Event.Id, "err", err2) - //TODO remove from triggerQueue? - continue + return nil, fmt.Errorf("failed to marshal event: %w", err2) } timelessHash := sha256.Sum256(protoBytes) @@ -188,23 +187,28 @@ func (c *consensusQueuePlugin) Observation( } } + executionID, err2 := workflows.GenerateExecutionIDWithTriggerIndex(event.WorkflowID, event.Event.Event.ID, event.TriggerIndex) + if err2 != nil { + return nil, fmt.Errorf("failed to generate execution ID: %w", err2) + } + obs.Events = append(obs.Events, &pb.ConsensusQueueEvent{ - WorkflowID: coord.WorkflowID, - TriggerEventID: coord.Event.Event.Id, - ObservedAt: observedAt, - Deadline: deadline, - TimelessHash: timelessHash[:], + WorkflowID: pbEvent.WorkflowID, + ExecutionID: executionID, + ObservedAt: observedAt, + Deadline: deadline, + TimelessHash: timelessHash[:], Blobs: []*pb.CoordinatedEventBlobHandle{{ Blob: 0, - Element: uint32(len(coordEvents)), + Element: uint32(len(events)), }}, }) - coordEvents = append(coordEvents, coord) + events = append(events, pbEvent) var addedCap bool - if _, ok := obs.WorkflowCapacities[coord.WorkflowID]; !ok { + if _, ok := obs.WorkflowCapacities[pbEvent.WorkflowID]; !ok { addedCap = true - obs.WorkflowCapacities[coord.WorkflowID] = uint32(min(capacity.PerWorkflow[coord.WorkflowID], math.MaxUint32)) + obs.WorkflowCapacities[pbEvent.WorkflowID] = uint32(min(capacity.PerWorkflow[pbEvent.WorkflowID], math.MaxUint32)) } // Check size @@ -212,15 +216,15 @@ func (c *consensusQueuePlugin) Observation( // too large, remove this one obs.Events = obs.Events[:len(obs.Events)-1] if addedCap { - delete(obs.WorkflowCapacities, coord.WorkflowID) + delete(obs.WorkflowCapacities, pbEvent.WorkflowID) } break } } obs.BlobHandles = nil // remove the placeholders - if len(coordEvents) > 0 { - blobHandle, n, err2 := broadcastAsBlob(ctx, blobBroadcaster, coordEvents, seqNr, c.onchainCfg.EstimatedRoundInterval) + if len(events) > 0 { + blobHandle, n, err2 := broadcastAsBlob(ctx, blobBroadcaster, events, seqNr, c.onchainCfg.EstimatedRoundInterval) if err2 != nil { return nil, err2 } @@ -229,10 +233,10 @@ func (c *consensusQueuePlugin) Observation( // we verified space for up to maxObservedBlobHandles blobs var offset int - for batch := 1; batch < maxObservedBlobHandles && n < len(coordEvents); batch++ { + for batch := 1; batch < maxObservedBlobHandles && n < len(events); batch++ { offset += n - coordEvents = coordEvents[n:] - blobHandle, n, err2 = broadcastAsBlob(ctx, blobBroadcaster, coordEvents, seqNr, c.onchainCfg.EstimatedRoundInterval) + events = events[n:] + blobHandle, n, err2 = broadcastAsBlob(ctx, blobBroadcaster, events, seqNr, c.onchainCfg.EstimatedRoundInterval) if err2 != nil { return nil, err2 } @@ -247,16 +251,6 @@ func (c *consensusQueuePlugin) Observation( return protoOpts.Marshal(obs) } -func toProtoSeq(in iter.Seq[triggers.CoordinatedEvent]) iter.Seq[*pb.CoordinatedEvent] { - return func(yield func(*pb.CoordinatedEvent) bool) { - for event := range in { - if !yield(event.ToProto()) { - return - } - } - } -} - func (c *consensusQueuePlugin) ValidateObservation( ctx context.Context, _ uint64, _ ocrtypes.AttributedQuery, ao ocrtypes.AttributedObservation, _ ocr3_1types.KeyValueStateReader, blobFetcher ocr3_1types.BlobFetcher, @@ -293,13 +287,13 @@ func (c *consensusQueuePlugin) ValidateObservation( //TODO ensure capacity map is only observations and KV observed & queued events - // ensure no duplicated trigger event ID or timelessHash - triggerEventIDs, timelessHashes := make(map[string]struct{}), make(map[string]struct{}) + // ensure no duplicate execution ID or timelessHash + execIDs, timelessHashes := make(map[string]struct{}), make(map[string]struct{}) for _, event := range obs.Events { - if _, ok := triggerEventIDs[event.TriggerEventID]; ok { - return fmt.Errorf("duplicate trigger event ID: %s", event.TriggerEventID) + if _, ok := execIDs[event.ExecutionID]; ok { + return fmt.Errorf("duplicate workflow execution ID: %s", event.ExecutionID) } - triggerEventIDs[event.TriggerEventID] = struct{}{} + execIDs[event.ExecutionID] = struct{}{} timelessHash := string(event.TimelessHash) if _, ok := timelessHashes[timelessHash]; ok { @@ -320,8 +314,8 @@ func validateObservedEvent(ctx context.Context, fetcher *blobCache, event *pb.Co if event.WorkflowID == "" { return errors.New("event workflow id is missing") } ///TODO check not too long - exact length? - if event.TriggerEventID == "" { - return errors.New("event trigger event id is missing") + if event.ExecutionID == "" { + return errors.New("event execution id is missing") } ///TODO check not too long - exact length? if event.ObservedAt == nil { return errors.New("event observation ts is missing") @@ -349,13 +343,19 @@ func validateObservedEvent(ctx context.Context, fetcher *blobCache, event *pb.Co 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 fmt.Errorf("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) } - if coordEvent.GetEvent().GetEvent().Id != event.TriggerEventID { - return fmt.Errorf("blob event ID %s does not match event trigger event ID %s", coordEvent.GetEvent().GetEvent().Id, event.TriggerEventID) + executionID, err := workflows.GenerateExecutionIDWithTriggerIndex(event.WorkflowID, coordEvent.GetEvent().GetEvent().Id, 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 { @@ -413,9 +413,9 @@ func (c *consensusQueuePlugin) StateTransition( // update state state.pruneExpiredObservations(obs.medianExpiration) - var queuedTriggerEventIDs []string // to be removed from the trigger.Queue + var queuedTimelessHashes []string // eligible for pruning later if necessary state.addObservedEvents(c.onchainCfg.F, obs.newObservedEvents, obs.observedBlobs, func(event *pb.ConsensusQueueEvent) { - queuedTriggerEventIDs = append(queuedTriggerEventIDs, event.TriggerEventID) + queuedTimelessHashes = append(queuedTimelessHashes, string(event.TimelessHash)) }) // pop as many queuedEvents as possible in to consensusEvents (up to capacity or KV limits) for len(state.queuedEvents) > 0 && len(state.consensusEvents) < int(obs.medianCap) { @@ -427,6 +427,7 @@ func (c *consensusQueuePlugin) StateTransition( // stop when either value or the overall size is too large if events, blobs := state.sizeOfConsensusEvents(), state.sizeOfBlobHandles(); events > maxKeyValueValueBytes || blobs > maxKeyValueValueBytes || events+blobs > maxKeyValueModifiedKeysPlusValuesBytes/2 { + state.queuedEvents.push(event) state.consensusEvents = state.consensusEvents[:len(state.consensusEvents)-1] break } @@ -438,23 +439,23 @@ func (c *consensusQueuePlugin) StateTransition( state.sizeOf() > maxKeyValueModifiedKeysPlusValuesBytes) { // sorted by decreasing priority, so prune the last toRemove := state.observedEventEntries[len(state.observedEventEntries)-1] - delete(state.observedEvents, toRemove.Event.TriggerEventID) + delete(state.observedEvents, string(toRemove.TimelessHash)) //TODO opt: drop more than one each time? } // prune (newly) queuedEvents if that value, blob handles, or the overall size is too large - if len(queuedTriggerEventIDs) > 0 && + if len(queuedTimelessHashes) > 0 && (state.sizeOfQueuedEvents() > maxKeyValueValueBytes || state.sizeOfBlobHandles() > maxKeyValueValueBytes || state.sizeOf() > maxKeyValueModifiedKeysPlusValuesBytes) { // prune lowest priority queuedEvents from newly added queuedTriggerEventIDs - queuedTriggerEventIDSet := map[string]struct{}{} - for _, id := range queuedTriggerEventIDs { - queuedTriggerEventIDSet[id] = struct{}{} + queuedTimelessHashSet := map[string]struct{}{} + for _, id := range queuedTimelessHashes { + queuedTimelessHashSet[id] = struct{}{} } eligibleEvents := make([]*pb.ConsensusQueueEvent, 0, len(state.queuedEvents)) for _, e := range state.queuedEvents { - if _, ok := queuedTriggerEventIDSet[e.TriggerEventID]; ok { + if _, ok := queuedTimelessHashSet[string(e.TimelessHash)]; ok { eligibleEvents = append(eligibleEvents, e) } } @@ -468,7 +469,7 @@ func (c *consensusQueuePlugin) StateTransition( state.sizeOf() > maxKeyValueModifiedKeysPlusValuesBytes) { toRemove := heap.Pop(backwardsQueuedEvents).(*pb.ConsensusQueueEvent) //TODO opt: faster delete...but need to maintain state.queuedEvents (though not order)...map indices? - state.queuedEvents = slices.DeleteFunc(state.queuedEvents, func(e *pb.ConsensusQueueEvent) bool { return e.TriggerEventID == toRemove.TriggerEventID }) + state.queuedEvents = slices.DeleteFunc(state.queuedEvents, func(event *pb.ConsensusQueueEvent) bool { return event == toRemove }) //TODO opt: drop more than one each time? } // rebuild the priority queue @@ -526,14 +527,10 @@ func (res *observations) aggregate(ctx context.Context, f int, aos []ocrtypes.At // 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. - var medianCount int res.medianCap = slices.Sorted(slices.Values(capacities))[f] for wf, caps := range wfCapacities { - if len(caps) > 2*f+1 { + if len(caps) >= 2*f+1 { res.medianCapPerWF[wf] = slices.Sorted(slices.Values(caps))[f] - if medianCount < 2*f+1 { - res.medianCapPerWF[wf] = (res.medianCapPerWF[wf] * 9) / 10 - } } } return @@ -545,12 +542,12 @@ func (res *observations) addEvent(obs commontypes.OracleID, event *pb.ConsensusQ aggregated, ok := res.newObservedEvents[string(event.TimelessHash)] if !ok { res.newObservedEvents[string(event.TimelessHash)] = &pb.ConsensusQueueObservedEvent{ - TriggerEventID: event.TriggerEventID, - WorkflowID: event.WorkflowID, - NodeIds: []uint8{uint8(obs)}, - ObservedAts: []*timestamppb.Timestamp{event.ObservedAt}, - Deadlines: []*timestamppb.Timestamp{event.Deadline}, - Blobs: nil, // res.observedBlobs tracks these while in memory + 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 @@ -579,7 +576,7 @@ func (c *consensusQueuePlugin) commitState(ctx context.Context, kvReader ocr3_1t c.triggerQueue.Remove(ctx, func(yield func(string) bool) { for _, e := range consensusEvents { - if !yield(e.TriggerEventID) { + if !yield(e.ExecutionID) { break } } @@ -590,7 +587,7 @@ func (c *consensusQueuePlugin) commitState(ctx context.Context, kvReader ocr3_1t } c.triggerQueue.Remove(ctx, func(yield func(string) bool) { for _, e := range queuedEvents { - if !yield(e.TriggerEventID) { + if !yield(e.ExecutionID) { break } } @@ -610,7 +607,7 @@ func (c *consensusQueuePlugin) tryStartExecutions(ctx context.Context, done chan defer wg.Done() if err2 := c.tryStartExecution(ctx, &fetcher, consensusEvent, blobHandles); err2 != nil { - c.lggr.Errorw("Failed to execute event", "eventID", consensusEvent.TriggerEventID, "err", err2) + c.lggr.Errorw("Failed to execute event", "executionID", consensusEvent.ExecutionID, "err", err2) return } }) @@ -626,7 +623,7 @@ func (c *consensusQueuePlugin) tryStartExecution(ctx context.Context, fetcher *b var errs []error for _, blob := range consensusEvent.Blobs { var err error - if int(blob.Blob) > len(blobHandles) { + if int(blob.Blob) >= len(blobHandles) { c.lggr.Errorw("Blob handle index out of bounds", "index", int(blob.Blob), "len", len(blobHandles)) continue } @@ -651,6 +648,7 @@ func (c *consensusQueuePlugin) tryStartExecution(ctx context.Context, fetcher *b return fmt.Errorf("failed to convert CoordinatedEvent from proto: %w", err) } + //TODO ensure this only *starts* the execution, and does not block while it runs return c.triggerCoordinator.StartExecution(ctx, event) } diff --git a/core/services/ocr3_1/plugins/queue/queue_test.go b/core/services/ocr3_1/plugins/queue/queue_test.go index ec7729bc56f..88be248cc8a 100644 --- a/core/services/ocr3_1/plugins/queue/queue_test.go +++ b/core/services/ocr3_1/plugins/queue/queue_test.go @@ -92,8 +92,6 @@ func (n noopQueue) Stats(ctx context.Context) (triggers.Stats, error) { return triggers.Stats{}, nil } -func (n noopQueue) Sorted() iter.Seq[triggers.CoordinatedEvent] { - return func(yield func(triggers.CoordinatedEvent) bool) {} -} +func (n noopQueue) Peek(int) []triggers.CoordinatedEvent { return nil } func (n noopQueue) Remove(ctx context.Context, triggerEventIDs iter.Seq[string]) {} diff --git a/core/services/workflows/v2/triggers/coordinator_shadow_test.go b/core/services/workflows/v2/triggers/coordinator_shadow_test.go index 960ec5e8e73..56d675774aa 100644 --- a/core/services/workflows/v2/triggers/coordinator_shadow_test.go +++ b/core/services/workflows/v2/triggers/coordinator_shadow_test.go @@ -334,11 +334,9 @@ type failingQueue struct { puts atomic.Int32 } -func (q *failingQueue) Sorted() iter.Seq[CoordinatedEvent] { - return func(yield func(CoordinatedEvent) bool) {} -} +func (q *failingQueue) Peek(int) []CoordinatedEvent { return nil } -func (q *failingQueue) Remove(ctx context.Context, triggerEventIDs []string) {} +func (q *failingQueue) Remove(ctx context.Context, execIDs iter.Seq[string]) {} func (q *failingQueue) Put(context.Context, CoordinatedEvent) error { q.puts.Add(1) diff --git a/core/services/workflows/v2/triggers/drainer_test.go b/core/services/workflows/v2/triggers/drainer_test.go index 03c6f990094..f44dc031f38 100644 --- a/core/services/workflows/v2/triggers/drainer_test.go +++ b/core/services/workflows/v2/triggers/drainer_test.go @@ -1,9 +1,9 @@ package triggers import ( - "container/heap" "context" "errors" + "fmt" "iter" "slices" "sync" @@ -61,33 +61,26 @@ type fakeQueue struct { drainCalls int } -func (q *fakeQueue) Sorted() iter.Seq[CoordinatedEvent] { +func (q *fakeQueue) Peek(limit int) []CoordinatedEvent { q.mu.Lock() - events := slices.Clone(q.results[0].events) + events := slices.Clone(q.results[0].events)[:min(limit, len(q.results[0].events))] q.mu.Unlock() - - eventHeap := new(coordinatedEventHeap(events)) - heap.Init(eventHeap) - return func(yield func(CoordinatedEvent) bool) { - for eventHeap.Len() > 0 { - e := heap.Pop(eventHeap).(CoordinatedEvent) - if !yield(e) { - return - } - } - } + return events } -func (q *fakeQueue) Remove(ctx context.Context, triggerEventIDs []string) { - triggerEventIDSet := map[string]struct{}{} - for _, triggerEventID := range triggerEventIDs { - triggerEventIDSet[triggerEventID] = struct{}{} +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 CoordinatedEvent) bool { - _, ok := triggerEventIDSet[e.Event.Event.ID] + if err := e.cacheExecutionID(); err != nil { + panic(fmt.Errorf("unable to generate execution ID: %w", err)) + } + _, ok := execIDSet[*e.executionID] return ok }) // note: empty results remain diff --git a/core/services/workflows/v2/triggers/queue.go b/core/services/workflows/v2/triggers/queue.go index 552f37b3a14..ec7f86a178d 100644 --- a/core/services/workflows/v2/triggers/queue.go +++ b/core/services/workflows/v2/triggers/queue.go @@ -1,9 +1,9 @@ package triggers import ( - "container/heap" "context" "errors" + "fmt" "iter" "maps" "slices" @@ -33,11 +33,12 @@ type Queue interface { // Stats reports current length, capacity, and cumulative drops. Stats(context.Context) (Stats, error) - // Sorted returns an iterator over all events, ordered by deadline and then trigger event ID. - // It does not drain the queue. Events remain but can be removed via Remove. - Sorted() iter.Seq[CoordinatedEvent] + // Peek is like Drain, but does not empty the queue and only returns up to max events. + // Events remain but can be removed via Remove. + Peek(max int) []CoordinatedEvent - // Remove removes events from the queue. + // Remove removes events from the queue by execution ID. + //TODO can't ack with trigger event ID - not unique! Remove(ctx context.Context, triggerEventIDs iter.Seq[string]) } @@ -87,6 +88,10 @@ func NewQueue(limit limits.BoundLimiter[int], metrics *monitoring.CentralTrigger // Put appends e, or returns ErrQueueFull and counts the drop when the queue is at capacity. func (q *CentralQueue) Put(ctx context.Context, e CoordinatedEvent) error { + if err := e.cacheExecutionID(); err != nil { + return fmt.Errorf("failed to generate execution ID: %w", err) + } + capacity := q.capacity(ctx) q.mu.Lock() @@ -123,10 +128,10 @@ func (q *CentralQueue) Drain(ctx context.Context) ([]CoordinatedEvent, error) { return events, nil } -func (q *CentralQueue) Remove(ctx context.Context, triggerEventIDs iter.Seq[string]) { - triggerEventIDSet := map[string]struct{}{} - for triggerEventID := range triggerEventIDs { - triggerEventIDSet[triggerEventID] = struct{}{} +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) @@ -135,8 +140,9 @@ func (q *CentralQueue) Remove(ctx context.Context, triggerEventIDs iter.Seq[stri defer q.mu.Unlock() var deleted int + //TODO opt: map so we don't have to iterate over them all (just use pointer elements?) q.events = slices.DeleteFunc(q.events, func(e CoordinatedEvent) bool { - _, ok := triggerEventIDSet[e.Event.Event.ID] + _, ok := execIDSet[*e.executionID] // events are rejected if we cannot set the execution ID if ok { deleted++ q.depthByWorkflow[e.WorkflowID]-- @@ -151,52 +157,12 @@ func (q *CentralQueue) Remove(ctx context.Context, triggerEventIDs iter.Seq[stri return } -func (q *CentralQueue) Sorted() iter.Seq[CoordinatedEvent] { +func (q *CentralQueue) Peek(limit int) []CoordinatedEvent { q.mu.Lock() - events := slices.Clone(q.events) + events := slices.Clone(q.events)[:min(len(q.events), limit)] q.mu.Unlock() - eventHeap := new(coordinatedEventHeap(events)) - heap.Init(eventHeap) - - return func(yield func(CoordinatedEvent) bool) { - for eventHeap.Len() > 0 { - if !yield((*eventHeap)[0]) { - return - } - heap.Pop(eventHeap) - } - } -} - -type coordinatedEventHeap []CoordinatedEvent - -func (c *coordinatedEventHeap) Len() int { - if c == nil { - return 0 - } - return len(*c) -} - -func (c *coordinatedEventHeap) Less(i, j int) bool { - return (*c)[i].CompareDeadline(&(*c)[j]) < 0 -} - -func (c *coordinatedEventHeap) Swap(i, j int) { - (*c)[i], (*c)[j] = (*c)[j], (*c)[i] -} - -func (c *coordinatedEventHeap) Push(x any) { - *c = append(*c, x.(CoordinatedEvent)) -} - -func (c *coordinatedEventHeap) Pop() any { - if c.Len() == 0 { - return nil - } - e := (*c)[len(*c)-1] - *c = (*c)[:len(*c)-1] - return e + return events } // Stats returns copies of the queue's maps, so callers may keep or change them. diff --git a/core/services/workflows/v2/triggers/triggers.go b/core/services/workflows/v2/triggers/triggers.go index b653de95539..30b12c61ee4 100644 --- a/core/services/workflows/v2/triggers/triggers.go +++ b/core/services/workflows/v2/triggers/triggers.go @@ -1,7 +1,6 @@ package triggers import ( - "cmp" "context" "errors" "fmt" @@ -21,6 +20,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/contexts" "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/settings/limits" + "github.com/smartcontractkit/chainlink-common/pkg/workflows" sdkpb "github.com/smartcontractkit/chainlink-protos/cre/go/sdk" "github.com/smartcontractkit/chainlink/v2/core/capabilities/validation" "github.com/smartcontractkit/chainlink/v2/core/platform" @@ -184,10 +184,17 @@ type CoordinatedEvent struct { Deadline time.Time Event capabilities.TriggerResponse + + executionID *string // cached } -func (e *CoordinatedEvent) CompareDeadline(o *CoordinatedEvent) int { - return cmp.Or(e.Deadline.Compare(o.Deadline), cmp.Compare(e.Event.Event.ID, o.Event.Event.ID)) +func (e *CoordinatedEvent) cacheExecutionID() error { + executionID, err := workflows.GenerateExecutionIDWithTriggerIndex(e.WorkflowID, e.Event.Event.ID, e.TriggerIndex) + if err != nil { + return fmt.Errorf("failed to generate execution ID: %w", err) + } + e.executionID = &executionID + return nil } func (e *CoordinatedEvent) ToProto() *pb.CoordinatedEvent { diff --git a/deployment/go.mod b/deployment/go.mod index 52fcdcb2041..11ac9a4ce1f 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.20261118150912-05caa74bd087 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b 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 52da3f4f005..e3c0e6efb2d 100644 --- a/deployment/go.sum +++ b/deployment/go.sum @@ -1411,8 +1411,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.20261118150912-05caa74bd087 h1:QQpXxddXoJi7b200xLaTI8yO8iKOukebi8WctQotQmY= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b h1:XHlQnqb1I6fMHkwvCXMqKnWdLGLHRElhSrXLSMVwuv8= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/go.mod b/go.mod index f8de929717a..dfd92a5310a 100644 --- a/go.mod +++ b/go.mod @@ -82,7 +82,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.20261118150912-05caa74bd087 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 github.com/smartcontractkit/chainlink-data-streams v1.1.3 diff --git a/go.sum b/go.sum index e5ba383d77a..b4f4d6593fb 100644 --- a/go.sum +++ b/go.sum @@ -1102,8 +1102,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.20261118150912-05caa74bd087 h1:QQpXxddXoJi7b200xLaTI8yO8iKOukebi8WctQotQmY= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b h1:XHlQnqb1I6fMHkwvCXMqKnWdLGLHRElhSrXLSMVwuv8= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/integration-tests/go.mod b/integration-tests/go.mod index 404dddb6f4b..26fd800c8ba 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.20261118150912-05caa74bd087 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b 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.20261112211734-e640e1c12078 diff --git a/integration-tests/go.sum b/integration-tests/go.sum index fb9330cb328..d9efcdd5660 100644 --- a/integration-tests/go.sum +++ b/integration-tests/go.sum @@ -1396,8 +1396,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.20261118150912-05caa74bd087 h1:QQpXxddXoJi7b200xLaTI8yO8iKOukebi8WctQotQmY= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b h1:XHlQnqb1I6fMHkwvCXMqKnWdLGLHRElhSrXLSMVwuv8= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/integration-tests/load/go.mod b/integration-tests/load/go.mod index e6c25a18c78..7078e160fec 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.20261118150912-05caa74bd087 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261112211734-e640e1c12078 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 591c6c77cb0..4c4c2ff414b 100644 --- a/integration-tests/load/go.sum +++ b/integration-tests/load/go.sum @@ -1636,8 +1636,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.20261118150912-05caa74bd087 h1:QQpXxddXoJi7b200xLaTI8yO8iKOukebi8WctQotQmY= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b h1:XHlQnqb1I6fMHkwvCXMqKnWdLGLHRElhSrXLSMVwuv8= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/system-tests/lib/go.mod b/system-tests/lib/go.mod index 2ab485d707f..563c94112a0 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.20261118150912-05caa74bd087 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b 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 bd08182f238..e74b479171e 100644 --- a/system-tests/lib/go.sum +++ b/system-tests/lib/go.sum @@ -1657,8 +1657,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.20261118150912-05caa74bd087 h1:QQpXxddXoJi7b200xLaTI8yO8iKOukebi8WctQotQmY= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b h1:XHlQnqb1I6fMHkwvCXMqKnWdLGLHRElhSrXLSMVwuv8= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/system-tests/tests/go.mod b/system-tests/tests/go.mod index f4cbd125a58..d9dcdea3333 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.20261118150912-05caa74bd087 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 github.com/smartcontractkit/chainlink-confidential-compute v1.3.0 diff --git a/system-tests/tests/go.sum b/system-tests/tests/go.sum index 4616835de7d..f86e29e5b8a 100644 --- a/system-tests/tests/go.sum +++ b/system-tests/tests/go.sum @@ -1836,8 +1836,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.20261118150912-05caa74bd087 h1:QQpXxddXoJi7b200xLaTI8yO8iKOukebi8WctQotQmY= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261118150912-05caa74bd087/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b h1:XHlQnqb1I6fMHkwvCXMqKnWdLGLHRElhSrXLSMVwuv8= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= From 668e74b12da15b758fda62e1e080959e6034e6fb Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Fri, 20 Nov 2026 12:43:04 -0600 Subject: [PATCH 16/38] fixes --- core/services/ocr3_1/plugins/queue/kvstate.go | 4 +- core/services/ocr3_1/plugins/queue/queue.go | 15 ++--- .../v2/triggers/coordinator_shadow_test.go | 4 +- .../workflows/v2/triggers/queue_test.go | 58 ++++++++++--------- 4 files changed, 42 insertions(+), 39 deletions(-) diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index 718477ddecc..e18cf46cfe7 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -277,7 +277,7 @@ func (s *kvState) prepareWriteObservedEvents() { for _, eventHash := range slices.SortedFunc(maps.Keys(s.observedEvents), func(a string, b string) int { ea, eb := s.observedEvents[a], s.observedEvents[b] //TODO can we use deadline here? is median valid & best option? (only have f+1) - return cmp.Or(cmp.Compare(len(ea.NodeIds), len(eb.NodeIds)), cmp.Compare(ea.ExecutionID, eb.ExecutionID)) + return cmp.Or(cmp.Compare(len(eb.NodeIds), len(ea.NodeIds)), cmp.Compare(eb.ExecutionID, ea.ExecutionID)) }) { event := s.observedEvents[eventHash] event.Blobs = nil // replace all @@ -358,7 +358,7 @@ func (s *kvState) writeTo(w *stateWriter) error { } func (s *kvState) pruneExpiredObservations(expiration time.Time) { - unexpiredFn := func(t *timestamppb.Timestamp) bool { return t.AsTime().After(expiration) } + unexpiredFn := func(t *timestamppb.Timestamp) bool { return t.AsTime().Before(expiration) } maps.DeleteFunc(s.observedEvents, func(k string, v *pb.ConsensusQueueObservedEvent) bool { if !slices.ContainsFunc(v.Deadlines, unexpiredFn) { return false // no unexpired deadlines, so delete the whole thing diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index 15b68b848c0..dc2e0de244e 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -232,19 +232,20 @@ func (c *consensusQueuePlugin) Observation( // note: elements already reference blob 0 and natural element index is aligned // we verified space for up to maxObservedBlobHandles blobs - var offset int - for batch := 1; batch < maxObservedBlobHandles && n < len(events); batch++ { - offset += n - events = events[n:] + lastEnd := n + events = events[n:] + for batch := 1; batch < maxObservedBlobHandles && len(events) > 0; batch++ { blobHandle, n, err2 = broadcastAsBlob(ctx, blobBroadcaster, events, seqNr, c.onchainCfg.EstimatedRoundInterval) if err2 != nil { return nil, err2 } obs.BlobHandles = append(obs.BlobHandles, blobHandle) - for i := offset; i < n; i++ { // update indices - obs.Events[offset+i].Blobs[0].Blob = uint32(batch) - obs.Events[offset+i].Blobs[0].Element = uint32(i) + for i := lastEnd; i < n; i++ { // update indices + obs.Events[lastEnd+i].Blobs[0].Blob = uint32(batch) + obs.Events[lastEnd+i].Blobs[0].Element = uint32(i) } + lastEnd += n + events = events[n:] } } diff --git a/core/services/workflows/v2/triggers/coordinator_shadow_test.go b/core/services/workflows/v2/triggers/coordinator_shadow_test.go index 56d675774aa..567a40774ce 100644 --- a/core/services/workflows/v2/triggers/coordinator_shadow_test.go +++ b/core/services/workflows/v2/triggers/coordinator_shadow_test.go @@ -454,7 +454,7 @@ func TestCoordinator_DrainerLifecycle(t *testing.T) { require.NoError(t, c.Start(t.Context())) require.NoError(t, d.Ready(), "the drainer must run once the coordinator starts") - putAll(t, q, centralEvent("wf-a", 0, "evt-1")) + putAll(t, q, centralEvent(t, "wf-a", 0, "evt-1")) ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) defer cancel() require.NoError(t, clock.BlockUntilContext(ctx, 1), "the drainer is not waiting on the clock") @@ -468,7 +468,7 @@ func TestCoordinator_DrainerLifecycle(t *testing.T) { require.Error(t, d.Ready(), "the drainer must stop when the coordinator closes") // Nothing waits on the clock after close, so Advance does nothing unless the drainer goroutine leaked. - putAll(t, q, centralEvent("wf-a", 0, "evt-2")) + putAll(t, q, centralEvent(t, "wf-a", 0, "evt-2")) clock.Advance(500 * time.Millisecond) assert.Never(t, func() bool { stats, err := q.Stats(t.Context()) diff --git a/core/services/workflows/v2/triggers/queue_test.go b/core/services/workflows/v2/triggers/queue_test.go index 378696d62b8..d3055fa676f 100644 --- a/core/services/workflows/v2/triggers/queue_test.go +++ b/core/services/workflows/v2/triggers/queue_test.go @@ -68,9 +68,9 @@ 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) - return CoordinatedEvent{ +func centralEvent(t *testing.T, workflowID string, triggerIndex int, id string) CoordinatedEvent { + observed := time.Now() + e := CoordinatedEvent{ WorkflowID: workflowID, TriggerCapID: fmt.Sprintf("trigger-%d@1.0.0", triggerIndex), TriggerIndex: triggerIndex, @@ -78,6 +78,8 @@ func centralEvent(workflowID string, triggerIndex int, id string) CoordinatedEve Deadline: observed.Add(time.Minute), Event: capabilities.TriggerResponse{Event: capabilities.TriggerEvent{ID: id}}, } + require.NoError(t, e.cacheExecutionID()) + return e } func putAll(t *testing.T, q *CentralQueue, events ...CoordinatedEvent) { @@ -113,9 +115,9 @@ func TestQueue_PutDrain(t *testing.T) { q := newTestCentralQueue(t, &fakeLimit{limit: 10}) want := []CoordinatedEvent{ - centralEvent("wf-a", 0, "evt-1"), - centralEvent("wf-b", 0, "evt-2"), - centralEvent("wf-a", 1, "evt-3"), + centralEvent(t, "wf-a", 0, "evt-1"), + centralEvent(t, "wf-b", 0, "evt-2"), + centralEvent(t, "wf-a", 1, "evt-3"), } putAll(t, q, want...) @@ -123,7 +125,7 @@ func TestQueue_PutDrain(t *testing.T) { require.NoError(t, err) assert.Equal(t, want, got) - putAll(t, q, centralEvent("wf-c", 0, "evt-4")) + putAll(t, q, centralEvent(t, "wf-c", 0, "evt-4")) assert.Equal(t, want, got, "a later put must not write into a drained slice") assert.Equal(t, []string{"evt-4"}, drainIDs(t, q)) @@ -139,9 +141,9 @@ func TestQueue_Capacity(t *testing.T) { t.Run("a put at the limit is rejected and not stored", func(t *testing.T) { t.Parallel() q := newTestCentralQueue(t, &fakeLimit{limit: 2}) - putAll(t, q, centralEvent("wf-a", 0, "evt-1"), centralEvent("wf-a", 0, "evt-2")) + putAll(t, q, centralEvent(t, "wf-a", 0, "evt-1"), centralEvent(t, "wf-a", 0, "evt-2")) - require.ErrorIs(t, q.Put(t.Context(), centralEvent("wf-a", 0, "evt-3")), ErrQueueFull) + require.ErrorIs(t, q.Put(t.Context(), centralEvent(t, "wf-a", 0, "evt-3")), ErrQueueFull) assert.Equal(t, []string{"evt-1", "evt-2"}, drainIDs(t, q)) }) @@ -149,10 +151,10 @@ func TestQueue_Capacity(t *testing.T) { t.Parallel() limit := &fakeLimit{limit: 3} q := newTestCentralQueue(t, limit) - putAll(t, q, centralEvent("wf-a", 0, "evt-1"), centralEvent("wf-a", 0, "evt-2"), centralEvent("wf-a", 0, "evt-3")) + putAll(t, q, centralEvent(t, "wf-a", 0, "evt-1"), centralEvent(t, "wf-a", 0, "evt-2"), centralEvent(t, "wf-a", 0, "evt-3")) limit.set(1, nil) - require.ErrorIs(t, q.Put(t.Context(), centralEvent("wf-a", 0, "evt-4")), ErrQueueFull) + require.ErrorIs(t, q.Put(t.Context(), centralEvent(t, "wf-a", 0, "evt-4")), ErrQueueFull) assert.Equal(t, []string{"evt-1", "evt-2", "evt-3"}, drainIDs(t, q)) }) @@ -160,11 +162,11 @@ func TestQueue_Capacity(t *testing.T) { t.Parallel() limit := &fakeLimit{limit: 1} q := newTestCentralQueue(t, limit) - putAll(t, q, centralEvent("wf-a", 0, "evt-1")) - require.ErrorIs(t, q.Put(t.Context(), centralEvent("wf-a", 0, "evt-2")), ErrQueueFull) + putAll(t, q, centralEvent(t, "wf-a", 0, "evt-1")) + require.ErrorIs(t, q.Put(t.Context(), centralEvent(t, "wf-a", 0, "evt-2")), ErrQueueFull) limit.set(2, nil) - putAll(t, q, centralEvent("wf-a", 0, "evt-3")) + putAll(t, q, centralEvent(t, "wf-a", 0, "evt-3")) assert.Equal(t, []string{"evt-1", "evt-3"}, drainIDs(t, q)) }) @@ -172,7 +174,7 @@ func TestQueue_Capacity(t *testing.T) { t.Parallel() // The value returned with the error is ignored. q := newTestCentralQueue(t, &fakeLimit{limit: 1, err: assert.AnError}) - putAll(t, q, centralEvent("wf-a", 0, "evt-1"), centralEvent("wf-a", 0, "evt-2")) + putAll(t, q, centralEvent(t, "wf-a", 0, "evt-1"), centralEvent(t, "wf-a", 0, "evt-2")) stats, err := q.Stats(t.Context()) require.NoError(t, err) @@ -185,11 +187,11 @@ func TestQueue_Capacity(t *testing.T) { limit := &fakeLimit{limit: defaultLimit + 5} q := newTestCentralQueue(t, limit) for i := range defaultLimit + 5 { - putAll(t, q, centralEvent("wf-a", 0, fmt.Sprintf("evt-%d", i))) + putAll(t, q, centralEvent(t, "wf-a", 0, fmt.Sprintf("evt-%d", i))) } limit.set(0, assert.AnError) - require.ErrorIs(t, q.Put(t.Context(), centralEvent("wf-a", 0, "one-more")), ErrQueueFull) + require.ErrorIs(t, q.Put(t.Context(), centralEvent(t, "wf-a", 0, "one-more")), ErrQueueFull) stats, err := q.Stats(t.Context()) require.NoError(t, err) @@ -205,9 +207,9 @@ func TestQueue_Stats(t *testing.T) { limit := &fakeLimit{limit: 3} q := newTestCentralQueue(t, limit) - putAll(t, q, centralEvent("wf-a", 0, "evt-1"), centralEvent("wf-a", 1, "evt-2"), centralEvent("wf-b", 0, "evt-3")) - require.ErrorIs(t, q.Put(t.Context(), centralEvent("wf-b", 0, "evt-4")), ErrQueueFull) - require.ErrorIs(t, q.Put(t.Context(), centralEvent("wf-a", 1, "evt-5")), ErrQueueFull) + putAll(t, q, centralEvent(t, "wf-a", 0, "evt-1"), centralEvent(t, "wf-a", 1, "evt-2"), centralEvent(t, "wf-b", 0, "evt-3")) + require.ErrorIs(t, q.Put(t.Context(), centralEvent(t, "wf-b", 0, "evt-4")), ErrQueueFull) + require.ErrorIs(t, q.Put(t.Context(), centralEvent(t, "wf-a", 1, "evt-5")), ErrQueueFull) stats, err := q.Stats(t.Context()) require.NoError(t, err) @@ -230,8 +232,8 @@ func TestQueue_Stats(t *testing.T) { drainIDs(t, q) limit.set(1, nil) - putAll(t, q, centralEvent("wf-c", 0, "evt-6")) - require.ErrorIs(t, q.Put(t.Context(), centralEvent("wf-b", 0, "evt-7")), ErrQueueFull) + putAll(t, q, centralEvent(t, "wf-c", 0, "evt-6")) + require.ErrorIs(t, q.Put(t.Context(), centralEvent(t, "wf-b", 0, "evt-7")), ErrQueueFull) stats, err = q.Stats(t.Context()) require.NoError(t, err) @@ -269,7 +271,7 @@ func TestQueue_ConcurrentPutDrain(t *testing.T) { for p := range producers { wg.Go(func() { for range perProducer { - e := centralEvent(fmt.Sprintf("wf-%d", p), 0, "evt") + e := centralEvent(t, fmt.Sprintf("wf-%d", p), 0, "evt") err := q.Put(t.Context(), e) if err == nil { accepted[p]++ @@ -336,7 +338,7 @@ func TestQueue_ConcurrentPutDrain(t *testing.T) { for _, e := range drained { prev, seen := last[e.WorkflowID] if seen { - assert.Greater(t, e.ObservedAt, 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.ObservedAt } @@ -371,11 +373,11 @@ func TestQueue_Metrics(t *testing.T) { qm, reader := testQueueMetrics(t) q := NewQueue(&fakeLimit{limit: 2}, qm, logger.Test(t)) - putAll(t, q, centralEvent("wf-a", 0, "evt-1"), centralEvent("wf-b", 0, "evt-2")) - require.ErrorIs(t, q.Put(t.Context(), centralEvent("wf-a", 0, "evt-3")), ErrQueueFull) + putAll(t, q, centralEvent(t, "wf-a", 0, "evt-1"), centralEvent(t, "wf-b", 0, "evt-2")) + require.ErrorIs(t, q.Put(t.Context(), centralEvent(t, "wf-a", 0, "evt-3")), ErrQueueFull) drainIDs(t, q) assert.Equal(t, int64(0), int64Gauge(t, reader, "platform_engine_central_trigger_queue_depth"), "after drain") - putAll(t, q, centralEvent("wf-a", 0, "evt-4")) + putAll(t, q, centralEvent(t, "wf-a", 0, "evt-4")) stats, err := q.Stats(t.Context()) require.NoError(t, err) @@ -422,7 +424,7 @@ func TestQueue_CapacityGaugeOnDrain(t *testing.T) { qm, reader := testQueueMetrics(t) limit := &fakeLimit{limit: 2} q := NewQueue(limit, qm, logger.Test(t)) - putAll(t, q, centralEvent("wf-a", 0, "evt-1")) + putAll(t, q, centralEvent(t, "wf-a", 0, "evt-1")) require.Equal(t, int64(2), int64Gauge(t, reader, "platform_engine_central_trigger_queue_capacity")) limit.set(5, nil) From 9066e97044a1665d7a0701fab7191fbed5b23075 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Fri, 20 Nov 2026 14:21:26 -0600 Subject: [PATCH 17/38] dynamic config; fixes --- core/services/ocr3_1/plugins/queue/blobs.go | 8 +++--- core/services/ocr3_1/plugins/queue/config.go | 5 +--- core/services/ocr3_1/plugins/queue/kvstate.go | 18 +++++++------ core/services/ocr3_1/plugins/queue/queue.go | 25 +++++++++++-------- .../ocr3_1/plugins/queue/queue_test.go | 4 +-- .../v2/triggers/coordinator_shadow_test.go | 4 ++- .../workflows/v2/triggers/drainer_test.go | 10 +++++--- core/services/workflows/v2/triggers/queue.go | 18 +++++++------ 8 files changed, 52 insertions(+), 40 deletions(-) diff --git a/core/services/ocr3_1/plugins/queue/blobs.go b/core/services/ocr3_1/plugins/queue/blobs.go index 1bde88bc86c..2e8302e9082 100644 --- a/core/services/ocr3_1/plugins/queue/blobs.go +++ b/core/services/ocr3_1/plugins/queue/blobs.go @@ -103,10 +103,10 @@ func extractEvent(b []byte, idx int) (*pb.CoordinatedEvent, []byte, error) { } // broadcastAsBlob broadcasts a blob with as many coordinated events as possible, returning the blob handle and count of events included. -func broadcastAsBlob(ctx context.Context, broadcaster ocr3_1types.BlobBroadcastFetcher, events []*pb.CoordinatedEvent, - seqNr uint64, estimatedRoundInterval time.Duration) (blobHandle []byte, n int, err error) { +func (c *consensusQueuePlugin) broadcastAsBlob(ctx context.Context, broadcaster ocr3_1types.BlobBroadcastFetcher, events []*pb.CoordinatedEvent, + seqNr uint64) (blobHandle []byte, n int, err error) { protoOpts := proto.MarshalOptions{Deterministic: true} - for ; protoOpts.Size(&pb.CoordinatedEventList{Events: events}) > maxBlobPayloadBytes; events = events[:len(events)-1] { + for ; protoOpts.Size(&pb.CoordinatedEventList{Events: events}) > c.limits.MaxBlobPayloadBytes; events = events[:len(events)-1] { //TODO opt: binary search for largest fit instead.... } n = len(events) @@ -116,7 +116,7 @@ func broadcastAsBlob(ctx context.Context, broadcaster ocr3_1types.BlobBroadcastF maxDeadline = t } } - roundDur := estimatedRoundInterval //TODO OK? pad? + roundDur := c.onchainCfg.EstimatedRoundInterval //TODO OK? pad? //TODO pad extra time and/or rounds? expSeqNr := seqNr + uint64(time.Until(maxDeadline)/roundDur) diff --git a/core/services/ocr3_1/plugins/queue/config.go b/core/services/ocr3_1/plugins/queue/config.go index 32269111a18..7577decc80f 100644 --- a/core/services/ocr3_1/plugins/queue/config.go +++ b/core/services/ocr3_1/plugins/queue/config.go @@ -9,10 +9,7 @@ const ( maxObservedEvents = 1000 // sanity check events in an observation //TODO reduce these? connect to cre settings? - maxObservationBytes = ocr3_1types.MaxMaxObservationBytes - maxKeyValueValueBytes = ocr3_1types.MaxMaxKeyValueValueBytes - maxKeyValueModifiedKeysPlusValuesBytes = ocr3_1types.MaxMaxKeyValueModifiedKeysPlusValuesBytes - maxBlobPayloadBytes = ocr3_1types.MaxMaxBlobPayloadBytes + maxKeyValueValueBytes = ocr3_1types.MaxMaxKeyValueValueBytes ) type PluginConfig struct { diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index e18cf46cfe7..d9d8cdf8dba 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -83,7 +83,7 @@ func (p *priorityQueue) pushObservations(timelessHash string, obs *pb.ConsensusQ ObservedAt: medianTimestamp(obs.ObservedAts), Deadline: medianTimestamp(obs.Deadlines), TimelessHash: []byte(timelessHash), - Blobs: obs.Blobs, + // note: observedBlobs tracks blobs while in memory } p.push(event) return event @@ -358,19 +358,20 @@ func (s *kvState) writeTo(w *stateWriter) error { } func (s *kvState) pruneExpiredObservations(expiration time.Time) { - unexpiredFn := func(t *timestamppb.Timestamp) bool { return t.AsTime().Before(expiration) } maps.DeleteFunc(s.observedEvents, func(k string, v *pb.ConsensusQueueObservedEvent) bool { - if !slices.ContainsFunc(v.Deadlines, unexpiredFn) { - return false // no unexpired deadlines, so delete the whole thing + if !slices.ContainsFunc(v.Deadlines, func(t *timestamppb.Timestamp) bool { + return t.AsTime().After(expiration) + }) { + return true // all deadlines expired, so delete the whole thing } // some expired, so prune them for i := 0; i < len(v.Deadlines); { - if !unexpiredFn(v.Deadlines[i]) { + if v.Deadlines[i].AsTime().Before(expiration) { v.NodeIds = slices.Delete(v.NodeIds, i, i+1) v.ObservedAts = slices.Delete(v.ObservedAts, i, i+1) v.Deadlines = slices.Delete(v.Deadlines, i, i+1) - v.Blobs = slices.Delete(v.Blobs, i, i+1) + // note: s.observedBlobs tracks blobs while in memory } else { i++ } @@ -408,13 +409,14 @@ func (s *kvState) addObservedEvents(f int, toAdd map[string]*pb.ConsensusQueueOb obsEvent.NodeIds = append(obsEvent.NodeIds, node) obsEvent.ObservedAts = append(obsEvent.ObservedAts, eventToAdd.ObservedAts[i]) obsEvent.Deadlines = append(obsEvent.Deadlines, eventToAdd.Deadlines[i]) - obsEvent.Blobs = append(obsEvent.Blobs, eventToAdd.Blobs[i]) + // note: s.observedBlobs tracks blobs while in memory } else { // overwrite previous observation obsEvent.ObservedAts[prev] = eventToAdd.ObservedAts[i] obsEvent.Deadlines[prev] = eventToAdd.Deadlines[i] - obsEvent.Blobs[prev] = eventToAdd.Blobs[i] + // note: s.observedBlobs tracks blobs while in memory } } + s.observedBlobs.addAll(eventHash, observedBlobs[eventHash]) if len(obsEvent.NodeIds) >= 2*f+1 { // promote proposal to priority queue diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index dc2e0de244e..01f60553495 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -76,7 +76,7 @@ func NewConsensusQueuePluginFactory( } func (c *consensusQueuePluginFactory) NewReportingPlugin(ctx context.Context, config ocr3types.ReportingPluginConfig, blobs ocr3_1types.BlobBroadcastFetcher) (ocr3_1types.ReportingPlugin[[]byte], ocr3_1types.ReportingPluginInfo, error) { - plugin := newConsensusQueuePlugin(c.lggr, config, c.triggerCoordinator, c.triggerQueue, c.expirationDur, blobs) + plugin := newConsensusQueuePlugin(c.lggr, config, c.cfg.Limits, c.triggerCoordinator, c.triggerQueue, c.expirationDur, blobs) pluginInfo := ocr3_1types.ReportingPluginInfo1{ Name: "ConsensusQueueReportingPlugin", Limits: c.cfg.Limits, @@ -91,6 +91,7 @@ type consensusQueuePlugin struct { eng *services.Engine lggr logger.Logger onchainCfg ocr3types.ReportingPluginConfig + limits ocr3_1types.ReportingPluginLimits blobHandleMarshalledBytesUpperBound int triggerCoordinator triggers.Coordinator triggerQueue triggers.Queue @@ -99,13 +100,14 @@ type consensusQueuePlugin struct { } func newConsensusQueuePlugin( - lggr logger.Logger, onchainCfg ocr3types.ReportingPluginConfig, triggerCoordinator triggers.Coordinator, + 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, ) *consensusQueuePlugin { c := &consensusQueuePlugin{ lggr: logger.Named(lggr, "ConsensusQueuePlugin"), onchainCfg: onchainCfg, + limits: limits, blobHandleMarshalledBytesUpperBound: ocr3_1types.BlobHandleMarshalledBytesUpperBound(onchainCfg.N, onchainCfg.F), triggerCoordinator: triggerCoordinator, triggerQueue: triggerQueue, @@ -170,7 +172,7 @@ func (c *consensusQueuePlugin) Observation( // Assemble an observation up to maxObservationBytes var events []*pb.CoordinatedEvent - for _, event := range c.triggerQueue.Peek(maxObservedEvents) { + for event := range c.triggerQueue.Peek(maxObservedEvents) { pbEvent := event.ToProto() observedAt, deadline := pbEvent.ObservedAt, pbEvent.Deadline pbEvent.ObservedAt, pbEvent.Deadline = nil, nil // for consistent hashing @@ -212,7 +214,7 @@ func (c *consensusQueuePlugin) Observation( } // Check size - if protoOpts.Size(obs) > maxObservationBytes { + if protoOpts.Size(obs) > c.limits.MaxObservationBytes { // too large, remove this one obs.Events = obs.Events[:len(obs.Events)-1] if addedCap { @@ -224,7 +226,7 @@ func (c *consensusQueuePlugin) Observation( obs.BlobHandles = nil // remove the placeholders if len(events) > 0 { - blobHandle, n, err2 := broadcastAsBlob(ctx, blobBroadcaster, events, seqNr, c.onchainCfg.EstimatedRoundInterval) + blobHandle, n, err2 := c.broadcastAsBlob(ctx, blobBroadcaster, events, seqNr) if err2 != nil { return nil, err2 } @@ -235,18 +237,19 @@ func (c *consensusQueuePlugin) Observation( lastEnd := n events = events[n:] for batch := 1; batch < maxObservedBlobHandles && len(events) > 0; batch++ { - blobHandle, n, err2 = broadcastAsBlob(ctx, blobBroadcaster, events, seqNr, c.onchainCfg.EstimatedRoundInterval) + blobHandle, n, err2 = c.broadcastAsBlob(ctx, blobBroadcaster, events, seqNr) if err2 != nil { return nil, err2 } obs.BlobHandles = append(obs.BlobHandles, blobHandle) - for i := lastEnd; i < n; i++ { // update indices + for i := 0; i < n; i++ { // update indices obs.Events[lastEnd+i].Blobs[0].Blob = uint32(batch) obs.Events[lastEnd+i].Blobs[0].Element = uint32(i) } lastEnd += n events = events[n:] } + //TODO if we hit max blobs, then drop excess events } return protoOpts.Marshal(obs) @@ -427,7 +430,7 @@ func (c *consensusQueuePlugin) StateTransition( state.consensusEvents = append(state.consensusEvents, event) // stop when either value or the overall size is too large if events, blobs := state.sizeOfConsensusEvents(), state.sizeOfBlobHandles(); events > maxKeyValueValueBytes || - blobs > maxKeyValueValueBytes || events+blobs > maxKeyValueModifiedKeysPlusValuesBytes/2 { + blobs > maxKeyValueValueBytes || events+blobs > c.limits.MaxKeyValueModifiedKeysPlusValuesBytes/2 { state.queuedEvents.push(event) state.consensusEvents = state.consensusEvents[:len(state.consensusEvents)-1] break @@ -437,7 +440,7 @@ func (c *consensusQueuePlugin) StateTransition( // prune observations if that value or the overall size is too large for len(state.observedEventEntries) > 0 && (state.sizeOfObservedEvents() > maxKeyValueValueBytes || - state.sizeOf() > maxKeyValueModifiedKeysPlusValuesBytes) { + state.sizeOf() > c.limits.MaxKeyValueModifiedKeysPlusValuesBytes) { // sorted by decreasing priority, so prune the last toRemove := state.observedEventEntries[len(state.observedEventEntries)-1] delete(state.observedEvents, string(toRemove.TimelessHash)) @@ -448,7 +451,7 @@ func (c *consensusQueuePlugin) StateTransition( if len(queuedTimelessHashes) > 0 && (state.sizeOfQueuedEvents() > maxKeyValueValueBytes || state.sizeOfBlobHandles() > maxKeyValueValueBytes || - state.sizeOf() > maxKeyValueModifiedKeysPlusValuesBytes) { + state.sizeOf() > c.limits.MaxKeyValueModifiedKeysPlusValuesBytes) { // prune lowest priority queuedEvents from newly added queuedTriggerEventIDs queuedTimelessHashSet := map[string]struct{}{} for _, id := range queuedTimelessHashes { @@ -467,7 +470,7 @@ func (c *consensusQueuePlugin) StateTransition( for backwardsQueuedEvents.Len() > 0 && (state.sizeOfQueuedEvents() > maxKeyValueValueBytes || state.sizeOfBlobHandles() > maxKeyValueValueBytes || - state.sizeOf() > maxKeyValueModifiedKeysPlusValuesBytes) { + state.sizeOf() > c.limits.MaxKeyValueModifiedKeysPlusValuesBytes) { toRemove := heap.Pop(backwardsQueuedEvents).(*pb.ConsensusQueueEvent) //TODO opt: faster delete...but need to maintain state.queuedEvents (though not order)...map indices? state.queuedEvents = slices.DeleteFunc(state.queuedEvents, func(event *pb.ConsensusQueueEvent) bool { return event == toRemove }) diff --git a/core/services/ocr3_1/plugins/queue/queue_test.go b/core/services/ocr3_1/plugins/queue/queue_test.go index 88be248cc8a..83b25e19d96 100644 --- a/core/services/ocr3_1/plugins/queue/queue_test.go +++ b/core/services/ocr3_1/plugins/queue/queue_test.go @@ -92,6 +92,6 @@ func (n noopQueue) Stats(ctx context.Context) (triggers.Stats, error) { return triggers.Stats{}, nil } -func (n noopQueue) Peek(int) []triggers.CoordinatedEvent { return nil } +func (n noopQueue) Peek(int) iter.Seq[triggers.CoordinatedEvent] { return nil } -func (n noopQueue) Remove(ctx context.Context, triggerEventIDs iter.Seq[string]) {} +func (n noopQueue) Remove(ctx context.Context, execIDs iter.Seq[string]) {} diff --git a/core/services/workflows/v2/triggers/coordinator_shadow_test.go b/core/services/workflows/v2/triggers/coordinator_shadow_test.go index 567a40774ce..3fd5a03bdcf 100644 --- a/core/services/workflows/v2/triggers/coordinator_shadow_test.go +++ b/core/services/workflows/v2/triggers/coordinator_shadow_test.go @@ -334,7 +334,9 @@ type failingQueue struct { puts atomic.Int32 } -func (q *failingQueue) Peek(int) []CoordinatedEvent { return nil } +func (q *failingQueue) Peek(int) iter.Seq[CoordinatedEvent] { + return func(yield func(CoordinatedEvent) bool) {} +} func (q *failingQueue) Remove(ctx context.Context, execIDs iter.Seq[string]) {} diff --git a/core/services/workflows/v2/triggers/drainer_test.go b/core/services/workflows/v2/triggers/drainer_test.go index f44dc031f38..b6b7e3a53f5 100644 --- a/core/services/workflows/v2/triggers/drainer_test.go +++ b/core/services/workflows/v2/triggers/drainer_test.go @@ -1,6 +1,7 @@ package triggers import ( + "cmp" "context" "errors" "fmt" @@ -61,11 +62,14 @@ type fakeQueue struct { drainCalls int } -func (q *fakeQueue) Peek(limit int) []CoordinatedEvent { +func (q *fakeQueue) Peek(limit int) iter.Seq[CoordinatedEvent] { q.mu.Lock() - events := slices.Clone(q.results[0].events)[:min(limit, len(q.results[0].events))] + events := slices.Clone(q.results[0].events) q.mu.Unlock() - return events + slices.SortFunc(events, func(a, b CoordinatedEvent) int { + return cmp.Or(a.Deadline.Compare(b.Deadline), cmp.Compare(*a.executionID, *b.executionID)) + }) + return slices.Values(events[:min(limit, len(events))]) } func (q *fakeQueue) Remove(ctx context.Context, execIDs iter.Seq[string]) { diff --git a/core/services/workflows/v2/triggers/queue.go b/core/services/workflows/v2/triggers/queue.go index ec7f86a178d..5d857595f3f 100644 --- a/core/services/workflows/v2/triggers/queue.go +++ b/core/services/workflows/v2/triggers/queue.go @@ -1,6 +1,7 @@ package triggers import ( + "cmp" "context" "errors" "fmt" @@ -33,9 +34,8 @@ type Queue interface { // Stats reports current length, capacity, and cumulative drops. Stats(context.Context) (Stats, error) - // Peek is like Drain, but does not empty the queue and only returns up to max events. - // Events remain but can be removed via Remove. - Peek(max int) []CoordinatedEvent + // Peek returns a sorted iterator over events. Events remain but can be removed via Remove. + Peek(int) iter.Seq[CoordinatedEvent] // Remove removes events from the queue by execution ID. //TODO can't ack with trigger event ID - not unique! @@ -157,12 +157,16 @@ func (q *CentralQueue) Remove(ctx context.Context, executionIDs iter.Seq[string] return } -func (q *CentralQueue) Peek(limit int) []CoordinatedEvent { +func (q *CentralQueue) Peek(limit int) iter.Seq[CoordinatedEvent] { q.mu.Lock() - events := slices.Clone(q.events)[:min(len(q.events), limit)] + events := slices.Clone(q.events) q.mu.Unlock() - - return events + //TODO opt: heap + slices.SortFunc(events, func(a, b CoordinatedEvent) int { + // events are rejected if we cannot set the execution ID + return cmp.Or(a.Deadline.Compare(b.Deadline), cmp.Compare(*a.executionID, *b.executionID)) + }) + return slices.Values(events[:min(limit, len(events))]) } // Stats returns copies of the queue's maps, so callers may keep or change them. From 5c2b92b29de8a56c2e4d0ee8c5fc0846c7cdec82 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Sun, 22 Nov 2026 06:34:14 -0600 Subject: [PATCH 18/38] fixes; cleanup; simplifications --- core/scripts/go.mod | 2 +- core/scripts/go.sum | 4 +- core/services/ocr3_1/plugins/queue/blobs.go | 8 +- core/services/ocr3_1/plugins/queue/kvstate.go | 10 +- core/services/ocr3_1/plugins/queue/queue.go | 172 +++++++++++------- .../ocr3_1/plugins/queue/queue_test.go | 3 +- .../v2/triggers/coordinator_shadow_test.go | 9 +- .../workflows/v2/triggers/drainer_test.go | 79 +++++--- core/services/workflows/v2/triggers/queue.go | 113 +++++++++--- .../workflows/v2/triggers/queue_test.go | 54 +++--- .../workflows/v2/triggers/triggers.go | 12 -- deployment/go.mod | 2 +- deployment/go.sum | 4 +- go.mod | 2 +- go.sum | 4 +- integration-tests/go.mod | 2 +- integration-tests/go.sum | 4 +- integration-tests/load/go.mod | 2 +- integration-tests/load/go.sum | 4 +- system-tests/lib/go.mod | 2 +- system-tests/lib/go.sum | 4 +- system-tests/tests/go.mod | 2 +- system-tests/tests/go.sum | 4 +- 23 files changed, 319 insertions(+), 183 deletions(-) diff --git a/core/scripts/go.mod b/core/scripts/go.mod index 7732a6d12c9..6c3f39af591 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.20261120175945-48b9bc85cc7b + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51 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.20261112211734-e640e1c12078 diff --git a/core/scripts/go.sum b/core/scripts/go.sum index 0bbf9098e56..c50ce511c6e 100644 --- a/core/scripts/go.sum +++ b/core/scripts/go.sum @@ -1686,8 +1686,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.20261120175945-48b9bc85cc7b h1:XHlQnqb1I6fMHkwvCXMqKnWdLGLHRElhSrXLSMVwuv8= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51 h1:fAvMtXBFQUgk+q5I28OPg/aEIJ053mzJfChxw6hO0lM= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/core/services/ocr3_1/plugins/queue/blobs.go b/core/services/ocr3_1/plugins/queue/blobs.go index 2e8302e9082..b5fc8c5db74 100644 --- a/core/services/ocr3_1/plugins/queue/blobs.go +++ b/core/services/ocr3_1/plugins/queue/blobs.go @@ -2,6 +2,7 @@ package queue import ( "context" + "errors" "fmt" "sync" "time" @@ -103,13 +104,16 @@ func extractEvent(b []byte, idx int) (*pb.CoordinatedEvent, []byte, error) { } // broadcastAsBlob 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.BlobBroadcastFetcher, events []*pb.CoordinatedEvent, +func (c *consensusQueuePlugin) broadcastAsBlob(ctx context.Context, broadcaster ocr3_1types.BlobBroadcaster, events []*pb.CoordinatedEvent, seqNr uint64) (blobHandle []byte, n int, err error) { protoOpts := proto.MarshalOptions{Deterministic: true} - for ; protoOpts.Size(&pb.CoordinatedEventList{Events: events}) > c.limits.MaxBlobPayloadBytes; events = events[:len(events)-1] { + for ; len(events) > 0 && protoOpts.Size(&pb.CoordinatedEventList{Events: events}) > c.limits.MaxBlobPayloadBytes; events = events[:len(events)-1] { //TODO opt: binary search for largest fit instead.... } n = len(events) + if n == 0 { + return nil, 0, errors.New("failed to package any events in blob") + } var maxDeadline time.Time for _, event := range events { if t := event.Deadline.AsTime(); t.After(maxDeadline) { diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index d9d8cdf8dba..8566e2278b6 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -18,7 +18,7 @@ import ( // KV store keys const ( - // observed events waiting for consensus (<2f+1 observers) + // observed events waiting for consensus (F+1 <= observers <2F+1) 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 } @@ -76,7 +76,7 @@ func (p *priorityQueue) Pop() any { func (p *priorityQueue) push(x *pb.ConsensusQueueEvent) { heap.Push(p, x) } -func (p *priorityQueue) pushObservations(timelessHash string, obs *pb.ConsensusQueueObservedEvent) *pb.ConsensusQueueEvent { +func (s *kvState) queueObservations(timelessHash string, obs *pb.ConsensusQueueObservedEvent) *pb.ConsensusQueueEvent { event := &pb.ConsensusQueueEvent{ WorkflowID: obs.WorkflowID, ExecutionID: obs.ExecutionID, @@ -85,7 +85,7 @@ func (p *priorityQueue) pushObservations(timelessHash string, obs *pb.ConsensusQ TimelessHash: []byte(timelessHash), // note: observedBlobs tracks blobs while in memory } - p.push(event) + s.queuedEvents.push(event) return event } @@ -392,7 +392,7 @@ func (s *kvState) addObservedEvents(f int, toAdd map[string]*pb.ConsensusQueueOb case len(eventToAdd.NodeIds) >= 2*f+1: // new proposal straight to priority queue s.queuedBlobs.addAll(eventHash, observedBlobs[eventHash]) - event := s.queuedEvents.pushObservations(eventHash, eventToAdd) + event := s.queueObservations(eventHash, eventToAdd) onQueued(event) case len(eventToAdd.NodeIds) >= f+1: // new proposal to the observation set @@ -423,7 +423,7 @@ func (s *kvState) addObservedEvents(f int, toAdd map[string]*pb.ConsensusQueueOb delete(s.observedEvents, eventHash) s.queuedBlobs[eventHash] = s.observedBlobs[eventHash] delete(s.observedBlobs, eventHash) - event := s.queuedEvents.pushObservations(eventHash, obsEvent) + event := s.queueObservations(eventHash, obsEvent) onQueued(event) } } diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index 01f60553495..bce898e8037 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -13,6 +13,7 @@ import ( "crypto/sha256" "errors" "fmt" + "maps" "math" "slices" "sync" @@ -149,14 +150,14 @@ func (c *consensusQueuePlugin) Observation( c.lggr.Warnw("Failed to get expiration grace duration - using default", "err", err) } - emptyBlobHandle := make([]byte, c.blobHandleMarshalledBytesUpperBound) obs := &pb.ConsensusQueueObservation{ // placeholder for accurate size calculation - BlobHandles: slices.Repeat([][]byte{emptyBlobHandle}, maxObservedBlobHandles), + BlobHandles: slices.Repeat([][]byte{make([]byte, c.blobHandleMarshalledBytesUpperBound)}, maxObservedBlobHandles), Expiration: timestamppb.New(time.Now().Add(-expirationGraceDur)), Capacity: uint32(min(capacity.Global, math.MaxUint32)), WorkflowCapacities: make(map[string]uint32), } + // collect KV workflow capacities for _, e := range observedEvents { if wfCap, ok := capacity.PerWorkflow[e.WorkflowID]; ok { obs.WorkflowCapacities[e.WorkflowID] = uint32(min(wfCap, math.MaxUint32)) @@ -167,94 +168,130 @@ func (c *consensusQueuePlugin) Observation( obs.WorkflowCapacities[e.WorkflowID] = uint32(min(wfCap, math.MaxUint32)) } } - - protoOpts := proto.MarshalOptions{Deterministic: true} + kvWFCapactities := maps.Clone(obs.WorkflowCapacities) // in case we need to rebuild later // Assemble an observation up to maxObservationBytes - var events []*pb.CoordinatedEvent - for event := range c.triggerQueue.Peek(maxObservedEvents) { - pbEvent := event.ToProto() - observedAt, deadline := pbEvent.ObservedAt, pbEvent.Deadline - pbEvent.ObservedAt, pbEvent.Deadline = nil, nil // for consistent hashing - protoBytes, err2 := protoOpts.Marshal(pbEvent) // TODO opt: avoid remarshalling - if err2 != nil { - return nil, fmt.Errorf("failed to marshal event: %w", err2) - } - timelessHash := sha256.Sum256(protoBytes) - + var events []*pb.CoordinatedEvent // to be broadcast + protoOpts := proto.MarshalOptions{Deterministic: true} + for timelessHash, event := range c.triggerQueue.Sorted(maxObservedEvents) { // skip if kv observation exists already - if obsEvent, ok := observedEvents[string(timelessHash[:])]; ok { + if obsEvent, ok := observedEvents[string(timelessHash)]; ok { if slices.Contains(obsEvent.NodeIds, uint8(c.onchainCfg.OracleID)) { continue } } - executionID, err2 := workflows.GenerateExecutionIDWithTriggerIndex(event.WorkflowID, event.Event.Event.ID, event.TriggerIndex) + events = append(events, event) + newWF, err2 := observeEvent(obs, timelessHash, event, capacity.PerWorkflow) if err2 != nil { - return nil, fmt.Errorf("failed to generate execution ID: %w", err2) - } - - obs.Events = append(obs.Events, &pb.ConsensusQueueEvent{ - WorkflowID: pbEvent.WorkflowID, - ExecutionID: executionID, - ObservedAt: observedAt, - Deadline: deadline, - TimelessHash: timelessHash[:], - Blobs: []*pb.CoordinatedEventBlobHandle{{ - Blob: 0, - Element: uint32(len(events)), - }}, - }) - events = append(events, pbEvent) - - var addedCap bool - if _, ok := obs.WorkflowCapacities[pbEvent.WorkflowID]; !ok { - addedCap = true - obs.WorkflowCapacities[pbEvent.WorkflowID] = uint32(min(capacity.PerWorkflow[pbEvent.WorkflowID], math.MaxUint32)) + return nil, err2 } // Check size if protoOpts.Size(obs) > c.limits.MaxObservationBytes { // too large, remove this one obs.Events = obs.Events[:len(obs.Events)-1] - if addedCap { - delete(obs.WorkflowCapacities, pbEvent.WorkflowID) + if newWF { + delete(obs.WorkflowCapacities, event.WorkflowID) } break } } - obs.BlobHandles = nil // remove the placeholders - if len(events) > 0 { - blobHandle, n, err2 := c.broadcastAsBlob(ctx, blobBroadcaster, events, seqNr) - if err2 != nil { - return nil, err2 - } - obs.BlobHandles = append(obs.BlobHandles, blobHandle) - // note: elements already reference blob 0 and natural element index is aligned - - // we verified space for up to maxObservedBlobHandles blobs - lastEnd := n - events = events[n:] - for batch := 1; batch < maxObservedBlobHandles && len(events) > 0; batch++ { - blobHandle, n, err2 = c.broadcastAsBlob(ctx, blobBroadcaster, events, seqNr) - if err2 != nil { - return nil, err2 - } - obs.BlobHandles = append(obs.BlobHandles, blobHandle) - for i := 0; i < n; i++ { // update indices - obs.Events[lastEnd+i].Blobs[0].Blob = uint32(batch) - obs.Events[lastEnd+i].Blobs[0].Element = uint32(i) + 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 = kvWFCapactities + for _, event := range obs.Events { + if _, ok := obs.WorkflowCapacities[event.WorkflowID]; !ok { + obs.WorkflowCapacities[event.WorkflowID] = uint32(min(capacity.PerWorkflow[event.WorkflowID], math.MaxUint32)) } - lastEnd += n - events = events[n:] } - //TODO if we hit max blobs, then drop excess events } return protoOpts.Marshal(obs) } +// 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), + }}, + }) + + if _, ok := obs.WorkflowCapacities[event.WorkflowID]; !ok { + newWF = true + obs.WorkflowCapacities[event.WorkflowID] = uint32(min(wfCapacities[event.WorkflowID], math.MaxUint32)) + } + + 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. +func (c *consensusQueuePlugin) broadcastObservationBlobs( + ctx context.Context, obs *pb.ConsensusQueueObservation, blobBroadcaster ocr3_1types.BlobBroadcaster, + events []*pb.CoordinatedEvent, seqNr uint64, +) (bool, error) { + if len(events) == 0 { + return true, nil + } + if len(events) != len(obs.Events) { + return false, fmt.Errorf("number of events and observedEvents must match") + } + + blobHandle, n, err := c.broadcastAsBlob(ctx, blobBroadcaster, events, seqNr) + if err != nil { + return false, err + } + obs.BlobHandles = append(obs.BlobHandles, blobHandle) + // note: elements already reference blob 0 and natural element index is aligned + + // we verified space for up to maxObservedBlobHandles blobs + lastEnd := n + events = events[n:] + for batch := 1; batch < maxObservedBlobHandles && len(events) > 0; batch++ { + blobHandle, n, err = c.broadcastAsBlob(ctx, blobBroadcaster, events, seqNr) + if err != nil { + return false, err + } + obs.BlobHandles = append(obs.BlobHandles, blobHandle) + for i := 0; i < n; i++ { // update indices + obs.Events[lastEnd+i].Blobs[0].Blob = uint32(batch) + obs.Events[lastEnd+i].Blobs[0].Element = uint32(i) + } + lastEnd += n + events = events[n:] + } + limited := lastEnd < len(obs.Events) + if limited { + // we hit max blobs, so drop excess events + obs.Events = obs.Events[:lastEnd] + // note: caller will fix wfCapacity + } + return !limited, nil +} + func (c *consensusQueuePlugin) ValidateObservation( ctx context.Context, _ uint64, _ ocrtypes.AttributedQuery, ao ocrtypes.AttributedObservation, _ ocr3_1types.KeyValueStateReader, blobFetcher ocr3_1types.BlobFetcher, @@ -289,7 +326,13 @@ func (c *consensusQueuePlugin) ValidateObservation( return err } - //TODO ensure capacity map is only observations and KV observed & queued events + // 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) + } + } + //TODO ensure map only contains wfs from observations and KV observed+queued events // ensure no duplicate execution ID or timelessHash execIDs, timelessHashes := make(map[string]struct{}), make(map[string]struct{}) @@ -531,6 +574,7 @@ func (res *observations) aggregate(ctx context.Context, f int, aos []ocrtypes.At // 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. + //TODO fill zeros for missing nodes? res.medianCap = slices.Sorted(slices.Values(capacities))[f] for wf, caps := range wfCapacities { if len(caps) >= 2*f+1 { diff --git a/core/services/ocr3_1/plugins/queue/queue_test.go b/core/services/ocr3_1/plugins/queue/queue_test.go index 83b25e19d96..59776538160 100644 --- a/core/services/ocr3_1/plugins/queue/queue_test.go +++ b/core/services/ocr3_1/plugins/queue/queue_test.go @@ -10,6 +10,7 @@ import ( "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types" "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types" + "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb" "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/settings/limits" "github.com/smartcontractkit/chainlink/v2/core/services/workflows/v2/triggers" @@ -92,6 +93,6 @@ func (n noopQueue) Stats(ctx context.Context) (triggers.Stats, error) { return triggers.Stats{}, nil } -func (n noopQueue) Peek(int) iter.Seq[triggers.CoordinatedEvent] { return nil } +func (n noopQueue) Sorted(int) iter.Seq2[[]byte, *pb.CoordinatedEvent] { return nil } func (n noopQueue) Remove(ctx context.Context, execIDs iter.Seq[string]) {} diff --git a/core/services/workflows/v2/triggers/coordinator_shadow_test.go b/core/services/workflows/v2/triggers/coordinator_shadow_test.go index 3fd5a03bdcf..c5f4e68ceab 100644 --- a/core/services/workflows/v2/triggers/coordinator_shadow_test.go +++ b/core/services/workflows/v2/triggers/coordinator_shadow_test.go @@ -17,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" @@ -334,8 +335,8 @@ type failingQueue struct { puts atomic.Int32 } -func (q *failingQueue) Peek(int) iter.Seq[CoordinatedEvent] { - return func(yield func(CoordinatedEvent) bool) {} +func (q *failingQueue) Sorted(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]) {} @@ -456,7 +457,7 @@ func TestCoordinator_DrainerLifecycle(t *testing.T) { require.NoError(t, c.Start(t.Context())) require.NoError(t, d.Ready(), "the drainer must run once the coordinator starts") - putAll(t, q, centralEvent(t, "wf-a", 0, "evt-1")) + putAll(t, q, centralEvent("wf-a", 0, "evt-1")) ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) defer cancel() require.NoError(t, clock.BlockUntilContext(ctx, 1), "the drainer is not waiting on the clock") @@ -470,7 +471,7 @@ func TestCoordinator_DrainerLifecycle(t *testing.T) { require.Error(t, d.Ready(), "the drainer must stop when the coordinator closes") // Nothing waits on the clock after close, so Advance does nothing unless the drainer goroutine leaked. - putAll(t, q, centralEvent(t, "wf-a", 0, "evt-2")) + putAll(t, q, centralEvent("wf-a", 0, "evt-2")) clock.Advance(500 * time.Millisecond) assert.Never(t, func() bool { stats, err := q.Stats(t.Context()) diff --git a/core/services/workflows/v2/triggers/drainer_test.go b/core/services/workflows/v2/triggers/drainer_test.go index b6b7e3a53f5..047d16e307c 100644 --- a/core/services/workflows/v2/triggers/drainer_test.go +++ b/core/services/workflows/v2/triggers/drainer_test.go @@ -1,10 +1,8 @@ package triggers import ( - "cmp" "context" "errors" - "fmt" "iter" "slices" "sync" @@ -21,9 +19,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" ) @@ -62,14 +62,22 @@ type fakeQueue struct { drainCalls int } -func (q *fakeQueue) Peek(limit int) iter.Seq[CoordinatedEvent] { +func (q *fakeQueue) Sorted(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 CoordinatedEvent) int { - return cmp.Or(a.Deadline.Compare(b.Deadline), cmp.Compare(*a.executionID, *b.executionID)) - }) - return slices.Values(events[:min(limit, len(events))]) + 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 + } + } + } } func (q *fakeQueue) Remove(ctx context.Context, execIDs iter.Seq[string]) { @@ -80,11 +88,8 @@ func (q *fakeQueue) Remove(ctx context.Context, execIDs iter.Seq[string]) { q.mu.Lock() defer q.mu.Unlock() for _, r := range q.results { - r.events = slices.DeleteFunc(r.events, func(e CoordinatedEvent) bool { - if err := e.cacheExecutionID(); err != nil { - panic(fmt.Errorf("unable to generate execution ID: %w", err)) - } - _, ok := execIDSet[*e.executionID] + r.events = slices.DeleteFunc(r.events, func(e centralQueueEvent) bool { + _, ok := execIDSet[e.executionID] return ok }) // note: empty results remain @@ -92,7 +97,7 @@ func (q *fakeQueue) Remove(ctx context.Context, execIDs iter.Seq[string]) { } type observeResult struct { - events []CoordinatedEvent + events []centralQueueEvent err error } @@ -109,7 +114,11 @@ func (q *fakeQueue) Drain(context.Context) ([]CoordinatedEvent, error) { } 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) getDrainCalls() int { @@ -127,6 +136,28 @@ 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 { + hash, err := pbe.TimelessHash() + require.NoError(t, err) + 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) { @@ -153,7 +184,7 @@ func TestDrainer_Drain(t *testing.T) { }{ { name: "queues an observed batch", - results: []*observeResult{{events: batchOf("a")}}, + results: []*observeResult{{events: centralQueueEvents(t, batchOf("a"))}}, want: [][]CoordinatedEvent{batchOf("a")}, }, { @@ -162,11 +193,11 @@ func TestDrainer_Drain(t *testing.T) { }, { 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")}, }, } @@ -198,8 +229,8 @@ func TestDrainer_DroppedEventsMetric(t *testing.T) { dm, reader := testDrainerMetrics(t) q := &fakeQueue{results: []*observeResult{ - {events: batchOf("a")}, - {events: append(batchOf("b"), batchOf("c")...)}, // dropped: the buffer holds "a" + {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()) @@ -221,7 +252,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()) }) @@ -247,12 +278,12 @@ func TestDrainer_Running(t *testing.T) { }{ { 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"}, }, } @@ -304,7 +335,7 @@ func TestDrainer_BlockedHook(t *testing.T) { t.Parallel() 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} @@ -423,7 +454,7 @@ 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) diff --git a/core/services/workflows/v2/triggers/queue.go b/core/services/workflows/v2/triggers/queue.go index 5d857595f3f..e7e2b47fde1 100644 --- a/core/services/workflows/v2/triggers/queue.go +++ b/core/services/workflows/v2/triggers/queue.go @@ -1,7 +1,9 @@ package triggers import ( + "bytes" "cmp" + "container/heap" "context" "errors" "fmt" @@ -10,9 +12,13 @@ import ( "slices" "sync" + "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" ) @@ -34,8 +40,8 @@ type Queue interface { // Stats reports current length, capacity, and cumulative drops. Stats(context.Context) (Stats, error) - // Peek returns a sorted iterator over events. Events remain but can be removed via Remove. - Peek(int) iter.Seq[CoordinatedEvent] + // Sorted returns a sorted iterator over events, up to limit. Events remain but can be removed via Remove. + Sorted(limit int) iter.Seq2[[]byte, *pb.CoordinatedEvent] // Remove removes events from the queue by execution ID. //TODO can't ack with trigger event ID - not unique! @@ -66,12 +72,23 @@ 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 } +type centralQueueEvent struct { + CoordinatedEvent + pb *pb.CoordinatedEvent + timelessHash []byte + executionID string +} + +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 // CentralTriggerEventQueueLimit default is used. Metrics are recorded as part of each Put and Drain. The queue // is safe for concurrent use. @@ -88,10 +105,6 @@ func NewQueue(limit limits.BoundLimiter[int], metrics *monitoring.CentralTrigger // Put appends e, or returns ErrQueueFull and counts the drop when the queue is at capacity. func (q *CentralQueue) Put(ctx context.Context, e CoordinatedEvent) error { - if err := e.cacheExecutionID(); err != nil { - return fmt.Errorf("failed to generate execution ID: %w", err) - } - capacity := q.capacity(ctx) q.mu.Lock() @@ -102,7 +115,21 @@ 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() + timelessHash, err := pbe.TimelessHash() + if err != nil { + return fmt.Errorf("failed to compute timeless hash: %w", err) + } + 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, + }) q.depthByWorkflow[e.WorkflowID]++ q.depthByTriggerType[e.TriggerCapID]++ q.metrics.IncrementPutsCounter(ctx) @@ -118,7 +145,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{} @@ -140,13 +170,13 @@ func (q *CentralQueue) Remove(ctx context.Context, executionIDs iter.Seq[string] defer q.mu.Unlock() var deleted int - //TODO opt: map so we don't have to iterate over them all (just use pointer elements?) - q.events = slices.DeleteFunc(q.events, func(e CoordinatedEvent) bool { - _, ok := execIDSet[*e.executionID] // events are rejected if we cannot set the execution ID + //TODO opt: map so we don't have to iterate over them all + q.events = slices.DeleteFunc(q.events, func(cqe centralQueueEvent) bool { + _, ok := execIDSet[cqe.executionID] if ok { deleted++ - q.depthByWorkflow[e.WorkflowID]-- - q.depthByTriggerType[e.TriggerCapID]-- + q.depthByWorkflow[cqe.WorkflowID]-- + q.depthByTriggerType[cqe.TriggerCapID]-- //TODO emit metric for time.Since(e.ObservedAt) } return ok @@ -157,16 +187,21 @@ func (q *CentralQueue) Remove(ctx context.Context, executionIDs iter.Seq[string] return } -func (q *CentralQueue) Peek(limit int) iter.Seq[CoordinatedEvent] { +func (q *CentralQueue) Sorted(limit int) iter.Seq2[[]byte, *pb.CoordinatedEvent] { q.mu.Lock() - events := slices.Clone(q.events) + events := priorityQueue(slices.Clone(q.events)) q.mu.Unlock() - //TODO opt: heap - slices.SortFunc(events, func(a, b CoordinatedEvent) int { - // events are rejected if we cannot set the execution ID - return cmp.Or(a.Deadline.Compare(b.Deadline), cmp.Compare(*a.executionID, *b.executionID)) - }) - return slices.Values(events[:min(limit, len(events))]) + + heap.Init(&events) + + return func(yield func([]byte, *pb.CoordinatedEvent) bool) { + for count := 0; events.Len() > 0 && count < limit; count++ { + cqe := heap.Pop(&events).(centralQueueEvent) + if !yield(cqe.timelessHash, proto.CloneOf(cqe.pb)) { + return + } + } + } } // Stats returns copies of the queue's maps, so callers may keep or change them. @@ -216,3 +251,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 d3055fa676f..c0d531a3b8a 100644 --- a/core/services/workflows/v2/triggers/queue_test.go +++ b/core/services/workflows/v2/triggers/queue_test.go @@ -68,9 +68,9 @@ 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(t *testing.T, workflowID string, triggerIndex int, id string) CoordinatedEvent { +func centralEvent(workflowID string, triggerIndex int, id string) CoordinatedEvent { observed := time.Now() - e := CoordinatedEvent{ + return CoordinatedEvent{ WorkflowID: workflowID, TriggerCapID: fmt.Sprintf("trigger-%d@1.0.0", triggerIndex), TriggerIndex: triggerIndex, @@ -78,8 +78,6 @@ func centralEvent(t *testing.T, workflowID string, triggerIndex int, id string) Deadline: observed.Add(time.Minute), Event: capabilities.TriggerResponse{Event: capabilities.TriggerEvent{ID: id}}, } - require.NoError(t, e.cacheExecutionID()) - return e } func putAll(t *testing.T, q *CentralQueue, events ...CoordinatedEvent) { @@ -115,9 +113,9 @@ func TestQueue_PutDrain(t *testing.T) { q := newTestCentralQueue(t, &fakeLimit{limit: 10}) want := []CoordinatedEvent{ - centralEvent(t, "wf-a", 0, "evt-1"), - centralEvent(t, "wf-b", 0, "evt-2"), - centralEvent(t, "wf-a", 1, "evt-3"), + centralEvent("wf-a", 0, "evt-1"), + centralEvent("wf-b", 0, "evt-2"), + centralEvent("wf-a", 1, "evt-3"), } putAll(t, q, want...) @@ -125,7 +123,7 @@ func TestQueue_PutDrain(t *testing.T) { require.NoError(t, err) assert.Equal(t, want, got) - putAll(t, q, centralEvent(t, "wf-c", 0, "evt-4")) + putAll(t, q, centralEvent("wf-c", 0, "evt-4")) assert.Equal(t, want, got, "a later put must not write into a drained slice") assert.Equal(t, []string{"evt-4"}, drainIDs(t, q)) @@ -141,9 +139,9 @@ func TestQueue_Capacity(t *testing.T) { t.Run("a put at the limit is rejected and not stored", func(t *testing.T) { t.Parallel() q := newTestCentralQueue(t, &fakeLimit{limit: 2}) - putAll(t, q, centralEvent(t, "wf-a", 0, "evt-1"), centralEvent(t, "wf-a", 0, "evt-2")) + putAll(t, q, centralEvent("wf-a", 0, "evt-1"), centralEvent("wf-a", 0, "evt-2")) - require.ErrorIs(t, q.Put(t.Context(), centralEvent(t, "wf-a", 0, "evt-3")), ErrQueueFull) + require.ErrorIs(t, q.Put(t.Context(), centralEvent("wf-a", 0, "evt-3")), ErrQueueFull) assert.Equal(t, []string{"evt-1", "evt-2"}, drainIDs(t, q)) }) @@ -151,10 +149,10 @@ func TestQueue_Capacity(t *testing.T) { t.Parallel() limit := &fakeLimit{limit: 3} q := newTestCentralQueue(t, limit) - putAll(t, q, centralEvent(t, "wf-a", 0, "evt-1"), centralEvent(t, "wf-a", 0, "evt-2"), centralEvent(t, "wf-a", 0, "evt-3")) + putAll(t, q, centralEvent("wf-a", 0, "evt-1"), centralEvent("wf-a", 0, "evt-2"), centralEvent("wf-a", 0, "evt-3")) limit.set(1, nil) - require.ErrorIs(t, q.Put(t.Context(), centralEvent(t, "wf-a", 0, "evt-4")), ErrQueueFull) + require.ErrorIs(t, q.Put(t.Context(), centralEvent("wf-a", 0, "evt-4")), ErrQueueFull) assert.Equal(t, []string{"evt-1", "evt-2", "evt-3"}, drainIDs(t, q)) }) @@ -162,11 +160,11 @@ func TestQueue_Capacity(t *testing.T) { t.Parallel() limit := &fakeLimit{limit: 1} q := newTestCentralQueue(t, limit) - putAll(t, q, centralEvent(t, "wf-a", 0, "evt-1")) - require.ErrorIs(t, q.Put(t.Context(), centralEvent(t, "wf-a", 0, "evt-2")), ErrQueueFull) + putAll(t, q, centralEvent("wf-a", 0, "evt-1")) + require.ErrorIs(t, q.Put(t.Context(), centralEvent("wf-a", 0, "evt-2")), ErrQueueFull) limit.set(2, nil) - putAll(t, q, centralEvent(t, "wf-a", 0, "evt-3")) + putAll(t, q, centralEvent("wf-a", 0, "evt-3")) assert.Equal(t, []string{"evt-1", "evt-3"}, drainIDs(t, q)) }) @@ -174,7 +172,7 @@ func TestQueue_Capacity(t *testing.T) { t.Parallel() // The value returned with the error is ignored. q := newTestCentralQueue(t, &fakeLimit{limit: 1, err: assert.AnError}) - putAll(t, q, centralEvent(t, "wf-a", 0, "evt-1"), centralEvent(t, "wf-a", 0, "evt-2")) + putAll(t, q, centralEvent("wf-a", 0, "evt-1"), centralEvent("wf-a", 0, "evt-2")) stats, err := q.Stats(t.Context()) require.NoError(t, err) @@ -187,11 +185,11 @@ func TestQueue_Capacity(t *testing.T) { limit := &fakeLimit{limit: defaultLimit + 5} q := newTestCentralQueue(t, limit) for i := range defaultLimit + 5 { - putAll(t, q, centralEvent(t, "wf-a", 0, fmt.Sprintf("evt-%d", i))) + putAll(t, q, centralEvent("wf-a", 0, fmt.Sprintf("evt-%d", i))) } limit.set(0, assert.AnError) - require.ErrorIs(t, q.Put(t.Context(), centralEvent(t, "wf-a", 0, "one-more")), ErrQueueFull) + require.ErrorIs(t, q.Put(t.Context(), centralEvent("wf-a", 0, "one-more")), ErrQueueFull) stats, err := q.Stats(t.Context()) require.NoError(t, err) @@ -207,9 +205,9 @@ func TestQueue_Stats(t *testing.T) { limit := &fakeLimit{limit: 3} q := newTestCentralQueue(t, limit) - putAll(t, q, centralEvent(t, "wf-a", 0, "evt-1"), centralEvent(t, "wf-a", 1, "evt-2"), centralEvent(t, "wf-b", 0, "evt-3")) - require.ErrorIs(t, q.Put(t.Context(), centralEvent(t, "wf-b", 0, "evt-4")), ErrQueueFull) - require.ErrorIs(t, q.Put(t.Context(), centralEvent(t, "wf-a", 1, "evt-5")), ErrQueueFull) + putAll(t, q, centralEvent("wf-a", 0, "evt-1"), centralEvent("wf-a", 1, "evt-2"), centralEvent("wf-b", 0, "evt-3")) + require.ErrorIs(t, q.Put(t.Context(), centralEvent("wf-b", 0, "evt-4")), ErrQueueFull) + require.ErrorIs(t, q.Put(t.Context(), centralEvent("wf-a", 1, "evt-5")), ErrQueueFull) stats, err := q.Stats(t.Context()) require.NoError(t, err) @@ -232,8 +230,8 @@ func TestQueue_Stats(t *testing.T) { drainIDs(t, q) limit.set(1, nil) - putAll(t, q, centralEvent(t, "wf-c", 0, "evt-6")) - require.ErrorIs(t, q.Put(t.Context(), centralEvent(t, "wf-b", 0, "evt-7")), ErrQueueFull) + putAll(t, q, centralEvent("wf-c", 0, "evt-6")) + require.ErrorIs(t, q.Put(t.Context(), centralEvent("wf-b", 0, "evt-7")), ErrQueueFull) stats, err = q.Stats(t.Context()) require.NoError(t, err) @@ -271,7 +269,7 @@ func TestQueue_ConcurrentPutDrain(t *testing.T) { for p := range producers { wg.Go(func() { for range perProducer { - e := centralEvent(t, fmt.Sprintf("wf-%d", p), 0, "evt") + e := centralEvent(fmt.Sprintf("wf-%d", p), 0, "evt") err := q.Put(t.Context(), e) if err == nil { accepted[p]++ @@ -373,11 +371,11 @@ func TestQueue_Metrics(t *testing.T) { qm, reader := testQueueMetrics(t) q := NewQueue(&fakeLimit{limit: 2}, qm, logger.Test(t)) - putAll(t, q, centralEvent(t, "wf-a", 0, "evt-1"), centralEvent(t, "wf-b", 0, "evt-2")) - require.ErrorIs(t, q.Put(t.Context(), centralEvent(t, "wf-a", 0, "evt-3")), ErrQueueFull) + putAll(t, q, centralEvent("wf-a", 0, "evt-1"), centralEvent("wf-b", 0, "evt-2")) + require.ErrorIs(t, q.Put(t.Context(), centralEvent("wf-a", 0, "evt-3")), ErrQueueFull) drainIDs(t, q) assert.Equal(t, int64(0), int64Gauge(t, reader, "platform_engine_central_trigger_queue_depth"), "after drain") - putAll(t, q, centralEvent(t, "wf-a", 0, "evt-4")) + putAll(t, q, centralEvent("wf-a", 0, "evt-4")) stats, err := q.Stats(t.Context()) require.NoError(t, err) @@ -424,7 +422,7 @@ func TestQueue_CapacityGaugeOnDrain(t *testing.T) { qm, reader := testQueueMetrics(t) limit := &fakeLimit{limit: 2} q := NewQueue(limit, qm, logger.Test(t)) - putAll(t, q, centralEvent(t, "wf-a", 0, "evt-1")) + putAll(t, q, centralEvent("wf-a", 0, "evt-1")) require.Equal(t, int64(2), int64Gauge(t, reader, "platform_engine_central_trigger_queue_capacity")) limit.set(5, nil) diff --git a/core/services/workflows/v2/triggers/triggers.go b/core/services/workflows/v2/triggers/triggers.go index 30b12c61ee4..665c0d106d4 100644 --- a/core/services/workflows/v2/triggers/triggers.go +++ b/core/services/workflows/v2/triggers/triggers.go @@ -20,7 +20,6 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/contexts" "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/settings/limits" - "github.com/smartcontractkit/chainlink-common/pkg/workflows" sdkpb "github.com/smartcontractkit/chainlink-protos/cre/go/sdk" "github.com/smartcontractkit/chainlink/v2/core/capabilities/validation" "github.com/smartcontractkit/chainlink/v2/core/platform" @@ -184,17 +183,6 @@ type CoordinatedEvent struct { Deadline time.Time Event capabilities.TriggerResponse - - executionID *string // cached -} - -func (e *CoordinatedEvent) cacheExecutionID() error { - executionID, err := workflows.GenerateExecutionIDWithTriggerIndex(e.WorkflowID, e.Event.Event.ID, e.TriggerIndex) - if err != nil { - return fmt.Errorf("failed to generate execution ID: %w", err) - } - e.executionID = &executionID - return nil } func (e *CoordinatedEvent) ToProto() *pb.CoordinatedEvent { diff --git a/deployment/go.mod b/deployment/go.mod index 11ac9a4ce1f..c9aecd408f9 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.20261120175945-48b9bc85cc7b + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51 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 e3c0e6efb2d..c5ce3e5572b 100644 --- a/deployment/go.sum +++ b/deployment/go.sum @@ -1411,8 +1411,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.20261120175945-48b9bc85cc7b h1:XHlQnqb1I6fMHkwvCXMqKnWdLGLHRElhSrXLSMVwuv8= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51 h1:fAvMtXBFQUgk+q5I28OPg/aEIJ053mzJfChxw6hO0lM= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/go.mod b/go.mod index dfd92a5310a..f4a2c2c2232 100644 --- a/go.mod +++ b/go.mod @@ -82,7 +82,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.20261120175945-48b9bc85cc7b + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 github.com/smartcontractkit/chainlink-data-streams v1.1.3 diff --git a/go.sum b/go.sum index b4f4d6593fb..9211689afd5 100644 --- a/go.sum +++ b/go.sum @@ -1102,8 +1102,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.20261120175945-48b9bc85cc7b h1:XHlQnqb1I6fMHkwvCXMqKnWdLGLHRElhSrXLSMVwuv8= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51 h1:fAvMtXBFQUgk+q5I28OPg/aEIJ053mzJfChxw6hO0lM= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/integration-tests/go.mod b/integration-tests/go.mod index 26fd800c8ba..d5c69124011 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.20261120175945-48b9bc85cc7b + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51 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.20261112211734-e640e1c12078 diff --git a/integration-tests/go.sum b/integration-tests/go.sum index d9efcdd5660..88dd53de619 100644 --- a/integration-tests/go.sum +++ b/integration-tests/go.sum @@ -1396,8 +1396,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.20261120175945-48b9bc85cc7b h1:XHlQnqb1I6fMHkwvCXMqKnWdLGLHRElhSrXLSMVwuv8= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51 h1:fAvMtXBFQUgk+q5I28OPg/aEIJ053mzJfChxw6hO0lM= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/integration-tests/load/go.mod b/integration-tests/load/go.mod index 7078e160fec..f984a0976e8 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.20261120175945-48b9bc85cc7b + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51 github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261112211734-e640e1c12078 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 4c4c2ff414b..6aef7c226dd 100644 --- a/integration-tests/load/go.sum +++ b/integration-tests/load/go.sum @@ -1636,8 +1636,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.20261120175945-48b9bc85cc7b h1:XHlQnqb1I6fMHkwvCXMqKnWdLGLHRElhSrXLSMVwuv8= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51 h1:fAvMtXBFQUgk+q5I28OPg/aEIJ053mzJfChxw6hO0lM= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/system-tests/lib/go.mod b/system-tests/lib/go.mod index 563c94112a0..eab206eb19c 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.20261120175945-48b9bc85cc7b + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51 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 e74b479171e..d60af6ea747 100644 --- a/system-tests/lib/go.sum +++ b/system-tests/lib/go.sum @@ -1657,8 +1657,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.20261120175945-48b9bc85cc7b h1:XHlQnqb1I6fMHkwvCXMqKnWdLGLHRElhSrXLSMVwuv8= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51 h1:fAvMtXBFQUgk+q5I28OPg/aEIJ053mzJfChxw6hO0lM= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/system-tests/tests/go.mod b/system-tests/tests/go.mod index d9dcdea3333..b4574d794c6 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.20261120175945-48b9bc85cc7b + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 github.com/smartcontractkit/chainlink-confidential-compute v1.3.0 diff --git a/system-tests/tests/go.sum b/system-tests/tests/go.sum index f86e29e5b8a..5ae692fb4bf 100644 --- a/system-tests/tests/go.sum +++ b/system-tests/tests/go.sum @@ -1836,8 +1836,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.20261120175945-48b9bc85cc7b h1:XHlQnqb1I6fMHkwvCXMqKnWdLGLHRElhSrXLSMVwuv8= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120175945-48b9bc85cc7b/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51 h1:fAvMtXBFQUgk+q5I28OPg/aEIJ053mzJfChxw6hO0lM= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= From fa2fcf64f1fe66b00c4dcf42ad888111d0d26c6d Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Sun, 22 Nov 2026 07:32:22 -0600 Subject: [PATCH 19/38] add tests & fixes --- core/scripts/go.mod | 2 +- core/scripts/go.sum | 4 +- core/services/cre/cre.go | 1 + core/services/ocr3_1/plugins/queue/blobs.go | 88 +- .../ocr3_1/plugins/queue/blobs_test.go | 414 ++++ core/services/ocr3_1/plugins/queue/config.go | 31 +- .../ocr3_1/plugins/queue/config_test.go | 305 +++ core/services/ocr3_1/plugins/queue/kvstate.go | 47 +- .../ocr3_1/plugins/queue/kvstate_test.go | 664 +++++ .../ocr3_1/plugins/queue/math_test.go | 47 + core/services/ocr3_1/plugins/queue/queue.go | 203 +- .../ocr3_1/plugins/queue/queue_test.go | 2174 ++++++++++++++++- .../ocr3_1/plugins/queue/transmitter_test.go | 21 + .../central_trigger_queue_metrics.go | 2 + .../workflows/v2/triggers/coordinator.go | 33 +- .../v2/triggers/coordinator_shadow_test.go | 2 +- .../workflows/v2/triggers/coordinator_test.go | 50 + .../workflows/v2/triggers/drainer_test.go | 8 +- core/services/workflows/v2/triggers/queue.go | 60 +- .../workflows/v2/triggers/queue_test.go | 108 + deployment/go.mod | 2 +- deployment/go.sum | 4 +- go.mod | 2 +- go.sum | 4 +- integration-tests/go.mod | 2 +- integration-tests/go.sum | 4 +- integration-tests/load/go.mod | 2 +- integration-tests/load/go.sum | 4 +- system-tests/lib/go.mod | 2 +- system-tests/lib/go.sum | 4 +- system-tests/tests/go.mod | 2 +- system-tests/tests/go.sum | 4 +- 32 files changed, 4192 insertions(+), 108 deletions(-) create mode 100644 core/services/ocr3_1/plugins/queue/config_test.go create mode 100644 core/services/ocr3_1/plugins/queue/kvstate_test.go create mode 100644 core/services/ocr3_1/plugins/queue/math_test.go create mode 100644 core/services/ocr3_1/plugins/queue/transmitter_test.go diff --git a/core/scripts/go.mod b/core/scripts/go.mod index 6c3f39af591..3fcc2bdb990 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.20261120232404-e79e51ba3b51 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7 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.20261112211734-e640e1c12078 diff --git a/core/scripts/go.sum b/core/scripts/go.sum index c50ce511c6e..5a7af3f3c9e 100644 --- a/core/scripts/go.sum +++ b/core/scripts/go.sum @@ -1686,8 +1686,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.20261120232404-e79e51ba3b51 h1:fAvMtXBFQUgk+q5I28OPg/aEIJ053mzJfChxw6hO0lM= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7 h1:YklE92DmcDaBVTWFe2woSPHE9fHQtYl+MZg6/60oYY4= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/core/services/cre/cre.go b/core/services/cre/cre.go index 8bff553b1eb..433b6011e1a 100644 --- a/core/services/cre/cre.go +++ b/core/services/cre/cre.go @@ -941,6 +941,7 @@ func newWorkflowRegistrySyncerV2( coordinatorClock, triggers.WithShadowMode(centralQueue, engineLimiters.ShadowTriggerMode), triggers.WithDrainer(centralQueueDrainer), + triggers.WithExpirationGrace(triggers.ConsensusQueueExpirationGrace(lf)), ) handlerOpts := []syncerV2.EventHandlerOption{ diff --git a/core/services/ocr3_1/plugins/queue/blobs.go b/core/services/ocr3_1/plugins/queue/blobs.go index b5fc8c5db74..f9813a4910f 100644 --- a/core/services/ocr3_1/plugins/queue/blobs.go +++ b/core/services/ocr3_1/plugins/queue/blobs.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "sort" "sync" "time" @@ -64,6 +65,16 @@ func fetchCoordinatedEventFromBlob(ctx context.Context, fetcher *blobCache, hand 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) +} + // extractEvent extracts the idx-th event from the blob, without unmarshaling any other events. func extractEvent(b []byte, idx int) (*pb.CoordinatedEvent, []byte, error) { i := 0 @@ -103,35 +114,76 @@ func extractEvent(b []byte, idx int) (*pb.CoordinatedEvent, []byte, error) { return nil, nil, fmt.Errorf("index %d out of range", idx) } -// broadcastAsBlob 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) { - protoOpts := proto.MarshalOptions{Deterministic: true} - for ; len(events) > 0 && protoOpts.Size(&pb.CoordinatedEventList{Events: events}) > c.limits.MaxBlobPayloadBytes; events = events[:len(events)-1] { - //TODO opt: binary search for largest fit instead.... - } - n = len(events) - if n == 0 { - return nil, 0, errors.New("failed to package any events in blob") +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)) } + 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 } } - roundDur := c.onchainCfg.EstimatedRoundInterval //TODO OK? pad? - //TODO pad extra time and/or rounds? - expSeqNr := seqNr + uint64(time.Until(maxDeadline)/roundDur) + // 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 := protoOpts.Marshal(&pb.CoordinatedEventList{Events: events}) + data, err := proto.MarshalOptions{Deterministic: true}.Marshal(&pb.CoordinatedEventList{Events: events}) if err != nil { - return nil, -1, fmt.Errorf("failed to marshal blob: %w", err) + 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, -1, fmt.Errorf("failed to broadcast blob: %w", err) + return nil, fmt.Errorf("failed to broadcast blob: %w", err) + } + return bh.MarshalBinary() +} + +// broadcastAsBlob 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 } - blobHandle, err = bh.MarshalBinary() - return + return blobHandle, n, nil } diff --git a/core/services/ocr3_1/plugins/queue/blobs_test.go b/core/services/ocr3_1/plugins/queue/blobs_test.go index eaa8e74fb50..e982a6e59b1 100644 --- a/core/services/ocr3_1/plugins/queue/blobs_test.go +++ b/core/services/ocr3_1/plugins/queue/blobs_test.go @@ -1,15 +1,21 @@ package queue import ( + "context" + "errors" + "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" ) @@ -85,3 +91,411 @@ func Test_coordinatedEventsFieldNumber(t *testing.T) { 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.Add(1) + go func() { + defer wg.Done() + 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()) + }) +} + +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() + var events []*pb.CoordinatedEvent + 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) + }) +} + +// 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) + } + } + }) +} + +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) + } +} diff --git a/core/services/ocr3_1/plugins/queue/config.go b/core/services/ocr3_1/plugins/queue/config.go index 7577decc80f..68b92d568ae 100644 --- a/core/services/ocr3_1/plugins/queue/config.go +++ b/core/services/ocr3_1/plugins/queue/config.go @@ -1,6 +1,9 @@ package queue import ( + "errors" + "fmt" + "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types" ) @@ -16,7 +19,31 @@ type PluginConfig struct { Limits ocr3_1types.ReportingPluginLimits `json:"limits,omitzero"` } +// Validate checks the limits are within libocr's bounds, and that this plugin can operate within them. func (c *PluginConfig) Validate() error { - // TODO validate? - return nil + if err := c.Limits.Validate(); err != nil { + return fmt.Errorf("invalid limits: %w", err) + } + var err error + positive := func(name string, v int) { + if v <= 0 { + err = errors.Join(err, fmt.Errorf("%s (%d) must be positive", name, v)) + } + } + positive("MaxObservationBytes", c.Limits.MaxObservationBytes) + positive("MaxBlobPayloadBytes", c.Limits.MaxBlobPayloadBytes) + positive("MaxKeyValueModifiedKeysPlusValuesBytes", c.Limits.MaxKeyValueModifiedKeysPlusValuesBytes) + // the quotas must admit at least one full observation's blobs, or broadcasts are rejected and events are dropped + if c.Limits.MaxPerOracleUnexpiredBlobCount < maxObservedBlobHandles { + err = errors.Join(err, fmt.Errorf("MaxPerOracleUnexpiredBlobCount (%d) must be at least %d, the blobs in a full observation", + c.Limits.MaxPerOracleUnexpiredBlobCount, maxObservedBlobHandles)) + } + if c.Limits.MaxKeyValueModifiedKeys < numKVKeys { + err = errors.Join(err, fmt.Errorf("MaxKeyValueModifiedKeys (%d) must be at least %d, the number of keys written each round", c.Limits.MaxKeyValueModifiedKeys, numKVKeys)) + } + if fullObservation := maxObservedBlobHandles * c.Limits.MaxBlobPayloadBytes; c.Limits.MaxPerOracleUnexpiredBlobCumulativePayloadBytes < fullObservation { + err = errors.Join(err, fmt.Errorf("MaxPerOracleUnexpiredBlobCumulativePayloadBytes (%d) must hold the blobs of a full observation (%d x MaxBlobPayloadBytes %d)", + c.Limits.MaxPerOracleUnexpiredBlobCumulativePayloadBytes, maxObservedBlobHandles, c.Limits.MaxBlobPayloadBytes)) + } + return err } 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..cf800c0c201 --- /dev/null +++ b/core/services/ocr3_1/plugins/queue/config_test.go @@ -0,0 +1,305 @@ +package queue + +import ( + "crypto/sha256" + "encoding/hex" + "fmt" + "math/rand" + "sort" + "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" + "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" +) + +func validLimits() ocr3_1types.ReportingPluginLimits { + return ocr3_1types.ReportingPluginLimits{ + MaxObservationBytes: ocr3_1types.MaxMaxObservationBytes, + MaxKeyValueModifiedKeys: numKVKeys, + MaxKeyValueModifiedKeysPlusValuesBytes: ocr3_1types.MaxMaxKeyValueModifiedKeysPlusValuesBytes, + MaxBlobPayloadBytes: ocr3_1types.MaxMaxBlobPayloadBytes, + MaxPerOracleUnexpiredBlobCumulativePayloadBytes: 2 * maxObservedBlobHandles * ocr3_1types.MaxMaxBlobPayloadBytes, + MaxPerOracleUnexpiredBlobCount: 100, + } +} + +func TestPluginConfig_Validate(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + mutate func(l *ocr3_1types.ReportingPluginLimits) + wantErr string // empty means valid + }{ + {name: "valid"}, + {"observation bytes unset", func(l *ocr3_1types.ReportingPluginLimits) { l.MaxObservationBytes = 0 }, "MaxObservationBytes"}, + {"observation bytes above libocr max", func(l *ocr3_1types.ReportingPluginLimits) { + l.MaxObservationBytes = ocr3_1types.MaxMaxObservationBytes + 1 + }, "out of range"}, + {"blob payload unset", func(l *ocr3_1types.ReportingPluginLimits) { l.MaxBlobPayloadBytes = 0 }, "MaxBlobPayloadBytes"}, + {"blob payload above libocr max", func(l *ocr3_1types.ReportingPluginLimits) { + l.MaxBlobPayloadBytes = ocr3_1types.MaxMaxBlobPayloadBytes + 1 + }, "out of range"}, + {"kv bytes unset", func(l *ocr3_1types.ReportingPluginLimits) { l.MaxKeyValueModifiedKeysPlusValuesBytes = 0 }, "MaxKeyValueModifiedKeysPlusValuesBytes"}, + {"too few modified keys", func(l *ocr3_1types.ReportingPluginLimits) { l.MaxKeyValueModifiedKeys = numKVKeys - 1 }, "MaxKeyValueModifiedKeys"}, + {"blob count unset", func(l *ocr3_1types.ReportingPluginLimits) { l.MaxPerOracleUnexpiredBlobCount = 0 }, "MaxPerOracleUnexpiredBlobCount"}, + {"blob count below one full observation", func(l *ocr3_1types.ReportingPluginLimits) { + l.MaxPerOracleUnexpiredBlobCount = maxObservedBlobHandles - 1 + }, "MaxPerOracleUnexpiredBlobCount"}, + {"cumulative blob bytes cannot hold a full observation", func(l *ocr3_1types.ReportingPluginLimits) { + l.MaxPerOracleUnexpiredBlobCumulativePayloadBytes = maxObservedBlobHandles*l.MaxBlobPayloadBytes - 1 + }, "MaxPerOracleUnexpiredBlobCumulativePayloadBytes"}, + {"exactly one full observation of blobs is enough", func(l *ocr3_1types.ReportingPluginLimits) { + l.MaxPerOracleUnexpiredBlobCumulativePayloadBytes = maxObservedBlobHandles * l.MaxBlobPayloadBytes + l.MaxPerOracleUnexpiredBlobCount = maxObservedBlobHandles + }, ""}, + {"negative", func(l *ocr3_1types.ReportingPluginLimits) { l.MaxObservationBytes = -1 }, "MaxObservationBytes"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + cfg := &PluginConfig{Limits: validLimits()} + if tt.mutate != nil { + tt.mutate(&cfg.Limits) + } + err := cfg.Validate() + if tt.wantErr == "" { + require.NoError(t, err) + return + } + require.ErrorContains(t, err, tt.wantErr) + }) + } + + t.Run("reports every problem", func(t *testing.T) { + t.Parallel() + err := (&PluginConfig{}).Validate() + require.Error(t, err) + for _, field := range []string{"MaxObservationBytes", "MaxBlobPayloadBytes", "MaxKeyValueModifiedKeysPlusValuesBytes", "MaxPerOracleUnexpiredBlobCount", "MaxKeyValueModifiedKeys"} { + assert.ErrorContains(t, err, field) + } + }) +} + +// The tests below calibrate the constants in config.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))}}, + } +} + +// 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 { + any, 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: any}}, + } +} + +// 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))}} + 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)) + } + e.Blobs = []*pb.CoordinatedEventBlobHandle{{Blob: uint32(rng.Intn(maxObservedBlobHandles * n)), Element: uint32(rng.Intn(maxObservedEvents))}} + 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), + float64(perRoundBlobs)*float64(rounds)*float64(ocr3_1types.MaxMaxBlobPayloadBytes)/(1<<30)) + assert.GreaterOrEqual(t, time.Duration(rounds)*roundDur, timeout+grace, "blobs must outlive their events") + } +} diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index 8566e2278b6..96ade11a5e2 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -8,6 +8,7 @@ import ( "slices" "time" + "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" @@ -16,6 +17,9 @@ import ( "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) @@ -254,10 +258,12 @@ func (s *kvState) sizeOfObservedEvents() int { } 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}) } @@ -277,7 +283,7 @@ func (s *kvState) prepareWriteObservedEvents() { for _, eventHash := range slices.SortedFunc(maps.Keys(s.observedEvents), func(a string, b string) int { ea, eb := s.observedEvents[a], s.observedEvents[b] //TODO can we use deadline here? is median valid & best option? (only have f+1) - return cmp.Or(cmp.Compare(len(eb.NodeIds), len(ea.NodeIds)), cmp.Compare(eb.ExecutionID, ea.ExecutionID)) + return cmp.Or(cmp.Compare(len(eb.NodeIds), len(ea.NodeIds)), cmp.Compare(a, b)) }) { event := s.observedEvents[eventHash] event.Blobs = nil // replace all @@ -305,7 +311,10 @@ func (s *kvState) prepareWriteBlobHandles() { s.queuedBlobHandles = nil queuedBlobIndexes := make(map[string]int) addBlobs := func(blobs map[string]uint32) []*pb.CoordinatedEventBlobHandle { - var blobHandles []*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] @@ -329,11 +338,35 @@ func (s *kvState) prepareWriteBlobHandles() { } } +// 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] +} + // 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 { //TODO MarshalOptions{UseCachedSize}? + 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) @@ -359,8 +392,9 @@ func (s *kvState) writeTo(w *stateWriter) error { func (s *kvState) pruneExpiredObservations(expiration time.Time) { maps.DeleteFunc(s.observedEvents, func(k string, v *pb.ConsensusQueueObservedEvent) bool { + // a deadline equal to the expiration is not expired, consistent with popLimited if !slices.ContainsFunc(v.Deadlines, func(t *timestamppb.Timestamp) bool { - return t.AsTime().After(expiration) + return !t.AsTime().Before(expiration) }) { return true // all deadlines expired, so delete the whole thing } @@ -384,7 +418,14 @@ func (s *kvState) pruneExpiredObservations(expiration time.Time) { // addObserved adds the observed events to the set, promoting to the priority queue on 2f+1 and calling onQueued. // Events with fewer than f+1 observations are ignored. func (s *kvState) addObservedEvents(f int, toAdd map[string]*pb.ConsensusQueueObservedEvent, observedBlobs blobHandleMap, onQueued func(event *pb.ConsensusQueueEvent)) { + alreadyQueued := make(map[string]struct{}, len(s.queuedEvents)) + for _, e := range s.queuedEvents { + alreadyQueued[string(e.TimelessHash)] = struct{}{} + } for _, eventHash := range slices.Sorted(maps.Keys(toAdd)) { + if _, ok := alreadyQueued[eventHash]; ok { + continue // already waiting for capacity; promoting it again would duplicate it + } eventToAdd := toAdd[eventHash] obsEvent, ok := s.observedEvents[eventHash] if !ok { 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..c4ebecacd9b --- /dev/null +++ b/core/services/ocr3_1/plugins/queue/kvstate_test.go @@ -0,0 +1,664 @@ +package queue + +import ( + "container/heap" + "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: blobHandleMap{}, + 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 TestPriorityQueue_RevOrder(t *testing.T) { + t.Parallel() + + pq := priorityQueue{qEvent("wf", "a", "h1", 10), qEvent("wf", "b", "h2", 30), qEvent("wf", "c", "h3", 20)} + rev := &revPriorityQueue{priorityQueue: &pq} + heap.Init(rev) + require.Equal(t, "h2", string(heap.Pop(rev).(*pb.ConsensusQueueEvent).TimelessHash), "latest deadline first") +} + +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 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)}, blobHandleMap{}, 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 := blobHandleMap{} + blobs.add("h", "blob", 0) + 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[string]uint32{"blob": 0}, s.observedBlobs["h"]) + }) + + t.Run("2f+1 goes straight to the priority queue", func(t *testing.T) { + t.Parallel() + s := newKVState() + var queued []*pb.ConsensusQueueEvent + blobs := blobHandleMap{} + blobs.add("h", "blob", 0) + 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 blob) + s.observedEvents["h"] = obsEvent("wf", "e", 100, 1, 2) + s.observedBlobs.add("h", "old-blob", 1) + + newBlobs := blobHandleMap{} + newBlobs.add("h", "new-blob", 5) + // 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{"old-blob": 1, "new-blob": 5}, s.queuedBlobs["h"]) + }) + + 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}, blobHandleMap{}, 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", "blobA", 0) + 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[string]uint32{"blobA": 0}, loaded.observedBlobs["obs"]) + 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", "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) + s.observedBlobs.add("o1", "blobA", 0) + s.observedBlobs.add("o2", "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) { + 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) { + 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", "blobX", 0) + s.observedBlobs.add("h2", "blobX", 1) + s.observedBlobs.add("h2", "blobY", 0) // two observers used different blobs + + s.prepareWriteObservedEvents() + + assert.ElementsMatch(t, [][]byte{[]byte("blobX"), []byte("blobY")}, s.observedBlobHandles) + require.Len(t, s.observedEventEntries, 2) + for _, entry := range s.observedEventEntries { + got := map[string]uint32{} + for _, b := range entry.Event.Blobs { + got[string(s.observedBlobHandles[b.Blob])] = b.Element + } + assert.Equal(t, s.observedBlobs[string(entry.TimelessHash)], got) + } +} + +// 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, blobHandleMap{}, 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)}, + blobHandleMap{}, 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)}, blobHandleMap{}, 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) +} 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/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index bce898e8037..98fac7d4b65 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -8,6 +8,7 @@ package queue import ( "bytes" + "cmp" "container/heap" "context" "crypto/sha256" @@ -22,6 +23,7 @@ import ( "github.com/smartcontractkit/libocr/commontypes" "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/offchainreporting2plus/ocr3_1types" @@ -32,7 +34,6 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb" "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/workflows/v2/triggers" @@ -69,10 +70,7 @@ func NewConsensusQueuePluginFactory( cfg: cfg, triggerCoordinator: triggerCoordinator, triggerQueue: triggerQueue, - expirationDur: func(ctx context.Context) (time.Duration, error) { - //TODO also allow this grace period in the trigger coordinator - return cresettings.Default.ConsensusQueueExpirationInterval.GetOrDefault(ctx, limitsFactory.Settings) - }, + expirationDur: triggers.ConsensusQueueExpirationGrace(limitsFactory), }, nil } @@ -173,7 +171,7 @@ func (c *consensusQueuePlugin) Observation( // Assemble an observation up to maxObservationBytes var events []*pb.CoordinatedEvent // to be broadcast protoOpts := proto.MarshalOptions{Deterministic: true} - for timelessHash, event := range c.triggerQueue.Sorted(maxObservedEvents) { + for timelessHash, event := range c.triggerQueue.Sorted(ctx, maxObservedEvents, c.maxEventBytes()) { // skip if kv observation exists already if obsEvent, ok := observedEvents[string(timelessHash)]; ok { if slices.Contains(obsEvent.NodeIds, uint8(c.onchainCfg.OracleID)) { @@ -188,8 +186,9 @@ func (c *consensusQueuePlugin) Observation( } // Check size - if protoOpts.Size(obs) > c.limits.MaxObservationBytes { + 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) @@ -197,6 +196,7 @@ func (c *consensusQueuePlugin) Observation( break } } + obs.BlobHandles = nil // remove placeholders fit, err := c.broadcastObservationBlobs(ctx, obs, blobBroadcaster, events, seqNr) if err != nil { @@ -214,6 +214,27 @@ func (c *consensusQueuePlugin) Observation( return protoOpts.Marshal(obs) } +// 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, @@ -249,6 +270,7 @@ func observeEvent( // 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 are divided between blobs first, so that the blobs can be broadcast concurrently. func (c *consensusQueuePlugin) broadcastObservationBlobs( ctx context.Context, obs *pb.ConsensusQueueObservation, blobBroadcaster ocr3_1types.BlobBroadcaster, events []*pb.CoordinatedEvent, seqNr uint64, @@ -260,33 +282,63 @@ func (c *consensusQueuePlugin) broadcastObservationBlobs( return false, fmt.Errorf("number of events and observedEvents must match") } - blobHandle, n, err := c.broadcastAsBlob(ctx, blobBroadcaster, events, seqNr) - if err != nil { - return false, err + // ends[i] is the index after the last event of blob i. We verified space for maxObservedBlobHandles handles. + var ends []int + for start := 0; start < len(events) && len(ends) < maxObservedBlobHandles; { + n := c.blobPrefix(events[start:]) + if n == 0 { + break + } + start += n + ends = append(ends, start) + } + if len(ends) == 0 { + c.lggr.Warnw("No events fit in a blob - omitting events from observation", "events", len(events), "blobLimit", c.limits.MaxBlobPayloadBytes) + obs.Events = obs.Events[:0] + return false, nil + } + + handles := make([][]byte, len(ends)) + errs := make([]error, len(ends)) + var eg errgroup.Group + for i, start := 0, 0; i < len(ends); i++ { + batch := events[start:ends[i]] + start = ends[i] + eg.Go(func() error { + handles[i], errs[i] = c.broadcastBlob(ctx, blobBroadcaster, batch, seqNr) + return nil + }) + } + _ = eg.Wait() + if err := ctx.Err(); err != nil { + return false, err // cancelled, so there is no point in observing at all } - obs.BlobHandles = append(obs.BlobHandles, blobHandle) - // note: elements already reference blob 0 and natural element index is aligned - // we verified space for up to maxObservedBlobHandles blobs - lastEnd := n - events = events[n:] - for batch := 1; batch < maxObservedBlobHandles && len(events) > 0; batch++ { - blobHandle, n, err = c.broadcastAsBlob(ctx, blobBroadcaster, events, seqNr) + // Keep the blobs before the first failure. A failed broadcast must not fail Observation (see libocr + // BlobBroadcaster), so observe without the events that did not make it. + keep := len(ends) + for i, err := range errs { if err != nil { - return false, err + c.lggr.Warnw("Failed to broadcast events blob - omitting it and the remaining events from observation", "blob", i, "err", err) + keep = i + break } - obs.BlobHandles = append(obs.BlobHandles, blobHandle) - for i := 0; i < n; i++ { // update indices - obs.Events[lastEnd+i].Blobs[0].Blob = uint32(batch) - obs.Events[lastEnd+i].Blobs[0].Element = uint32(i) + } + if keep == 0 { + obs.Events = obs.Events[:0] + return false, nil + } + + obs.BlobHandles = append(obs.BlobHandles, handles[:keep]...) + for i, start := 0, 0; i < keep; i++ { // point every event at its blob and element + for j, e := range obs.Events[start:ends[i]] { + e.Blobs[0].Blob, e.Blobs[0].Element = uint32(i), uint32(j) } - lastEnd += n - events = events[n:] + start = ends[i] } - limited := lastEnd < len(obs.Events) + limited := ends[keep-1] < len(obs.Events) if limited { - // we hit max blobs, so drop excess events - obs.Events = obs.Events[:lastEnd] + obs.Events = obs.Events[:ends[keep-1]] // drop the events that did not fit in the blobs, or whose blob failed // note: caller will fix wfCapacity } return !limited, nil @@ -294,7 +346,7 @@ func (c *consensusQueuePlugin) broadcastObservationBlobs( func (c *consensusQueuePlugin) ValidateObservation( ctx context.Context, _ uint64, _ ocrtypes.AttributedQuery, ao ocrtypes.AttributedObservation, - _ ocr3_1types.KeyValueStateReader, blobFetcher ocr3_1types.BlobFetcher, + kvReader ocr3_1types.KeyValueStateReader, blobFetcher ocr3_1types.BlobFetcher, ) error { var obs pb.ConsensusQueueObservation err := proto.Unmarshal(ao.Observation, &obs) @@ -307,7 +359,14 @@ func (c *consensusQueuePlugin) ValidateObservation( if obs.Expiration == nil { return errors.New("expiration is missing") } - //TODO what do we expect from WF capacities? check KV state and insist 100% match? or subset - none extra? + 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 len(obs.Events) > maxObservedEvents { return fmt.Errorf("events are limited to %d but got %d", maxObservedEvents, len(obs.Events)) @@ -332,7 +391,32 @@ func (c *consensusQueuePlugin) ValidateObservation( return fmt.Errorf("missing capacity for workflow ID %s", event.WorkflowID) } } - //TODO ensure map only contains wfs from observations and KV observed+queued events + + // 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) + } + } // ensure no duplicate execution ID or timelessHash execIDs, timelessHashes := make(map[string]struct{}), make(map[string]struct{}) @@ -360,19 +444,25 @@ func (c *consensusQueuePlugin) ValidateObservation( func validateObservedEvent(ctx context.Context, fetcher *blobCache, event *pb.ConsensusQueueEvent, blobHandles [][]byte) error { if event.WorkflowID == "" { return errors.New("event workflow id is missing") - } ///TODO check not too long - exact length? + } // TODO ensure not too long if event.ExecutionID == "" { - return errors.New("event execution id is missing") - } ///TODO check not too long - exact length? + 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 event.TimelessHash == nil { + if len(event.TimelessHash) == 0 { return fmt.Errorf("event blob hash is missing") - } ///TODO check not too long - exact length? + } 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 fmt.Errorf("event blob is missing") @@ -397,7 +487,7 @@ func validateObservedEvent(ctx context.Context, fetcher *blobCache, event *pb.Co 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().Id, int(coordEvent.TriggerIndex)) + 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) } @@ -445,14 +535,11 @@ func (c *consensusQueuePlugin) StateTransition( return nil, fmt.Errorf("failed to read state: %w", err) } - // wait for aggregation + // wait for aggregation, which reports cancellation as its error, so a partial result is never used select { case <-ctx.Done(): return nil, ctx.Err() case <-done: - if err = ctx.Err(); err != nil { - return nil, err - } } if obs.err != nil { return nil, fmt.Errorf("failed to aggregate observations: %w", obs.err) @@ -471,16 +558,11 @@ func (c *consensusQueuePlugin) StateTransition( break } state.consensusEvents = append(state.consensusEvents, event) - // stop when either value or the overall size is too large - if events, blobs := state.sizeOfConsensusEvents(), state.sizeOfBlobHandles(); events > maxKeyValueValueBytes || - blobs > maxKeyValueValueBytes || events+blobs > c.limits.MaxKeyValueModifiedKeysPlusValuesBytes/2 { - state.queuedEvents.push(event) - state.consensusEvents = state.consensusEvents[:len(state.consensusEvents)-1] - break - } } + state.trimConsensusEvents(c.limits.MaxKeyValueModifiedKeysPlusValuesBytes) // prune observations if that value or the overall size is too large + state.prepareWriteObservedEvents() // populates the (priority sorted) entries to prune from for len(state.observedEventEntries) > 0 && (state.sizeOfObservedEvents() > maxKeyValueValueBytes || state.sizeOf() > c.limits.MaxKeyValueModifiedKeysPlusValuesBytes) { @@ -547,11 +629,23 @@ type observations struct { func (res *observations) aggregate(ctx context.Context, f int, aos []ocrtypes.AttributedObservation) { res.medianCapPerWF = make(map[string]uint32) res.newObservedEvents = make(map[string]*pb.ConsensusQueueObservedEvent) + res.observedBlobs = make(blobHandleMap) + + // 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)) 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 { @@ -564,7 +658,8 @@ func (res *observations) aggregate(ctx context.Context, f int, aos []ocrtypes.At wfCapacities[wf] = append(wfCapacities[wf], c) } for _, event := range obs.Events { - if ctx.Err() != nil { + if err2 := ctx.Err(); err2 != nil { + res.err = err2 return } res.addEvent(ao.Observer, event, obs.BlobHandles) @@ -574,12 +669,12 @@ func (res *observations) aggregate(ctx context.Context, f int, aos []ocrtypes.At // 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. - //TODO fill zeros for missing nodes? res.medianCap = slices.Sorted(slices.Values(capacities))[f] for wf, caps := range wfCapacities { - if len(caps) >= 2*f+1 { - res.medianCapPerWF[wf] = slices.Sorted(slices.Values(caps))[f] - } + // 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.medianCapPerWF[wf] = slices.Sorted(slices.Values(caps))[f] } return } @@ -612,6 +707,9 @@ func (c *consensusQueuePlugin) Committed(ctx context.Context, _ uint64, kvReader } // 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 { @@ -697,6 +795,7 @@ func (c *consensusQueuePlugin) tryStartExecution(ctx context.Context, fetcher *b } //TODO ensure this only *starts* the execution, and does not block while it runs + // TestCommitted_DoesNotWaitForExecutions return c.triggerCoordinator.StartExecution(ctx, event) } diff --git a/core/services/ocr3_1/plugins/queue/queue_test.go b/core/services/ocr3_1/plugins/queue/queue_test.go index 59776538160..39bcb0e7e07 100644 --- a/core/services/ocr3_1/plugins/queue/queue_test.go +++ b/core/services/ocr3_1/plugins/queue/queue_test.go @@ -1,18 +1,38 @@ package queue import ( + "bytes" + "cmp" "context" + "crypto/sha256" + "errors" + "fmt" "iter" + "maps" + "math" + "math/rand" + "slices" + "sort" + "strings" + "sync" + "sync/atomic" "testing" + "time" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "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/limits" + "github.com/smartcontractkit/chainlink-common/pkg/workflows" "github.com/smartcontractkit/chainlink/v2/core/services/workflows/v2/triggers" ) @@ -93,6 +113,2158 @@ func (n noopQueue) Stats(ctx context.Context) (triggers.Stats, error) { return triggers.Stats{}, nil } -func (n noopQueue) Sorted(int) iter.Seq2[[]byte, *pb.CoordinatedEvent] { return 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 +} + +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 { + 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) +} + +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{"wf": 5})), + mkAO(1, base(1, map[string]uint32{"wf": 1})), + mkAO(2, base(7, map[string]uint32{"wf": 9})), + }) + require.NoError(t, res.err) + assert.Equal(t, uint32(7), res.medianCap, "F+1th lowest of 1,7,10") + assert.Equal(t, uint32(5), res.medianCapPerWF["wf"], "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.medianCap) + }) + + 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, "wf", "evt") + mkObs := func() *pb.ConsensusQueueObservation { + o := base(5, map[string]uint32{"wf": 5}) + o.BlobHandles = [][]byte{[]byte("handle")} + _, err := observeEvent(o, hash, proto.CloneOf(event), map[string]int{"wf": 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[string]uint32{"handle": 0}, res.observedBlobs[string(hash)]) + }) +} + +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{}} + var events []*pb.CoordinatedEvent + for _, id := range []string{"a", "b", "c"} { + h, e := newCoordinatedEvent(t, "wf", 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, "wf", "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() + + var events []hashedEvent + for _, id := range []string{"a", "b"} { + h, e := newCoordinatedEvent(t, "wf", 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.Zero(t, len(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() + + var events []hashedEvent + for _, id := range []string{"a", "b", "c"} { + h, e := newCoordinatedEvent(t, "wf", 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, "wf", "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: "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"}, + {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 = "other" }, 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, "wf", "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, "wf", "evt") + for _, ce := range []*pb.CoordinatedEvent{ + {WorkflowID: "wf"}, // no Event + {WorkflowID: "wf", 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() + var events []hashedEvent + for i := range n { + h, e := newCoordinatedEvent(t, "wf", 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, "wf") }, 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 but are not bound to the honest value. + // These document the open TODOs in ValidateObservation; they fail until each field is bounded. + 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 +} + +var stdNode = nodeOpts{capacity: 10, wfCaps: map[string]uint32{"wf": 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), + } + 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} +} + +// mkEvents makes n events for workflow "wf" with deadlines base, base+1, ... +func mkEvents(t testing.TB, n int, base int64) []hashedEvent { + t.Helper() + var out []hashedEvent + for i := range n { + h, e := newCoordinatedEvent(t, "wf", 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("wf", 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.T, 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) + var ids []string + 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) + var ids []string + 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[string]uint32{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{"wf": 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{"wf": 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{"wf": 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{"wf": 2}, expiration: 90}, pick(0, 1, 2)...)), + ao(t, 1, nodeObs(t, nodeOpts{capacity: 5, wfCaps: map[string]uint32{"wf": 3}, expiration: 95}, pick(0, 1, 3)...)), + ao(t, 2, nodeObs(t, nodeOpts{capacity: 4, wfCaps: map[string]uint32{"wf": 9}, expiration: 99}, pick(0, 2, 3, 4, 5)...)), + ao(t, 3, nodeObs(t, nodeOpts{capacity: 9, wfCaps: map[string]uint32{"wf": 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 + var all []string + for _, ev := range e { + all = append(all, string(ev.hash)) + } + slices.Sort(all) + var kept []string + 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{"wf": 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) + var want []string + 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{"wf": 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 + block chan struct{} // if set, StartExecution blocks until closed (like a running workflow) + 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 { + if r.block != nil { + <-r.block + } + 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) + 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() + var ces []*pb.CoordinatedEvent + for i, id := range append(append([]string(nil), consensus...), queued...) { + ce, qe := blobEvent(t, "wf", 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, "wf", 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, "wf", "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) + }) +} + +// Executions must only be *started* on the OCR call path: a workflow that runs for a long time must not hold up the round. +// (Open issue: commitState currently waits for every StartExecution to return.) +func TestCommitted_DoesNotWaitForExecutions(t *testing.T) { + t.Parallel() + + coord, blobs, kv := &recCoordinator{block: make(chan struct{})}, &memBlobs{}, memKV{} + c := newCommitPlugin(t, coord, &recQueue{}, blobs) + seedKV(t, kv, blobs, []string{"a"}, nil) + + done := make(chan error, 1) + go func() { done <- c.Committed(t.Context(), 1, kv) }() + t.Cleanup(func() { close(coord.block) }) // always release the "workflow" + + select { + case err := <-done: + require.NoError(t, err) + case <-time.After(time.Second): + t.Fatal("Committed blocked on a running workflow execution") + } +} + +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("wf", "m0", 100, 0, 1) // includes OracleID 0 (this node) + s.observedEvents[string(mine[1].hash)] = obsEvent("wf", "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) + var got [][]byte + 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, int64(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, "wf") + }) + + 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, int64(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, int64(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, "wf", "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(fmt.Sprint(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{"wf": 9}), mk(map[string]uint32{"wf": 9}), mk(nil))) + require.NoError(t, res.err) + assert.Equal(t, uint32(9), res.medianCapPerWF["wf"], "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{"wf": 9}), mk(nil), mk(nil))) + require.NoError(t, res.err) + assert.Contains(t, res.medianCapPerWF, "wf") + assert.Zero(t, res.medianCapPerWF["wf"]) + }) + + 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() + + cfg := &PluginConfig{} + tests := []struct { + name string + cfg *PluginConfig + coord triggers.Coordinator + queue triggers.Queue + }{ + {"nil cfg", nil, noopCoordinator{}, noopQueue{}}, + {"nil coordinator", cfg, nil, noopQueue{}}, + {"nil queue", cfg, noopCoordinator{}, nil}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + f, err := NewConsensusQueuePluginFactory(logger.Test(t), tt.cfg, limits.Factory{}, tt.coord, tt.queue) + require.Error(t, err) + 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, int64(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{ memBlobs } + +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, int64(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, int64(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, int64(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 blob fails: nothing observed", 0, 0}, + {"middle blob fails: only the events before it are kept", 2, 2}, + {"last blob fails", 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) + for i, e := range obs.Events { + assert.Equal(t, ev[i].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) + } + if tt.wantEvents > 0 { + assert.Contains(t, obs.WorkflowCapacities, "wf", "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("wf", 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)))) + } + 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") + }) +} 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..25150404aa5 100644 --- a/core/services/workflows/monitoring/central_trigger_queue_metrics.go +++ b/core/services/workflows/monitoring/central_trigger_queue_metrics.go @@ -14,6 +14,8 @@ 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" ) // CentralTriggerQueueMetrics are the central trigger queue's instruments. They are separate from diff --git a/core/services/workflows/v2/triggers/coordinator.go b/core/services/workflows/v2/triggers/coordinator.go index f12ced66992..78298770be9 100644 --- a/core/services/workflows/v2/triggers/coordinator.go +++ b/core/services/workflows/v2/triggers/coordinator.go @@ -157,6 +157,9 @@ 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) + // shadow is nil unless WithShadowMode is set. shadow *shadowMode // drainer is nil unless WithDrainer is set. @@ -242,6 +245,34 @@ 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) + } +} + +// 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. // @@ -664,7 +695,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) { //TODO grace period + 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) diff --git a/core/services/workflows/v2/triggers/coordinator_shadow_test.go b/core/services/workflows/v2/triggers/coordinator_shadow_test.go index c5f4e68ceab..a13f453f311 100644 --- a/core/services/workflows/v2/triggers/coordinator_shadow_test.go +++ b/core/services/workflows/v2/triggers/coordinator_shadow_test.go @@ -335,7 +335,7 @@ type failingQueue struct { puts atomic.Int32 } -func (q *failingQueue) Sorted(int) iter.Seq2[[]byte, *pb.CoordinatedEvent] { +func (q *failingQueue) Sorted(context.Context, int, int) iter.Seq2[[]byte, *pb.CoordinatedEvent] { return func(yield func([]byte, *pb.CoordinatedEvent) bool) {} } diff --git a/core/services/workflows/v2/triggers/coordinator_test.go b/core/services/workflows/v2/triggers/coordinator_test.go index 13b47858455..f22bbc722b6 100644 --- a/core/services/workflows/v2/triggers/coordinator_test.go +++ b/core/services/workflows/v2/triggers/coordinator_test.go @@ -857,6 +857,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} diff --git a/core/services/workflows/v2/triggers/drainer_test.go b/core/services/workflows/v2/triggers/drainer_test.go index 047d16e307c..7d7f6256d92 100644 --- a/core/services/workflows/v2/triggers/drainer_test.go +++ b/core/services/workflows/v2/triggers/drainer_test.go @@ -2,6 +2,7 @@ package triggers import ( "context" + "crypto/sha256" "errors" "iter" "slices" @@ -62,7 +63,7 @@ type fakeQueue struct { drainCalls int } -func (q *fakeQueue) Sorted(limit int) iter.Seq2[[]byte, *pb.CoordinatedEvent] { +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() @@ -144,9 +145,10 @@ func centralQueueEvents(t *testing.T, events []CoordinatedEvent) []centralQueueE CoordinatedEvent: e, pb: pbe, timelessHash: func() []byte { - hash, err := pbe.TimelessHash() + b, err := pbe.MarshalTimeless() require.NoError(t, err) - return hash + hash := sha256.Sum256(b) + return hash[:] }(), executionID: func() string { execID, err := workflows.GenerateExecutionIDWithTriggerIndex(e.WorkflowID, e.Event.Event.ID, e.TriggerIndex) diff --git a/core/services/workflows/v2/triggers/queue.go b/core/services/workflows/v2/triggers/queue.go index e7e2b47fde1..6c85947faec 100644 --- a/core/services/workflows/v2/triggers/queue.go +++ b/core/services/workflows/v2/triggers/queue.go @@ -5,6 +5,7 @@ import ( "cmp" "container/heap" "context" + "crypto/sha256" "errors" "fmt" "iter" @@ -41,7 +42,10 @@ type Queue interface { Stats(context.Context) (Stats, error) // Sorted returns a sorted iterator over events, up to limit. Events remain but can be removed via Remove. - Sorted(limit int) iter.Seq2[[]byte, *pb.CoordinatedEvent] + // 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. //TODO can't ack with trigger event ID - not unique! @@ -83,6 +87,7 @@ type centralQueueEvent struct { 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 { @@ -116,10 +121,11 @@ func (q *CentralQueue) Put(ctx context.Context, e CoordinatedEvent) error { return ErrQueueFull } pbe := e.ToProto() - timelessHash, err := pbe.TimelessHash() + 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 compute timeless hash: %w", err) + 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) @@ -127,8 +133,9 @@ func (q *CentralQueue) Put(ctx context.Context, e CoordinatedEvent) error { q.events = append(q.events, centralQueueEvent{ CoordinatedEvent: e, pb: pbe, - timelessHash: timelessHash, + timelessHash: timelessHash[:], executionID: execID, + blobSize: len(timelessBytes), }) q.depthByWorkflow[e.WorkflowID]++ q.depthByTriggerType[e.TriggerCapID]++ @@ -187,7 +194,7 @@ func (q *CentralQueue) Remove(ctx context.Context, executionIDs iter.Seq[string] return } -func (q *CentralQueue) Sorted(limit int) iter.Seq2[[]byte, *pb.CoordinatedEvent] { +func (q *CentralQueue) Sorted(ctx context.Context, limit, maxEventBytes int) iter.Seq2[[]byte, *pb.CoordinatedEvent] { q.mu.Lock() events := priorityQueue(slices.Clone(q.events)) q.mu.Unlock() @@ -195,8 +202,18 @@ func (q *CentralQueue) Sorted(limit int) iter.Seq2[[]byte, *pb.CoordinatedEvent] heap.Init(&events) return func(yield func([]byte, *pb.CoordinatedEvent) bool) { - for count := 0; events.Len() > 0 && count < limit; count++ { + // 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 } @@ -204,6 +221,37 @@ func (q *CentralQueue) Sorted(limit int) iter.Seq2[[]byte, *pb.CoordinatedEvent] } } +// dropOversize removes the events from the queue, if they are still there. +// TODO should we fall back to executing instead of just dropping? +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)) + } +} + // 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) diff --git a/core/services/workflows/v2/triggers/queue_test.go b/core/services/workflows/v2/triggers/queue_test.go index c0d531a3b8a..8f34e6dad00 100644 --- a/core/services/workflows/v2/triggers/queue_test.go +++ b/core/services/workflows/v2/triggers/queue_test.go @@ -3,6 +3,7 @@ package triggers import ( "context" "fmt" + "strings" "sync" "testing" "time" @@ -12,6 +13,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" @@ -477,3 +479,109 @@ 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.Len(t, ids(q, 10, maxSmall-1), 0, "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) + }) +} diff --git a/deployment/go.mod b/deployment/go.mod index c9aecd408f9..f2d6bb69f9f 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.20261120232404-e79e51ba3b51 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7 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 c5ce3e5572b..e6963895ea0 100644 --- a/deployment/go.sum +++ b/deployment/go.sum @@ -1411,8 +1411,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.20261120232404-e79e51ba3b51 h1:fAvMtXBFQUgk+q5I28OPg/aEIJ053mzJfChxw6hO0lM= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7 h1:YklE92DmcDaBVTWFe2woSPHE9fHQtYl+MZg6/60oYY4= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/go.mod b/go.mod index f4a2c2c2232..4c814d66dba 100644 --- a/go.mod +++ b/go.mod @@ -82,7 +82,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.20261120232404-e79e51ba3b51 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 github.com/smartcontractkit/chainlink-data-streams v1.1.3 diff --git a/go.sum b/go.sum index 9211689afd5..9e99f147ded 100644 --- a/go.sum +++ b/go.sum @@ -1102,8 +1102,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.20261120232404-e79e51ba3b51 h1:fAvMtXBFQUgk+q5I28OPg/aEIJ053mzJfChxw6hO0lM= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7 h1:YklE92DmcDaBVTWFe2woSPHE9fHQtYl+MZg6/60oYY4= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/integration-tests/go.mod b/integration-tests/go.mod index d5c69124011..cd4ec88fca8 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.20261120232404-e79e51ba3b51 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7 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.20261112211734-e640e1c12078 diff --git a/integration-tests/go.sum b/integration-tests/go.sum index 88dd53de619..0291c887708 100644 --- a/integration-tests/go.sum +++ b/integration-tests/go.sum @@ -1396,8 +1396,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.20261120232404-e79e51ba3b51 h1:fAvMtXBFQUgk+q5I28OPg/aEIJ053mzJfChxw6hO0lM= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7 h1:YklE92DmcDaBVTWFe2woSPHE9fHQtYl+MZg6/60oYY4= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/integration-tests/load/go.mod b/integration-tests/load/go.mod index f984a0976e8..5a7a9ab1c7a 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.20261120232404-e79e51ba3b51 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7 github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261112211734-e640e1c12078 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 6aef7c226dd..ddebc853988 100644 --- a/integration-tests/load/go.sum +++ b/integration-tests/load/go.sum @@ -1636,8 +1636,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.20261120232404-e79e51ba3b51 h1:fAvMtXBFQUgk+q5I28OPg/aEIJ053mzJfChxw6hO0lM= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7 h1:YklE92DmcDaBVTWFe2woSPHE9fHQtYl+MZg6/60oYY4= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/system-tests/lib/go.mod b/system-tests/lib/go.mod index eab206eb19c..6c44cc3200d 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.20261120232404-e79e51ba3b51 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7 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 d60af6ea747..2687e3dec0f 100644 --- a/system-tests/lib/go.sum +++ b/system-tests/lib/go.sum @@ -1657,8 +1657,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.20261120232404-e79e51ba3b51 h1:fAvMtXBFQUgk+q5I28OPg/aEIJ053mzJfChxw6hO0lM= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7 h1:YklE92DmcDaBVTWFe2woSPHE9fHQtYl+MZg6/60oYY4= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/system-tests/tests/go.mod b/system-tests/tests/go.mod index b4574d794c6..e71f44fdf02 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.20261120232404-e79e51ba3b51 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 github.com/smartcontractkit/chainlink-confidential-compute v1.3.0 diff --git a/system-tests/tests/go.sum b/system-tests/tests/go.sum index 5ae692fb4bf..002af4b9143 100644 --- a/system-tests/tests/go.sum +++ b/system-tests/tests/go.sum @@ -1836,8 +1836,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.20261120232404-e79e51ba3b51 h1:fAvMtXBFQUgk+q5I28OPg/aEIJ053mzJfChxw6hO0lM= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261120232404-e79e51ba3b51/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7 h1:YklE92DmcDaBVTWFe2woSPHE9fHQtYl+MZg6/60oYY4= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= From d6961fc94723fe6d285d694188ceaa1d1434c8cd Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Sun, 22 Nov 2026 09:47:45 -0600 Subject: [PATCH 20/38] cleanup --- core/services/ocr3_1/plugins/queue/blobs.go | 32 +-- .../ocr3_1/plugins/queue/blobs_test.go | 16 ++ core/services/ocr3_1/plugins/queue/config.go | 5 + core/services/ocr3_1/plugins/queue/kvstate.go | 103 ++++++++++ core/services/ocr3_1/plugins/queue/math.go | 3 + core/services/ocr3_1/plugins/queue/queue.go | 192 ++++++++---------- 6 files changed, 224 insertions(+), 127 deletions(-) diff --git a/core/services/ocr3_1/plugins/queue/blobs.go b/core/services/ocr3_1/plugins/queue/blobs.go index f9813a4910f..4350d528c8f 100644 --- a/core/services/ocr3_1/plugins/queue/blobs.go +++ b/core/services/ocr3_1/plugins/queue/blobs.go @@ -2,7 +2,6 @@ package queue import ( "context" - "errors" "fmt" "sort" "sync" @@ -30,6 +29,7 @@ func (c *blobCache) fetchBlob(ctx context.Context, handle []byte) ([]byte, error c.mu.RUnlock() return fn() } + c.mu.RUnlock() c.mu.Lock() @@ -37,13 +37,16 @@ func (c *blobCache) fetchBlob(ctx context.Context, handle []byte) ([]byte, error 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() @@ -60,6 +63,7 @@ func fetchCoordinatedEventFromBlob(ctx context.Context, fetcher *blobCache, hand if err != nil { return nil, nil, err } + return coordEvent, eb, nil } @@ -83,22 +87,27 @@ func extractEvent(b []byte, idx int) (*pb.CoordinatedEvent, []byte, error) { if n < 0 { return nil, nil, protowire.ParseError(n) } + b = b[n:] if num == coordinatedEventsFieldNumber { if typ != protowire.BytesType { return nil, nil, fmt.Errorf("expected bytes type for field %d, got %d", coordinatedEventsFieldNumber, typ) } + v, m := protowire.ConsumeBytes(b) if m < 0 { return nil, nil, protowire.ParseError(m) } + if i == idx { var event pb.CoordinatedEvent if err := proto.Unmarshal(v, &event); err != nil { return nil, v, fmt.Errorf("failed to unmarshal event: %w", err) } + return &event, v, nil } + // advance i++ b = b[m:] @@ -108,9 +117,11 @@ func extractEvent(b []byte, idx int) (*pb.CoordinatedEvent, []byte, error) { if n < 0 { return nil, nil, protowire.ParseError(n) } + b = b[n:] } } + return nil, nil, fmt.Errorf("index %d out of range", idx) } @@ -137,6 +148,7 @@ func blobExpirySeqNr(seqNr uint64, remaining, roundDur time.Duration) uint64 { lifetime := max(0, remaining) + minBlobLifetime rounds = max(rounds, uint64((lifetime+roundDur-1)/roundDur)) } + return seqNr + rounds } @@ -156,34 +168,24 @@ func (c *consensusQueuePlugin) broadcastBlob(ctx context.Context, broadcaster oc 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() -} -// broadcastAsBlob 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 + 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 index e982a6e59b1..15415762037 100644 --- a/core/services/ocr3_1/plugins/queue/blobs_test.go +++ b/core/services/ocr3_1/plugins/queue/blobs_test.go @@ -499,3 +499,19 @@ func TestBroadcastAsBlob_GraceIsOptional(t *testing.T) { assert.InDelta(t, tt.want, int(blobs.hints[0].(ocr3_1types.BlobExpirationHintSequenceNumber).SeqNr), 1, tt.name) } } + +// 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 +} diff --git a/core/services/ocr3_1/plugins/queue/config.go b/core/services/ocr3_1/plugins/queue/config.go index 68b92d568ae..1eb16ffc84b 100644 --- a/core/services/ocr3_1/plugins/queue/config.go +++ b/core/services/ocr3_1/plugins/queue/config.go @@ -24,12 +24,14 @@ func (c *PluginConfig) Validate() error { if err := c.Limits.Validate(); err != nil { return fmt.Errorf("invalid limits: %w", err) } + var err error positive := func(name string, v int) { if v <= 0 { err = errors.Join(err, fmt.Errorf("%s (%d) must be positive", name, v)) } } + positive("MaxObservationBytes", c.Limits.MaxObservationBytes) positive("MaxBlobPayloadBytes", c.Limits.MaxBlobPayloadBytes) positive("MaxKeyValueModifiedKeysPlusValuesBytes", c.Limits.MaxKeyValueModifiedKeysPlusValuesBytes) @@ -38,12 +40,15 @@ func (c *PluginConfig) Validate() error { err = errors.Join(err, fmt.Errorf("MaxPerOracleUnexpiredBlobCount (%d) must be at least %d, the blobs in a full observation", c.Limits.MaxPerOracleUnexpiredBlobCount, maxObservedBlobHandles)) } + if c.Limits.MaxKeyValueModifiedKeys < numKVKeys { err = errors.Join(err, fmt.Errorf("MaxKeyValueModifiedKeys (%d) must be at least %d, the number of keys written each round", c.Limits.MaxKeyValueModifiedKeys, numKVKeys)) } + if fullObservation := maxObservedBlobHandles * c.Limits.MaxBlobPayloadBytes; c.Limits.MaxPerOracleUnexpiredBlobCumulativePayloadBytes < fullObservation { err = errors.Join(err, fmt.Errorf("MaxPerOracleUnexpiredBlobCumulativePayloadBytes (%d) must hold the blobs of a full observation (%d x MaxBlobPayloadBytes %d)", c.Limits.MaxPerOracleUnexpiredBlobCumulativePayloadBytes, maxObservedBlobHandles, c.Limits.MaxBlobPayloadBytes)) } + return err } diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index 96ade11a5e2..208b55fa38d 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -41,6 +41,7 @@ func (s *stateWriter) writeValue[M proto.Message](key string, m M) error { if err != nil { return fmt.Errorf("failed to marshal %T: %w", m, err) } + return s.kv.Write([]byte(key), val) } @@ -53,6 +54,7 @@ func (p *priorityQueue) Len() int { if p == nil { return 0 } + return len(*p) } @@ -73,6 +75,7 @@ func (p *priorityQueue) Pop() any { if p.Len() == 0 { return nil } + e := (*p)[len(*p)-1] *p = (*p)[:len(*p)-1] return e @@ -89,6 +92,7 @@ func (s *kvState) queueObservations(timelessHash string, obs *pb.ConsensusQueueO TimelessHash: []byte(timelessHash), // note: observedBlobs tracks blobs while in memory } + s.queuedEvents.push(event) return event } @@ -99,6 +103,7 @@ func (p *priorityQueue) mustPop() *pb.ConsensusQueueEvent { if p.Len() == 0 { return nil } + return heap.Pop(p).(*pb.ConsensusQueueEvent) } @@ -111,22 +116,27 @@ func (p *priorityQueue) popLimited(capPerWF map[string]uint32, expiration time.T 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 } @@ -145,6 +155,7 @@ 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 } @@ -152,6 +163,7 @@ func (m blobHandleMap) addAll(eventHash string, blobHandles map[string]uint32) { if _, ok := m[eventHash]; !ok { m[eventHash] = make(map[string]uint32) } + for blobHandle, elementIndex := range blobHandles { m[eventHash][blobHandle] = elementIndex } @@ -185,6 +197,7 @@ func (s *kvState) loadFrom(kv ocr3_1types.KeyValueStateReadWriter) error { if err != nil { return err } + s.queuedEvents = queuedEvents s.queuedBlobs = make(blobHandleMap) @@ -192,6 +205,7 @@ func (s *kvState) loadFrom(kv ocr3_1types.KeyValueStateReadWriter) error { if err != nil { return err } + for _, event := range s.queuedEvents { for _, blob := range event.GetBlobs() { s.queuedBlobs.add(string(event.TimelessHash), string(queuedBlobs[blob.Blob]), blob.Element) @@ -206,13 +220,16 @@ func readQueuedEvents(kv ocr3_1types.KeyValueStateReader) ([]*pb.ConsensusQueueE 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 } @@ -221,16 +238,19 @@ func readObservedEvents(kv ocr3_1types.KeyValueStateReader) (observedEvents map[ if err != nil { return nil, nil, fmt.Errorf("failed to read observed events: %w", err) } + observedBlobs = make(blobHandleMap) 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 { for _, b := range event.GetBlobs() { @@ -240,6 +260,7 @@ func readObservedEvents(kv ocr3_1types.KeyValueStateReader) (observedEvents map[ } else { observedEvents = make(map[string]*pb.ConsensusQueueObservedEvent) } + return } @@ -295,11 +316,13 @@ func (s *kvState) prepareWriteObservedEvents() { observedBlobIndexes[blobHandle] = idx s.observedBlobHandles = append(s.observedBlobHandles, []byte(blobHandle)) } + event.Blobs = append(event.Blobs, &pb.CoordinatedEventBlobHandle{ Blob: uint32(idx), Element: ei, }) } + s.observedEventEntries = append(s.observedEventEntries, &pb.ConsensusQueueObservedEventEntry{ TimelessHash: []byte(eventHash), Event: event}) } @@ -314,6 +337,7 @@ func (s *kvState) prepareWriteBlobHandles() { if len(blobs) == 0 { return nil } + blobHandles := make([]*pb.CoordinatedEventBlobHandle, 0, len(blobs)) for _, blobHandle := range slices.Sorted(maps.Keys(blobs)) { ei := blobs[blobHandle] @@ -323,16 +347,20 @@ func (s *kvState) prepareWriteBlobHandles() { queuedBlobIndexes[blobHandle] = idx s.queuedBlobHandles = append(s.queuedBlobHandles, []byte(blobHandle)) } + blobHandles = append(blobHandles, &pb.CoordinatedEventBlobHandle{ Blob: uint32(idx), 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)]) } @@ -351,14 +379,82 @@ func (s *kvState) trimConsensusEvents(maxTotalBytes int) { 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] } +// 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) { + for len(s.queuedEvents) > 0 && len(s.consensusEvents) < capacity { + event := s.queuedEvents.popLimited(capPerWF, expiration) + if event == nil { + break + } + + s.consensusEvents = append(s.consensusEvents, event) + } + + s.trimConsensusEvents(maxTotalBytes) +} + +// pruneObservedToFit drops the lowest priority observed events until that value, and the overall size, fit. +func (s *kvState) pruneObservedToFit(maxTotalBytes int) { + s.prepareWriteObservedEvents() // populates the (priority sorted) entries to prune from + for len(s.observedEventEntries) > 0 && + (s.sizeOfObservedEvents() > maxKeyValueValueBytes || s.sizeOf() > maxTotalBytes) { + // sorted by decreasing priority, so prune the last + toRemove := s.observedEventEntries[len(s.observedEventEntries)-1] + delete(s.observedEvents, string(toRemove.TimelessHash)) + //TODO opt: drop more than one each time? + } +} + +// pruneQueuedToFit drops the lowest priority events of those that were newly queued until the queued events, the blob +// handles, and the overall size fit. +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) + } + } + + backwardsQueuedEvents := &revPriorityQueue{priorityQueue: new(priorityQueue(eligibleEvents))} + heap.Init(backwardsQueuedEvents) + + // prune until we fit + for backwardsQueuedEvents.Len() > 0 && !fits() { + toRemove := heap.Pop(backwardsQueuedEvents).(*pb.ConsensusQueueEvent) + //TODO opt: faster delete...but need to maintain s.queuedEvents (though not order)...map indices? + s.queuedEvents = slices.DeleteFunc(s.queuedEvents, func(event *pb.ConsensusQueueEvent) bool { return event == toRemove }) + //TODO opt: drop more than one each time? + } + + // 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 { @@ -422,10 +518,12 @@ func (s *kvState) addObservedEvents(f int, toAdd map[string]*pb.ConsensusQueueOb for _, e := range s.queuedEvents { alreadyQueued[string(e.TimelessHash)] = struct{}{} } + for _, eventHash := range slices.Sorted(maps.Keys(toAdd)) { if _, ok := alreadyQueued[eventHash]; ok { continue // already waiting for capacity; promoting it again would duplicate it } + eventToAdd := toAdd[eventHash] obsEvent, ok := s.observedEvents[eventHash] if !ok { @@ -457,6 +555,7 @@ func (s *kvState) addObservedEvents(f int, toAdd map[string]*pb.ConsensusQueueOb // note: s.observedBlobs tracks blobs while in memory } } + s.observedBlobs.addAll(eventHash, observedBlobs[eventHash]) if len(obsEvent.NodeIds) >= 2*f+1 { @@ -484,6 +583,7 @@ func readConsensusState(kvReader ocr3_1types.KeyValueStateReader) ([]*pb.Consens if err := proto.Unmarshal(v, &pbs); err != nil { return nil, nil, fmt.Errorf("failed to unmarshal consensus events: %w", err) } + consensusEvents = pbs.GetEvents() } @@ -491,6 +591,7 @@ func readConsensusState(kvReader ocr3_1types.KeyValueStateReader) ([]*pb.Consens if err != nil { return nil, nil, err } + return consensusEvents, blobHandles, nil } @@ -507,7 +608,9 @@ func readBlobHandles(kvReader ocr3_1types.KeyValueStateReader) ([][]byte, error) 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/math.go b/core/services/ocr3_1/plugins/queue/math.go index 400276f25df..4d961b0ffd8 100644 --- a/core/services/ocr3_1/plugins/queue/math.go +++ b/core/services/ocr3_1/plugins/queue/math.go @@ -16,15 +16,18 @@ func medianTimestamp(s []*timestamppb.Timestamp) *timestamppb.Timestamp { 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) diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index 98fac7d4b65..3ca4cdfe583 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -9,7 +9,6 @@ package queue import ( "bytes" "cmp" - "container/heap" "context" "crypto/sha256" "errors" @@ -152,25 +151,61 @@ func (c *consensusQueuePlugin) Observation( // placeholder for accurate size calculation BlobHandles: slices.Repeat([][]byte{make([]byte, c.blobHandleMarshalledBytesUpperBound)}, maxObservedBlobHandles), Expiration: timestamppb.New(time.Now().Add(-expirationGraceDur)), - Capacity: uint32(min(capacity.Global, math.MaxUint32)), - WorkflowCapacities: make(map[string]uint32), + Capacity: clampUint32(capacity.Global), + WorkflowCapacities: stateWorkflowCapacities(capacity, observedEvents, queuedEvents), } - // collect KV workflow capacities - for _, e := range observedEvents { - if wfCap, ok := capacity.PerWorkflow[e.WorkflowID]; ok { - obs.WorkflowCapacities[e.WorkflowID] = uint32(min(wfCap, math.MaxUint32)) + 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]) + } } } - for _, e := range queuedEvents { - if wfCap, ok := capacity.PerWorkflow[e.WorkflowID]; ok { - obs.WorkflowCapacities[e.WorkflowID] = uint32(min(wfCap, math.MaxUint32)) + + return proto.MarshalOptions{Deterministic: true}.Marshal(obs) +} + +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) } } - kvWFCapactities := maps.Clone(obs.WorkflowCapacities) // in case we need to rebuild later + for _, e := range observedEvents { + add(e.WorkflowID) + } + for _, e := range queuedEvents { + add(e.WorkflowID) + } + return capacities +} - // Assemble an observation up to maxObservationBytes - var events []*pb.CoordinatedEvent // to be broadcast - protoOpts := proto.MarshalOptions{Deterministic: true} +// 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) { + var events []*pb.CoordinatedEvent for timelessHash, event := range c.triggerQueue.Sorted(ctx, maxObservedEvents, c.maxEventBytes()) { // skip if kv observation exists already if obsEvent, ok := observedEvents[string(timelessHash)]; ok { @@ -180,12 +215,11 @@ func (c *consensusQueuePlugin) Observation( } events = append(events, event) - newWF, err2 := observeEvent(obs, timelessHash, event, capacity.PerWorkflow) - if err2 != nil { - return nil, err2 + newWF, err := observeEvent(obs, timelessHash, event, wfCapacities) + if err != nil { + return nil, err } - // Check size if observationSize(obs) > c.limits.MaxObservationBytes { // too large, remove this one events = events[:len(events)-1] @@ -196,22 +230,7 @@ func (c *consensusQueuePlugin) Observation( break } } - 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 = kvWFCapactities - for _, event := range obs.Events { - if _, ok := obs.WorkflowCapacities[event.WorkflowID]; !ok { - obs.WorkflowCapacities[event.WorkflowID] = uint32(min(capacity.PerWorkflow[event.WorkflowID], math.MaxUint32)) - } - } - } - - return protoOpts.Marshal(obs) + return events, nil } // observationSize returns the encoded size of an observation that grows as events are appended, without sizing every @@ -300,6 +319,7 @@ func (c *consensusQueuePlugin) broadcastObservationBlobs( handles := make([][]byte, len(ends)) errs := make([]error, len(ends)) + // At most maxObservedBlobHandles (10, the vault plugin's limit on concurrent broadcasts) are broadcast at once. var eg errgroup.Group for i, start := 0, 0; i < len(ends); i++ { batch := events[start:ends[i]] @@ -521,28 +541,28 @@ func (c *consensusQueuePlugin) StateTransition( ctx context.Context, _ uint64, _ ocrtypes.AttributedQuery, aos []ocrtypes.AttributedObservation, kvReaderWriter ocr3_1types.KeyValueStateReadWriter, _ ocr3_1types.BlobFetcher, ) (ocr3_1types.ReportsPlusPrecursor, error) { - done := make(chan struct{}) - var obs observations - - go func() { - defer close(done) - obs.aggregate(ctx, c.onchainCfg.F, aos) - }() - - var state kvState - err := state.loadFrom(kvReaderWriter) - if err != nil { - return nil, fmt.Errorf("failed to read state: %w", err) - } - - // wait for aggregation, which reports cancellation as its error, so a partial result is never used - select { - case <-ctx.Done(): - return nil, ctx.Err() - case <-done: - } - if obs.err != nil { - return nil, fmt.Errorf("failed to aggregate observations: %w", obs.err) + // 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 @@ -551,64 +571,12 @@ func (c *consensusQueuePlugin) StateTransition( state.addObservedEvents(c.onchainCfg.F, obs.newObservedEvents, obs.observedBlobs, func(event *pb.ConsensusQueueEvent) { queuedTimelessHashes = append(queuedTimelessHashes, string(event.TimelessHash)) }) - // pop as many queuedEvents as possible in to consensusEvents (up to capacity or KV limits) - for len(state.queuedEvents) > 0 && len(state.consensusEvents) < int(obs.medianCap) { - event := state.queuedEvents.popLimited(obs.medianCapPerWF, obs.medianExpiration) - if event == nil { - break - } - state.consensusEvents = append(state.consensusEvents, event) - } - state.trimConsensusEvents(c.limits.MaxKeyValueModifiedKeysPlusValuesBytes) - - // prune observations if that value or the overall size is too large - state.prepareWriteObservedEvents() // populates the (priority sorted) entries to prune from - for len(state.observedEventEntries) > 0 && - (state.sizeOfObservedEvents() > maxKeyValueValueBytes || - state.sizeOf() > c.limits.MaxKeyValueModifiedKeysPlusValuesBytes) { - // sorted by decreasing priority, so prune the last - toRemove := state.observedEventEntries[len(state.observedEventEntries)-1] - delete(state.observedEvents, string(toRemove.TimelessHash)) - //TODO opt: drop more than one each time? - } - - // prune (newly) queuedEvents if that value, blob handles, or the overall size is too large - if len(queuedTimelessHashes) > 0 && - (state.sizeOfQueuedEvents() > maxKeyValueValueBytes || - state.sizeOfBlobHandles() > maxKeyValueValueBytes || - state.sizeOf() > c.limits.MaxKeyValueModifiedKeysPlusValuesBytes) { - // prune lowest priority queuedEvents from newly added queuedTriggerEventIDs - queuedTimelessHashSet := map[string]struct{}{} - for _, id := range queuedTimelessHashes { - queuedTimelessHashSet[id] = struct{}{} - } - eligibleEvents := make([]*pb.ConsensusQueueEvent, 0, len(state.queuedEvents)) - for _, e := range state.queuedEvents { - if _, ok := queuedTimelessHashSet[string(e.TimelessHash)]; ok { - eligibleEvents = append(eligibleEvents, e) - } - } - backwardsQueuedEvents := &revPriorityQueue{priorityQueue: new(priorityQueue(eligibleEvents))} - heap.Init(backwardsQueuedEvents) - - // prune until we fit - for backwardsQueuedEvents.Len() > 0 && - (state.sizeOfQueuedEvents() > maxKeyValueValueBytes || - state.sizeOfBlobHandles() > maxKeyValueValueBytes || - state.sizeOf() > c.limits.MaxKeyValueModifiedKeysPlusValuesBytes) { - toRemove := heap.Pop(backwardsQueuedEvents).(*pb.ConsensusQueueEvent) - //TODO opt: faster delete...but need to maintain state.queuedEvents (though not order)...map indices? - state.queuedEvents = slices.DeleteFunc(state.queuedEvents, func(event *pb.ConsensusQueueEvent) bool { return event == toRemove }) - //TODO opt: drop more than one each time? - } - // rebuild the priority queue - heap.Init(&state.queuedEvents) - } - + state.popConsensusEvents(int(obs.medianCap), obs.medianCapPerWF, 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 - err = state.writeTo(&stateWriter{kv: kvReaderWriter}) - if err != nil { + if err := state.writeTo(&stateWriter{kv: kvReaderWriter}); err != nil { return nil, err } From 6919c0757e806e20862296583371148ec638bb33 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Sun, 22 Nov 2026 10:06:31 -0600 Subject: [PATCH 21/38] cleanup TODOs --- core/services/ocr3_1/plugins/queue/config.go | 3 +- core/services/ocr3_1/plugins/queue/kvstate.go | 5 +- core/services/ocr3_1/plugins/queue/queue.go | 7 +- .../ocr3_1/plugins/queue/queue_test.go | 98 ++++++++++--------- .../workflows/v2/triggers/coordinator.go | 9 +- .../v2/triggers/coordinator_helpers_test.go | 21 ++++ .../workflows/v2/triggers/coordinator_test.go | 48 +++++++++ core/services/workflows/v2/triggers/queue.go | 8 +- 8 files changed, 139 insertions(+), 60 deletions(-) diff --git a/core/services/ocr3_1/plugins/queue/config.go b/core/services/ocr3_1/plugins/queue/config.go index 1eb16ffc84b..d3104a17d37 100644 --- a/core/services/ocr3_1/plugins/queue/config.go +++ b/core/services/ocr3_1/plugins/queue/config.go @@ -11,7 +11,8 @@ const ( maxObservedBlobHandles = 10 // sanity check on blobs in an observation maxObservedEvents = 1000 // sanity check events in an observation - //TODO reduce these? connect to cre settings? + // These are calibrated by the TestCalibration tests. The limits they must fit in come from the job's PluginConfig. + //TODO connect to cre settings, so that changing them is atomic across the DON maxKeyValueValueBytes = ocr3_1types.MaxMaxKeyValueValueBytes ) diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index 208b55fa38d..c0669be10af 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -269,7 +269,6 @@ func (s *kvState) sizeOf() (size int) { size += len(observedEventsKey) + len(queuedEventsKey) + len(consensusEventsKey) + len(blobHandlesKey) size += s.sizeOfObservedEvents() + s.sizeOfQueuedEvents() + s.sizeOfConsensusEvents() + s.sizeOfBlobHandles() - //TODO opt: proto.MarshalOptions.UseCachedSize return } @@ -458,8 +457,6 @@ func (s *kvState) pruneQueuedToFit(newlyQueued []string, maxTotalBytes int) { // 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 { - //TODO MarshalOptions{UseCachedSize}? - s.prepareWriteObservedEvents() s.prepareWriteBlobHandles() @@ -542,7 +539,7 @@ func (s *kvState) addObservedEvents(f int, toAdd map[string]*pb.ConsensusQueueOb } } else { // update proposal - // TODO opt: build a map to avoid n^2? + // (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) diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index 3ca4cdfe583..cee8e92eac5 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -35,6 +35,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/services" "github.com/smartcontractkit/chainlink-common/pkg/settings/limits" "github.com/smartcontractkit/chainlink-common/pkg/workflows" + "github.com/smartcontractkit/chainlink/v2/core/services/workflows/types" "github.com/smartcontractkit/chainlink/v2/core/services/workflows/v2/triggers" ) @@ -464,7 +465,10 @@ func (c *consensusQueuePlugin) ValidateObservation( func validateObservedEvent(ctx context.Context, fetcher *blobCache, event *pb.ConsensusQueueEvent, blobHandles [][]byte) error { if event.WorkflowID == "" { return errors.New("event workflow id is missing") - } // TODO ensure not too long + } + 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) } @@ -522,7 +526,6 @@ func validateObservedEvent(ctx context.Context, fetcher *blobCache, event *pb.Co return fmt.Errorf("blob deadline timestamp is not nil: %v", coordEvent.Deadline) } - //TODO opt: reduce allocations with a pool 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) } diff --git a/core/services/ocr3_1/plugins/queue/queue_test.go b/core/services/ocr3_1/plugins/queue/queue_test.go index 39bcb0e7e07..d99df0107c4 100644 --- a/core/services/ocr3_1/plugins/queue/queue_test.go +++ b/core/services/ocr3_1/plugins/queue/queue_test.go @@ -135,6 +135,9 @@ func newCoordinatedEvent(t testing.TB, wf, eventID string) (hash []byte, event * 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 @@ -286,13 +289,13 @@ func TestObservationsAggregate(t *testing.T) { t.Parallel() var res observations res.aggregate(t.Context(), f, []ocrtypes.AttributedObservation{ - mkAO(0, base(10, map[string]uint32{"wf": 5})), - mkAO(1, base(1, map[string]uint32{"wf": 1})), - mkAO(2, base(7, map[string]uint32{"wf": 9})), + 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.medianCap, "F+1th lowest of 1,7,10") - assert.Equal(t, uint32(5), res.medianCapPerWF["wf"], "F+1th lowest of 1,5,9") + assert.Equal(t, uint32(5), res.medianCapPerWF[testWF], "F+1th lowest of 1,5,9") assert.Equal(t, time.Unix(100, 0).UTC(), res.medianExpiration.UTC()) }) @@ -317,11 +320,11 @@ func TestObservationsAggregate(t *testing.T) { t.Run("events are merged by hash across observers", func(t *testing.T) { t.Parallel() - hash, event := newCoordinatedEvent(t, "wf", "evt") + hash, event := newCoordinatedEvent(t, testWF, "evt") mkObs := func() *pb.ConsensusQueueObservation { - o := base(5, map[string]uint32{"wf": 5}) + o := base(5, map[string]uint32{testWF: 5}) o.BlobHandles = [][]byte{[]byte("handle")} - _, err := observeEvent(o, hash, proto.CloneOf(event), map[string]int{"wf": 5}) + _, err := observeEvent(o, hash, proto.CloneOf(event), map[string]int{testWF: 5}) require.NoError(t, err) return o } @@ -357,7 +360,7 @@ func TestBroadcastObservationBlobs(t *testing.T) { obs := &pb.ConsensusQueueObservation{WorkflowCapacities: map[string]uint32{}} var events []*pb.CoordinatedEvent for _, id := range []string{"a", "b", "c"} { - h, e := newCoordinatedEvent(t, "wf", id) + h, e := newCoordinatedEvent(t, testWF, id) events = append(events, e) _, err := observeEvent(obs, h, e, nil) require.NoError(t, err) @@ -374,7 +377,7 @@ func TestBroadcastObservationBlobs(t *testing.T) { t.Parallel() blobs := &memBlobs{} c := testPlugin(t, sliceQueue{}, blobs, ocr3_1types.MaxMaxObservationBytes) - _, e := newCoordinatedEvent(t, "wf", "a") + _, e := newCoordinatedEvent(t, testWF, "a") _, err := c.broadcastObservationBlobs(t.Context(), &pb.ConsensusQueueObservation{}, blobs, []*pb.CoordinatedEvent{e}, 1) require.Error(t, err) }) @@ -386,7 +389,7 @@ func TestObservation_PassesValidateObservation(t *testing.T) { var events []hashedEvent for _, id := range []string{"a", "b"} { - h, e := newCoordinatedEvent(t, "wf", id) + h, e := newCoordinatedEvent(t, testWF, id) events = append(events, hashedEvent{h, e}) } blobs := &memBlobs{} @@ -427,7 +430,7 @@ func TestObservation_SizeLimited(t *testing.T) { var events []hashedEvent for _, id := range []string{"a", "b", "c"} { - h, e := newCoordinatedEvent(t, "wf", id) + h, e := newCoordinatedEvent(t, testWF, id) events = append(events, hashedEvent{h, e}) } @@ -441,7 +444,7 @@ func TestObservation_SizeLimited(t *testing.T) { for i := range probe.BlobHandles { probe.BlobHandles[i] = make([]byte, c0.blobHandleMarshalledBytesUpperBound) } - _, e0 := newCoordinatedEvent(t, "wf", "a") + _, e0 := newCoordinatedEvent(t, testWF, "a") _, err := observeEvent(probe, events[0].hash, e0, nil) require.NoError(t, err) limit := proto.Size(probe) + 8 @@ -490,6 +493,9 @@ func TestValidateObservedEvent(t *testing.T) { }{ {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"}, @@ -499,7 +505,7 @@ func TestValidateObservedEvent(t *testing.T) { {name: "blob index out of range", mutate: func(_ *pb.CoordinatedEvent, qe *pb.ConsensusQueueEvent) { qe.Blobs[0].Blob = uint32(len(handles)) }, wantErr: "out of range"}, {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 = "other" }, wantErr: "does not match event workflow ID"}, + {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"}, @@ -509,7 +515,7 @@ func TestValidateObservedEvent(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - ce, qe := blobEvent(t, "wf", "evt") + ce, qe := blobEvent(t, testWF, "evt") if tt.mutate != nil { tt.mutate(ce, qe) } @@ -527,10 +533,10 @@ func TestValidateObservedEvent(t *testing.T) { // 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, "wf", "evt") + _, qe := blobEvent(t, testWF, "evt") for _, ce := range []*pb.CoordinatedEvent{ - {WorkflowID: "wf"}, // no Event - {WorkflowID: "wf", Event: &pb.TriggerResponse{}}, // no inner Event + {WorkflowID: testWF}, // no Event + {WorkflowID: testWF, Event: &pb.TriggerResponse{}}, // no inner Event } { f := &countingFetcher{payload: marshalEvents(t, ce)} require.NotPanics(t, func() { @@ -545,7 +551,7 @@ func observeN(t *testing.T, n int) (*consensusQueuePlugin, *memBlobs, *pb.Consen t.Helper() var events []hashedEvent for i := range n { - h, e := newCoordinatedEvent(t, "wf", fmt.Sprintf("evt-%d", i)) + h, e := newCoordinatedEvent(t, testWF, fmt.Sprintf("evt-%d", i)) e.Deadline = ts(int64(2000 + 10*i)) events = append(events, hashedEvent{h, e}) } @@ -586,7 +592,7 @@ func TestValidateObservation(t *testing.T) { }, 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, "wf") }, wantErr: "missing capacity"}, + {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"}, } @@ -676,7 +682,7 @@ type nodeOpts struct { expiration int64 // seconds } -var stdNode = nodeOpts{capacity: 10, wfCaps: map[string]uint32{"wf": 10}, expiration: 100} +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 { @@ -704,12 +710,12 @@ func ao(t testing.TB, id int, obs *pb.ConsensusQueueObservation) ocrtypes.Attrib return ocrtypes.AttributedObservation{Observer: commontypes.OracleID(id), Observation: b} } -// mkEvents makes n events for workflow "wf" with deadlines base, base+1, ... +// mkEvents makes n events for workflow testWF with deadlines base, base+1, ... func mkEvents(t testing.TB, n int, base int64) []hashedEvent { t.Helper() var out []hashedEvent for i := range n { - h, e := newCoordinatedEvent(t, "wf", fmt.Sprintf("evt-%02d", i)) + h, e := newCoordinatedEvent(t, testWF, fmt.Sprintf("evt-%02d", i)) e.Deadline = ts(base + int64(i)) out = append(out, hashedEvent{h, e}) } @@ -718,7 +724,7 @@ func mkEvents(t testing.TB, n int, base int64) []hashedEvent { func execIDOf(t testing.TB, id string) string { t.Helper() - v, err := workflows.GenerateExecutionIDWithTriggerIndex("wf", id, 0) + v, err := workflows.GenerateExecutionIDWithTriggerIndex(testWF, id, 0) require.NoError(t, err) return v } @@ -859,7 +865,7 @@ func TestStateTransition_Capacity(t *testing.T) { 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{"wf": tt.wfCap}, expiration: 100}, e...))) + 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...)) @@ -877,7 +883,7 @@ func TestStateTransition_Capacity(t *testing.T) { c := newSTPlugin(t) kv := memKV{} e := mkEvents(t, 2, 2000) - none := nodeOpts{capacity: 0, wfCaps: map[string]uint32{"wf": 0}, expiration: 100} + 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) @@ -891,7 +897,7 @@ func TestStateTransition_Capacity(t *testing.T) { func TestStateTransition_Expiration(t *testing.T) { t.Parallel() - late := nodeOpts{capacity: 10, wfCaps: map[string]uint32{"wf": 10}, expiration: 3000} + 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() @@ -933,10 +939,10 @@ func deterministicScenario(t *testing.T, shuffleSeed int64) memKV { 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{"wf": 2}, expiration: 90}, pick(0, 1, 2)...)), - ao(t, 1, nodeObs(t, nodeOpts{capacity: 5, wfCaps: map[string]uint32{"wf": 3}, expiration: 95}, pick(0, 1, 3)...)), - ao(t, 2, nodeObs(t, nodeOpts{capacity: 4, wfCaps: map[string]uint32{"wf": 9}, expiration: 99}, pick(0, 2, 3, 4, 5)...)), - ao(t, 3, nodeObs(t, nodeOpts{capacity: 9, wfCaps: map[string]uint32{"wf": 1}, expiration: 80}, pick(1, 4)...)), + 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] }) @@ -1056,7 +1062,7 @@ func TestStateTransition_SizeLimits(t *testing.T) { c.limits.MaxKeyValueModifiedKeysPlusValuesBytes = limit kv := memKV{} e := mkEvents(t, 30, 2000) - none := nodeOpts{capacity: 0, wfCaps: map[string]uint32{"wf": 0}, expiration: 100} // nothing executes + 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, @@ -1079,7 +1085,7 @@ func TestStateTransition_SizeLimits(t *testing.T) { const n = 20 e := mkEvents(t, n, 2000) aos := func() []ocrtypes.AttributedObservation { - big := nodeOpts{capacity: 100, wfCaps: map[string]uint32{"wf": 100}, expiration: 100} + 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...))} } @@ -1195,7 +1201,7 @@ func seedKV(t testing.TB, kv memKV, blobs *memBlobs, consensus, queued []string) s := newKVState() var ces []*pb.CoordinatedEvent for i, id := range append(append([]string(nil), consensus...), queued...) { - ce, qe := blobEvent(t, "wf", id) + 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) @@ -1233,7 +1239,7 @@ func TestCommitted(t *testing.T) { for i, id := range []string{"a", "b"} { e, ok := byTrigger[id] require.True(t, ok, "event %s not started", id) - assert.Equal(t, "wf", e.WorkflowID) + 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") } @@ -1283,7 +1289,7 @@ func TestCommitted(t *testing.T) { t.Parallel() coord, blobs, kv := &recCoordinator{}, &memBlobs{}, memKV{} c := newCommitPlugin(t, coord, &recQueue{}, blobs) - _, qe := blobEvent(t, "wf", "a") + _, 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) @@ -1435,8 +1441,8 @@ func TestObservation_Fields(t *testing.T) { c := newCommitPlugin(t, &recCoordinator{}, &recQueue{sliceQueue: sliceQueue{events: append(append([]hashedEvent{}, mine...), theirs...)}}, blobs) s := newKVState() - s.observedEvents[string(mine[0].hash)] = obsEvent("wf", "m0", 100, 0, 1) // includes OracleID 0 (this node) - s.observedEvents[string(mine[1].hash)] = obsEvent("wf", "m1", 100, 2, 3) // does not + 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})) @@ -1503,7 +1509,7 @@ func TestObservation_BlobBatching(t *testing.T) { for i, e := range obs.Events { // earliest first assert.Equal(t, ev[i].hash, e.TimelessHash) } - assert.Contains(t, obs.WorkflowCapacities, "wf") + assert.Contains(t, obs.WorkflowCapacities, testWF) }) t.Run("size limited observations keep only the events that fit", func(t *testing.T) { @@ -1585,7 +1591,7 @@ func TestMaxEventBytes(t *testing.T) { t.Parallel() eventOfSize := func(k int) *pb.CoordinatedEvent { // event whose encoded size grows with k - e, _ := blobEvent(t, "wf", "evt") + e, _ := blobEvent(t, testWF, "evt") e.Event.Event.TriggerType = strings.Repeat("x", k) return e } @@ -1655,18 +1661,18 @@ func TestObservationsAggregate_Omissions(t *testing.T) { 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{"wf": 9}), mk(map[string]uint32{"wf": 9}), mk(nil))) + 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.medianCapPerWF["wf"], "F omissions count as zero, which sorted[F] tolerates") + assert.Equal(t, uint32(9), res.medianCapPerWF[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{"wf": 9}), mk(nil), mk(nil))) + 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.medianCapPerWF, "wf") - assert.Zero(t, res.medianCapPerWF["wf"]) + assert.Contains(t, res.medianCapPerWF, testWF) + assert.Zero(t, res.medianCapPerWF[testWF]) }) t.Run("too few observations is an error, not a panic", func(t *testing.T) { @@ -1940,7 +1946,7 @@ func TestObservation_PartialBlobFailure(t *testing.T) { assert.Equal(t, uint32(i%2), e.Blobs[0].Element) } if tt.wantEvents > 0 { - assert.Contains(t, obs.WorkflowCapacities, "wf", "capacities cover the events kept") + 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") } }) @@ -2023,7 +2029,7 @@ func packedEvents(tb testing.TB, n, payload int) []hashedEvent { out := make([]hashedEvent, 0, n) for i := range n { e := eventOfPayload(i, payload) - e.WorkflowID = hexID("wf", i%50) + e.WorkflowID = hexID(testWF, i%50) b, err := e.MarshalTimeless() require.NoError(tb, err) sum := sha256.Sum256(b) diff --git a/core/services/workflows/v2/triggers/coordinator.go b/core/services/workflows/v2/triggers/coordinator.go index 78298770be9..3836444e70b 100644 --- a/core/services/workflows/v2/triggers/coordinator.go +++ b/core/services/workflows/v2/triggers/coordinator.go @@ -529,10 +529,15 @@ func (c *coordinator) StartExecution(ctx context.Context, event CoordinatedEvent //TODO more admission checks? // c.admission.ExecutionConcurrency.Wait(ctx, 1)? - _ = time.Since(event.ObservedAt) //TODO emit latency metric + // the time the event spent queued, as recorded by the admitter for events that do not go through consensus + wfMetrics := c.deps.Metrics + if cw, ok := c.workflows.get(event.WorkflowID); ok { + wfMetrics = cw.metrics + } + wfMetrics.With(platform.KeyTriggerID, event.TriggerCapID).RecordTriggerEventQueueWaitSeconds(ctx, c.clock.Since(event.ObservedAt).Seconds()) + // The event has already left the queue, and starting it is best effort: a failure is the caller's to log. if err = eng.ExecuteTrigger(ctx, event); err != nil { - //TODO handle errors, ack? return fmt.Errorf("workflow %s: failed to execute trigger %s: %w", wfID, event.Event.Event.ID, err) } 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_test.go b/core/services/workflows/v2/triggers/coordinator_test.go index f22bbc722b6..3739cecfc25 100644 --- a/core/services/workflows/v2/triggers/coordinator_test.go +++ b/core/services/workflows/v2/triggers/coordinator_test.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "maps" + "strings" "testing" "time" @@ -1168,3 +1169,50 @@ func TestCoordinator_DeliveryLogs(t *testing.T) { }) } } + +func TestCoordinator_StartExecution(t *testing.T) { + t.Parallel() + + newEvent := func(f *coordinatorFixture, 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: "evt-1"}}, + } + } + + t.Run("executes the event and records how long it was queued", func(t *testing.T) { + t.Parallel() + wfMetrics, reader := newTestMeterMetrics(t) + f := newCoordinatorFixture(t, withMetrics(wfMetrics)) + + require.NoError(t, f.c.StartExecution(t.Context(), newEvent(f, 5*time.Second))) + + assert.Equal(t, []string{"evt-1"}, f.engine.executedIDs()) + 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("unknown workflow", func(t *testing.T) { + t.Parallel() + wfMetrics, reader := newTestMeterMetrics(t) + f := newCoordinatorFixture(t, withMetrics(wfMetrics)) + event := newEvent(f, time.Second) + event.WorkflowID = hexWorkflowID(7) // no engine + require.Error(t, f.c.StartExecution(t.Context(), event)) + count, _ := histogramSum(t, reader, "platform_engine_trigger_event_queue_wait_seconds") + assert.Zero(t, count, "nothing started, so nothing is recorded") + }) + + t.Run("invalid workflow ID", func(t *testing.T) { + t.Parallel() + f := newCoordinatorFixture(t) + event := newEvent(f, time.Second) + event.WorkflowID = "not-hex" + require.Error(t, f.c.StartExecution(t.Context(), event)) + assert.Empty(t, f.engine.executedIDs()) + }) +} + +func hexWorkflowID(i byte) string { return strings.Repeat(fmt.Sprintf("%02x", i), 32) } diff --git a/core/services/workflows/v2/triggers/queue.go b/core/services/workflows/v2/triggers/queue.go index 6c85947faec..ff247247da3 100644 --- a/core/services/workflows/v2/triggers/queue.go +++ b/core/services/workflows/v2/triggers/queue.go @@ -48,8 +48,7 @@ type Queue interface { Sorted(ctx context.Context, limit, maxEventBytes int) iter.Seq2[[]byte, *pb.CoordinatedEvent] // Remove removes events from the queue by execution ID. - //TODO can't ack with trigger event ID - not unique! - Remove(ctx context.Context, triggerEventIDs iter.Seq[string]) + Remove(ctx context.Context, executionIDs iter.Seq[string]) } // Stats is a point-in-time view of a Queue. @@ -177,7 +176,6 @@ func (q *CentralQueue) Remove(ctx context.Context, executionIDs iter.Seq[string] defer q.mu.Unlock() var deleted int - //TODO opt: map so we don't have to iterate over them all q.events = slices.DeleteFunc(q.events, func(cqe centralQueueEvent) bool { _, ok := execIDSet[cqe.executionID] if ok { @@ -221,8 +219,8 @@ func (q *CentralQueue) Sorted(ctx context.Context, limit, maxEventBytes int) ite } } -// dropOversize removes the events from the queue, if they are still there. -// TODO should we fall back to executing instead of just dropping? +// 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 From 7824491a4aa9a21d8ac85ebfa292ee1a5b68154f Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Sun, 22 Nov 2026 10:21:26 -0600 Subject: [PATCH 22/38] optimizations --- core/services/ocr3_1/plugins/queue/kvstate.go | 66 +++++---- .../ocr3_1/plugins/queue/kvstate_test.go | 126 ++++++++++++++++-- .../ocr3_1/plugins/queue/queue_test.go | 59 +++++++- 3 files changed, 213 insertions(+), 38 deletions(-) diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index c0669be10af..eb1308da51f 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -6,6 +6,7 @@ import ( "fmt" "maps" "slices" + "sort" "time" "google.golang.org/protobuf/encoding/protowire" @@ -140,15 +141,6 @@ func (p *priorityQueue) popLimited(capPerWF map[string]uint32, expiration time.T return } -type revPriorityQueue struct { - *priorityQueue -} - -func (r *revPriorityQueue) Less(i, j int) bool { - a, b := (*r.priorityQueue)[i], (*r.priorityQueue)[j] - return b.CompareDeadline(a) < 0 -} - type blobHandleMap map[string]map[string]uint32 // eventHash -> blobHandle -> idx func (m blobHandleMap) add(eventHash string, blobHandle string, element uint32) { @@ -405,24 +397,38 @@ func (s *kvState) popConsensusEvents(capacity int, capPerWF map[string]uint32, e } // 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 (priority sorted) entries to prune from - for len(s.observedEventEntries) > 0 && - (s.sizeOfObservedEvents() > maxKeyValueValueBytes || s.sizeOf() > maxTotalBytes) { - // sorted by decreasing priority, so prune the last - toRemove := s.observedEventEntries[len(s.observedEventEntries)-1] - delete(s.observedEvents, string(toRemove.TimelessHash)) - //TODO opt: drop more than one each time? + 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) } // pruneQueuedToFit drops the lowest priority events of those that were newly queued until the queued events, the blob -// handles, and the overall size fit. +// 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 } @@ -431,24 +437,28 @@ func (s *kvState) pruneQueuedToFit(newlyQueued []string, maxTotalBytes int) { 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) }) - backwardsQueuedEvents := &revPriorityQueue{priorityQueue: new(priorityQueue(eligibleEvents))} - heap.Init(backwardsQueuedEvents) - - // prune until we fit - for backwardsQueuedEvents.Len() > 0 && !fits() { - toRemove := heap.Pop(backwardsQueuedEvents).(*pb.ConsensusQueueEvent) - //TODO opt: faster delete...but need to maintain s.queuedEvents (though not order)...map indices? - s.queuedEvents = slices.DeleteFunc(s.queuedEvents, func(event *pb.ConsensusQueueEvent) bool { return event == toRemove }) - //TODO opt: drop more than one each time? + 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) // rebuild the priority queue heap.Init(&s.queuedEvents) diff --git a/core/services/ocr3_1/plugins/queue/kvstate_test.go b/core/services/ocr3_1/plugins/queue/kvstate_test.go index c4ebecacd9b..5be6f3be2d3 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate_test.go +++ b/core/services/ocr3_1/plugins/queue/kvstate_test.go @@ -2,6 +2,9 @@ package queue import ( "container/heap" + "fmt" + "maps" + "math/rand" "slices" "testing" "time" @@ -68,15 +71,6 @@ func TestPriorityQueue_Order(t *testing.T) { require.Nil(t, pq.mustPop(), "empty queue pops nil") } -func TestPriorityQueue_RevOrder(t *testing.T) { - t.Parallel() - - pq := priorityQueue{qEvent("wf", "a", "h1", 10), qEvent("wf", "b", "h2", 30), qEvent("wf", "c", "h3", 20)} - rev := &revPriorityQueue{priorityQueue: &pq} - heap.Init(rev) - require.Equal(t, "h2", string(heap.Pop(rev).(*pb.ConsensusQueueEvent).TimelessHash), "latest deadline first") -} - func TestPopLimited(t *testing.T) { t.Parallel() @@ -662,3 +656,117 @@ func TestAddObservedEvents_UpdateDeduplicatesNodes(t *testing.T) { 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 range 1 + rng.Intn(2) { + s.observedBlobs.add(hash, pool[rng.Intn(len(pool))], uint32(rng.Intn(1000))) + } + } + 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))) + } + 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) + } + } +} diff --git a/core/services/ocr3_1/plugins/queue/queue_test.go b/core/services/ocr3_1/plugins/queue/queue_test.go index d99df0107c4..00ee2ebb9ab 100644 --- a/core/services/ocr3_1/plugins/queue/queue_test.go +++ b/core/services/ocr3_1/plugins/queue/queue_test.go @@ -735,7 +735,7 @@ func stateTransition(t testing.TB, c *consensusQueuePlugin, kv ocr3_1types.KeyVa return err } -func loadState(t *testing.T, kv memKV) *kvState { +func loadState(t testing.TB, kv memKV) *kvState { t.Helper() var s kvState require.NoError(t, s.loadFrom(kv)) @@ -2274,3 +2274,60 @@ func TestObservationSize(t *testing.T) { 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 { + var aos []ocrtypes.AttributedObservation + 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 := 0; i < 9; i++ { // 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") + }) +} From c2255e12d732879e8918bec43511a83130bccb6c Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Sun, 22 Nov 2026 10:31:14 -0600 Subject: [PATCH 23/38] fix central queue --- core/services/ocr3_1/plugins/queue/queue.go | 3 +- .../ocr3_1/plugins/queue/queue_test.go | 25 ---- .../workflows/v2/triggers/coordinator.go | 108 ++++++++------ .../workflows/v2/triggers/coordinator_test.go | 134 +++++++++++++++--- 4 files changed, 182 insertions(+), 88 deletions(-) diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index cee8e92eac5..079c16bf96a 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -765,8 +765,7 @@ func (c *consensusQueuePlugin) tryStartExecution(ctx context.Context, fetcher *b return fmt.Errorf("failed to convert CoordinatedEvent from proto: %w", err) } - //TODO ensure this only *starts* the execution, and does not block while it runs - // TestCommitted_DoesNotWaitForExecutions + // StartExecution returns once the execution has started, not when it finishes. return c.triggerCoordinator.StartExecution(ctx, event) } diff --git a/core/services/ocr3_1/plugins/queue/queue_test.go b/core/services/ocr3_1/plugins/queue/queue_test.go index 00ee2ebb9ab..da50b2ebd17 100644 --- a/core/services/ocr3_1/plugins/queue/queue_test.go +++ b/core/services/ocr3_1/plugins/queue/queue_test.go @@ -1118,7 +1118,6 @@ type recCoordinator struct { mu sync.Mutex started []triggers.CoordinatedEvent startErr error - block chan struct{} // if set, StartExecution blocks until closed (like a running workflow) capacity triggers.Capacity capErr error } @@ -1128,9 +1127,6 @@ func (r *recCoordinator) AvailableCapacity(context.Context) (triggers.Capacity, } func (r *recCoordinator) StartExecution(_ context.Context, e triggers.CoordinatedEvent) error { - if r.block != nil { - <-r.block - } r.mu.Lock() defer r.mu.Unlock() r.started = append(r.started, e) @@ -1321,27 +1317,6 @@ func TestCommitted(t *testing.T) { }) } -// Executions must only be *started* on the OCR call path: a workflow that runs for a long time must not hold up the round. -// (Open issue: commitState currently waits for every StartExecution to return.) -func TestCommitted_DoesNotWaitForExecutions(t *testing.T) { - t.Parallel() - - coord, blobs, kv := &recCoordinator{block: make(chan struct{})}, &memBlobs{}, memKV{} - c := newCommitPlugin(t, coord, &recQueue{}, blobs) - seedKV(t, kv, blobs, []string{"a"}, nil) - - done := make(chan error, 1) - go func() { done <- c.Committed(t.Context(), 1, kv) }() - t.Cleanup(func() { close(coord.block) }) // always release the "workflow" - - select { - case err := <-done: - require.NoError(t, err) - case <-time.After(time.Second): - t.Fatal("Committed blocked on a running workflow execution") - } -} - func TestObservation_StartsExecutionsFromState(t *testing.T) { t.Parallel() diff --git a/core/services/workflows/v2/triggers/coordinator.go b/core/services/workflows/v2/triggers/coordinator.go index 3836444e70b..b4a5732b7e0 100644 --- a/core/services/workflows/v2/triggers/coordinator.go +++ b/core/services/workflows/v2/triggers/coordinator.go @@ -84,7 +84,11 @@ type Coordinator interface { // limiter does not break down by scope. AvailableCapacity(ctx context.Context) (Capacity, error) - // StartExecution starts execution of the triggered event or returns an error. + // StartExecution starts execution of the triggered event, and returns once it has started, not when it finishes. + // It takes an execution slot like any admitted event, and holds it until the execution finishes, so that + // AvailableCapacity reflects it. It waits for a slot if there is none free, and returns an error if the workflow is + // not registered, its engine is gone, or the slot cannot be taken. How the execution itself ends is logged. + // Starting an event that is already executing is not an error, so it is safe to call repeatedly. StartExecution(context.Context, CoordinatedEvent) error } @@ -511,36 +515,35 @@ func (c *coordinator) Ack(ctx context.Context, triggerCapID, triggerRegistration } func (c *coordinator) StartExecution(ctx context.Context, event CoordinatedEvent) error { - wfID, err := types.WorkflowIDFromHex(event.WorkflowID) - if err != nil { - return err - } - - //TODO share code with admitEvent? - - eng, ok := c.engines.Get(wfID) + cw, ok := c.workflows.get(event.WorkflowID) if !ok { - return fmt.Errorf("workflow %s: engine not found", wfID) + return fmt.Errorf("workflow %s: not registered", event.WorkflowID) } - if !eng.IsCoordinated() { - return fmt.Errorf("workflow %s: engine not coordinated", wfID) + engine, err := c.lookupEngine(cw.wid) + if err != nil { + return fmt.Errorf("workflow %s: %w", cw.wid, err) } - //TODO more admission checks? - // c.admission.ExecutionConcurrency.Wait(ctx, 1)? - - // the time the event spent queued, as recorded by the admitter for events that do not go through consensus - wfMetrics := c.deps.Metrics - if cw, ok := c.workflows.get(event.WorkflowID); ok { - wfMetrics = cw.metrics - } - wfMetrics.With(platform.KeyTriggerID, event.TriggerCapID).RecordTriggerEventQueueWaitSeconds(ctx, c.clock.Since(event.ObservedAt).Seconds()) + // 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) + tm := cw.metrics.With(platform.KeyTriggerID, event.TriggerCapID) + tm.RecordTriggerEventQueueWaitSeconds(ctx, c.clock.Since(event.ObservedAt).Seconds()) - // The event has already left the queue, and starting it is best effort: a failure is the caller's to log. - if err = eng.ExecuteTrigger(ctx, event); err != nil { - return fmt.Errorf("workflow %s: failed to execute trigger %s: %w", wfID, event.Event.Event.ID, err) + semWaitStart := c.clock.Now() + free, err := c.admission.ExecutionConcurrency.Wait(ctx, 1) + tm.RecordExecutionSemaphoreWaitSeconds(ctx, c.clock.Now().Sub(semWaitStart).Seconds()) + if err != nil { + return fmt.Errorf("workflow %s: failed to acquire an execution slot: %w", cw.wid, err) } + c.eng.Go(func(context.Context) { + defer free() + // WithoutCancel: the caller returns as soon as the execution has started, which must not cancel it. + err := engine.ExecuteTrigger(context.WithoutCancel(ctx), event) + // Starting the same event again is routine here: it is started when it is committed and again by the next + // observation, in case the first was missed. The engine ignores the repeats. + logExecuteResult(cw.lggr, event, err, true) + }) return nil } @@ -732,15 +735,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) }) } } @@ -749,19 +744,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_test.go b/core/services/workflows/v2/triggers/coordinator_test.go index 3739cecfc25..96dfdd7fad7 100644 --- a/core/services/workflows/v2/triggers/coordinator_test.go +++ b/core/services/workflows/v2/triggers/coordinator_test.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "maps" - "strings" "testing" "time" @@ -1173,46 +1172,139 @@ func TestCoordinator_DeliveryLogs(t *testing.T) { func TestCoordinator_StartExecution(t *testing.T) { t.Parallel() - newEvent := func(f *coordinatorFixture, age time.Duration) CoordinatedEvent { + // 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: "evt-1"}}, + 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("executes the event and records how long it was queued", func(t *testing.T) { + 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 := newCoordinatorFixture(t, withMetrics(wfMetrics)) + f := register(t, withMetrics(wfMetrics)) - require.NoError(t, f.c.StartExecution(t.Context(), newEvent(f, 5*time.Second))) + 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("unknown workflow", func(t *testing.T) { + t.Run("returns once the execution has started, not when it finishes", func(t *testing.T) { t.Parallel() - wfMetrics, reader := newTestMeterMetrics(t) - f := newCoordinatorFixture(t, withMetrics(wfMetrics)) - event := newEvent(f, time.Second) - event.WorkflowID = hexWorkflowID(7) // no engine - require.Error(t, f.c.StartExecution(t.Context(), event)) - count, _ := histogramSum(t, reader, "platform_engine_trigger_event_queue_wait_seconds") - assert.Zero(t, count, "nothing started, so nothing is recorded") + 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("invalid workflow ID", func(t *testing.T) { + t.Run("holds an execution slot until the execution finishes", func(t *testing.T) { t.Parallel() - f := newCoordinatorFixture(t) - event := newEvent(f, time.Second) + 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, so capacity reflects the first + second := make(chan error, 1) + go func() { second <- f.c.StartExecution(t.Context(), newEvent(f, "evt-2", 0)) }() + 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.NoError(t, <-second) + require.Eventually(t, executed(f, 2), 5*time.Second, 5*time.Millisecond) + }) + + t.Run("a slot that cannot be taken is an error and nothing starts", func(t *testing.T) { + t.Parallel() + admission, _ := 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) + + ctx, cancel := context.WithCancel(t.Context()) + cancel() + err := f.c.StartExecution(ctx, newEvent(f, "evt-2", 0)) + require.ErrorIs(t, err, context.Canceled) + assert.Len(t, f.engine.executed(), 1) + release() + }) + + 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, f.c.StartExecution(t.Context(), event)) - assert.Empty(t, f.engine.executedIDs()) + require.Error(t, invalid.c.StartExecution(t.Context(), event)) + assert.Empty(t, invalid.engine.executed()) }) } - -func hexWorkflowID(i byte) string { return strings.Repeat(fmt.Sprintf("%02x", i), 32) } From 765c58253b257f59a6d13592b1813917d4db4e6d Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Sun, 22 Nov 2026 10:49:48 -0600 Subject: [PATCH 24/38] ensure idempotency --- core/services/cre/cre.go | 14 +- core/services/workflows/store/store_memory.go | 16 ++- .../workflows/store/store_memory_test.go | 64 +++++++++ core/services/workflows/v2/base_engine.go | 35 ++--- .../workflows/v2/triggers/coordinator.go | 83 ++++++++--- .../workflows/v2/triggers/coordinator_test.go | 134 ++++++++++++++++-- 6 files changed, 297 insertions(+), 49 deletions(-) diff --git a/core/services/cre/cre.go b/core/services/cre/cre.go index 433b6011e1a..3a12cd16865 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 @@ -923,6 +927,7 @@ func newWorkflowRegistrySyncerV2( // 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. + eventLifetime := triggers.NewEventLifetime(triggers.ConsensusQueueExpirationGrace(lf)) centralQueue := triggers.NewQueue(engineLimiters.CentralTriggerEventQueue, wfmonitoring.NewCentralTriggerQueueMetricLabeler(commonmetrics.NewLabeler(), centralQueueMetrics), lggr) centralQueueDrainer := triggers.NewCentralQueueDrainer(centralQueue, engineLimiters.CentralTriggerQueueDrainInterval, @@ -942,6 +947,7 @@ func newWorkflowRegistrySyncerV2( triggers.WithShadowMode(centralQueue, engineLimiters.ShadowTriggerMode), triggers.WithDrainer(centralQueueDrainer), triggers.WithExpirationGrace(triggers.ConsensusQueueExpirationGrace(lf)), + triggers.WithEventLifetime(eventLifetime), ) handlerOpts := []syncerV2.EventHandlerOption{ @@ -1048,9 +1054,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, diff --git a/core/services/workflows/store/store_memory.go b/core/services/workflows/store/store_memory.go index 76dba758f18..75e247428c6 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 min 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. min is called on each sweep, and must be set before Start. +func (s *InMemoryStore) SetMinimumCompletedRetention(min func() time.Duration) { + s.minimumCompletedRetention = min } 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..1c5c741ce2e 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, min func() time.Duration) (*InMemoryStore, *clockwork.FakeClock) { + fakeClock := clockwork.NewFakeClock() + store := NewInMemoryStoreWithPruneConfiguration(logger.TestLogger(t), fakeClock, time.Millisecond, configured, 24*time.Hour) + store.SetMinimumCompletedRetention(min) + 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 min atomic.Int64 + min.Store(int64(time.Minute)) + store, fakeClock := newStore(t, func() time.Duration { return time.Duration(min.Load()) }) + + min.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 96a876e158d..87f3cfaf03d 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 b4a5732b7e0..5c99647df77 100644 --- a/core/services/workflows/v2/triggers/coordinator.go +++ b/core/services/workflows/v2/triggers/coordinator.go @@ -84,11 +84,12 @@ type Coordinator interface { // limiter does not break down by scope. AvailableCapacity(ctx context.Context) (Capacity, error) - // StartExecution starts execution of the triggered event, and returns once it has started, not when it finishes. - // It takes an execution slot like any admitted event, and holds it until the execution finishes, so that - // AvailableCapacity reflects it. It waits for a slot if there is none free, and returns an error if the workflow is - // not registered, its engine is gone, or the slot cannot be taken. How the execution itself ends is logged. - // Starting an event that is already executing is not an error, so it is safe to call repeatedly. + // 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 } @@ -164,6 +165,9 @@ type coordinator struct { // 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. @@ -259,6 +263,41 @@ func ConsensusQueueExpirationGrace(lf limits.Factory) func(context.Context) (tim } } +// 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 { @@ -524,24 +563,29 @@ func (c *coordinator) StartExecution(ctx context.Context, event CoordinatedEvent return fmt.Errorf("workflow %s: %w", cw.wid, err) } - // 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) tm := cw.metrics.With(platform.KeyTriggerID, event.TriggerCapID) tm.RecordTriggerEventQueueWaitSeconds(ctx, c.clock.Since(event.ObservedAt).Seconds()) - semWaitStart := c.clock.Now() - free, err := c.admission.ExecutionConcurrency.Wait(ctx, 1) - tm.RecordExecutionSemaphoreWaitSeconds(ctx, c.clock.Now().Sub(semWaitStart).Seconds()) - if err != nil { - return fmt.Errorf("workflow %s: failed to acquire an execution slot: %w", cw.wid, err) - } + // 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) - c.eng.Go(func(context.Context) { + 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: the caller returns as soon as the execution has started, which must not cancel it. - err := engine.ExecuteTrigger(context.WithoutCancel(ctx), event) - // Starting the same event again is routine here: it is started when it is committed and again by the next - // observation, in case the first was missed. The engine ignores the repeats. + + // 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 @@ -597,6 +641,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. diff --git a/core/services/workflows/v2/triggers/coordinator_test.go b/core/services/workflows/v2/triggers/coordinator_test.go index 96dfdd7fad7..6d1b2b05b77 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" @@ -1233,7 +1235,7 @@ func TestCoordinator_StartExecution(t *testing.T) { release() }) - t.Run("holds an execution slot until the execution finishes", func(t *testing.T) { + 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)) @@ -1242,33 +1244,57 @@ func TestCoordinator_StartExecution(t *testing.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, so capacity reflects the first + // 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.NoError(t, <-second) - require.Eventually(t, executed(f, 2), 5*time.Second, 5*time.Millisecond) + require.Eventually(t, executed(f, 2), 5*time.Second, 5*time.Millisecond, "starts once the slot is free") }) - t.Run("a slot that cannot be taken is an error and nothing starts", func(t *testing.T) { + 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) - 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) - ctx, cancel := context.WithCancel(t.Context()) - cancel() - err := f.c.StartExecution(ctx, newEvent(f, "evt-2", 0)) - require.ErrorIs(t, err, context.Canceled) - assert.Len(t, f.engine.executed(), 1) + 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) @@ -1308,3 +1334,87 @@ func TestCoordinator_StartExecution(t *testing.T) { 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.Add(1) + go func() { + defer wg.Done() + 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") +} From 0a6870a3f0cce31646ca4955ccea6219e7d9b201 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Sun, 22 Nov 2026 11:09:13 -0600 Subject: [PATCH 25/38] defense --- core/services/ocr3_1/plugins/queue/blobs.go | 107 ++++--- .../ocr3_1/plugins/queue/blobs_test.go | 93 +++++++ .../ocr3_1/plugins/queue/config_test.go | 4 +- core/services/ocr3_1/plugins/queue/kvstate.go | 131 ++++++--- .../ocr3_1/plugins/queue/kvstate_test.go | 263 +++++++++++++++--- core/services/ocr3_1/plugins/queue/queue.go | 77 +++-- .../ocr3_1/plugins/queue/queue_test.go | 155 ++++++++++- 7 files changed, 685 insertions(+), 145 deletions(-) diff --git a/core/services/ocr3_1/plugins/queue/blobs.go b/core/services/ocr3_1/plugins/queue/blobs.go index 4350d528c8f..039edeac83b 100644 --- a/core/services/ocr3_1/plugins/queue/blobs.go +++ b/core/services/ocr3_1/plugins/queue/blobs.go @@ -15,12 +15,13 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb" ) -// blobCache is a short-lived cache for coordinating concurrent fetches of event blobs. +// 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 + mu sync.RWMutex + cache map[string]func() ([]byte, error) // blob handle -> blob + elements map[string]func() ([][]byte, error) // blob handle -> its events, split up } func (c *blobCache) fetchBlob(ctx context.Context, handle []byte) ([]byte, error) { @@ -52,19 +53,45 @@ func (c *blobCache) fetchBlob(ctx context.Context, handle []byte) ([]byte, error return fn() } -// fetchCoordinatedEventFromBlob fetches and extracts the idx-th event from the blob, without unmarshaling any other events. +// 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) { + 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) { - bb, err := fetcher.fetchBlob(ctx, handle) + elements, err := fetcher.fetchElements(ctx, handle) if err != nil { return nil, nil, fmt.Errorf("failed to fetch blob: %w", err) } - - coordEvent, eb, err := extractEvent(bb, idx) - if err != nil { - return nil, nil, err + if idx < 0 || idx >= len(elements) { + return nil, nil, fmt.Errorf("index %d out of range", idx) } - return coordEvent, eb, nil + 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 @@ -79,50 +106,48 @@ func (c *consensusQueuePlugin) maxEventBytes() int { return max(0, c.limits.MaxBlobPayloadBytes-maxEventFramingOverhead) } -// extractEvent extracts the idx-th event from the blob, without unmarshaling any other events. -func extractEvent(b []byte, idx int) (*pb.CoordinatedEvent, []byte, error) { - i := 0 +// 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 max events. +func splitEvents(b []byte, max int) ([][]byte, error) { + var events [][]byte for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) if n < 0 { - return nil, nil, protowire.ParseError(n) + return nil, protowire.ParseError(n) } b = b[n:] - if num == coordinatedEventsFieldNumber { - if typ != protowire.BytesType { - return nil, nil, fmt.Errorf("expected bytes type for field %d, got %d", coordinatedEventsFieldNumber, typ) - } - - v, m := protowire.ConsumeBytes(b) - if m < 0 { - return nil, nil, protowire.ParseError(m) - } - - if i == idx { - var event pb.CoordinatedEvent - if err := proto.Unmarshal(v, &event); err != nil { - return nil, v, fmt.Errorf("failed to unmarshal event: %w", err) - } - - return &event, v, nil - } - - // advance - i++ - b = b[m:] - continue - } else { + if num != coordinatedEventsFieldNumber { n := protowire.ConsumeFieldValue(num, typ, b) if n < 0 { - return nil, nil, protowire.ParseError(n) + return nil, protowire.ParseError(n) } b = b[n:] + continue } - } - return nil, nil, fmt.Errorf("index %d out of range", idx) + 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) == max { + return nil, fmt.Errorf("blob has more than %d events", max) + } + + events = append(events, v) + b = b[m:] + } + return events, nil } const ( diff --git a/core/services/ocr3_1/plugins/queue/blobs_test.go b/core/services/ocr3_1/plugins/queue/blobs_test.go index 15415762037..ed71c6dbaa8 100644 --- a/core/services/ocr3_1/plugins/queue/blobs_test.go +++ b/core/services/ocr3_1/plugins/queue/blobs_test.go @@ -3,6 +3,8 @@ package queue import ( "context" "errors" + "fmt" + "math" "sync" "testing" "time" @@ -515,3 +517,94 @@ func (c *consensusQueuePlugin) broadcastAsBlob(ctx context.Context, broadcaster 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 index cf800c0c201..0dd3b68d597 100644 --- a/core/services/ocr3_1/plugins/queue/config_test.go +++ b/core/services/ocr3_1/plugins/queue/config_test.go @@ -262,7 +262,9 @@ func TestCalibration_KVState(t *testing.T) { e.ObservedAts = append(e.ObservedAts, randTS(rng)) e.Deadlines = append(e.Deadlines, randTS(rng)) } - e.Blobs = []*pb.CoordinatedEventBlobHandle{{Blob: uint32(rng.Intn(maxObservedBlobHandles * n)), Element: uint32(rng.Intn(maxObservedEvents))}} + 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))}) + } entry := &pb.ConsensusQueueObservedEventEntry{TimelessHash: make([]byte, sha256.Size), Event: e} return protowire.SizeBytes(proto.Size(entry)) + protowire.SizeTag(1) }) diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index eb1308da51f..0aef2ac23a1 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -5,6 +5,7 @@ import ( "container/heap" "fmt" "maps" + "math" "slices" "sort" "time" @@ -23,7 +24,8 @@ const numKVKeys = 4 // KV store keys const ( - // observed events waiting for consensus (F+1 <= observers <2F+1) + // 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 } @@ -108,37 +110,39 @@ func (p *priorityQueue) mustPop() *pb.ConsensusQueueEvent { return heap.Pop(p).(*pb.ConsensusQueueEvent) } -// popLimited pops up to capacity events from the queue, each of which must also have sufficient wf capacity. +// 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. -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() +// +// 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) []*pb.ConsensusQueueEvent { + var popped, skipped []*pb.ConsensusQueueEvent + for len(popped) < n { + event := p.mustPop() if event == nil { break } if event.Deadline.AsTime().Before(expiration) { - // drop expired - continue + continue // drop expired } if capPerWF[event.WorkflowID] == 0 { - // ignore but restore after - wfLimited = append(wfLimited, event) + skipped = append(skipped, event) continue } capPerWF[event.WorkflowID]-- - break + popped = append(popped, event) } - // restore omitted for next time - for _, limited := range wfLimited { - p.push(limited) + for _, event := range skipped { + p.push(event) } - return + return popped } type blobHandleMap map[string]map[string]uint32 // eventHash -> blobHandle -> idx @@ -161,11 +165,42 @@ func (m blobHandleMap) addAll(eventHash string, blobHandles map[string]uint32) { } } +// 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 +} + type kvState struct { // observedEventsKey observedEvents map[string]*pb.ConsensusQueueObservedEvent // key: timeless hash observedEventEntries []*pb.ConsensusQueueObservedEventEntry // only populated before write - observedBlobs blobHandleMap + observedBlobs voterBlobs observedBlobHandles [][]byte // only populated before write // priorityQueueKey @@ -200,7 +235,9 @@ func (s *kvState) loadFrom(kv ocr3_1types.KeyValueStateReadWriter) error { for _, event := range s.queuedEvents { for _, blob := range event.GetBlobs() { - s.queuedBlobs.add(string(event.TimelessHash), string(queuedBlobs[blob.Blob]), blob.Element) + if int(blob.Blob) < len(queuedBlobs) { + s.queuedBlobs.add(string(event.TimelessHash), string(queuedBlobs[blob.Blob]), blob.Element) + } } } @@ -225,13 +262,13 @@ func readQueuedEvents(kv ocr3_1types.KeyValueStateReader) ([]*pb.ConsensusQueueE return nil, nil } -func readObservedEvents(kv ocr3_1types.KeyValueStateReader) (observedEvents map[string]*pb.ConsensusQueueObservedEvent, observedBlobs blobHandleMap, err error) { +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(blobHandleMap) + observedBlobs = make(voterBlobs) if v != nil { var observed pb.ConsensusQueueObservedEvents if err = proto.Unmarshal(v, &observed); err != nil { @@ -245,8 +282,11 @@ func readObservedEvents(kv ocr3_1types.KeyValueStateReader) (observedEvents map[ blobHandles := observed.GetBlobHandles() for eventHash, event := range observedEvents { - for _, b := range event.GetBlobs() { - observedBlobs.add(eventHash, string(blobHandles[b.Blob]), b.Element) + // 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 { @@ -298,19 +338,24 @@ func (s *kvState) prepareWriteObservedEvents() { return cmp.Or(cmp.Compare(len(eb.NodeIds), len(ea.NodeIds)), cmp.Compare(a, b)) }) { event := s.observedEvents[eventHash] - event.Blobs = nil // replace all - for _, blobHandle := range slices.Sorted(maps.Keys(s.observedBlobs[eventHash])) { - ei := s.observedBlobs[eventHash][blobHandle] - idx, ok := observedBlobIndexes[blobHandle] + 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[blobHandle] = idx - s.observedBlobHandles = append(s.observedBlobHandles, []byte(blobHandle)) + observedBlobIndexes[ref.handle] = idx + s.observedBlobHandles = append(s.observedBlobHandles, []byte(ref.handle)) } event.Blobs = append(event.Blobs, &pb.CoordinatedEventBlobHandle{ Blob: uint32(idx), - Element: ei, + Element: ref.element, }) } @@ -384,15 +429,7 @@ func (s *kvState) trimConsensusEvents(maxTotalBytes int) { // 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) { - for len(s.queuedEvents) > 0 && len(s.consensusEvents) < capacity { - event := s.queuedEvents.popLimited(capPerWF, expiration) - if event == nil { - break - } - - s.consensusEvents = append(s.consensusEvents, event) - } - + s.consensusEvents = append(s.consensusEvents, s.queuedEvents.popEligible(capacity-len(s.consensusEvents), capPerWF, expiration)...) s.trimConsensusEvents(maxTotalBytes) } @@ -499,16 +536,17 @@ func (s *kvState) pruneExpiredObservations(expiration time.Time) { if !slices.ContainsFunc(v.Deadlines, func(t *timestamppb.Timestamp) bool { return !t.AsTime().Before(expiration) }) { + delete(s.observedBlobs, k) return true // all deadlines expired, so delete the whole thing } // some expired, so prune them for i := 0; i < len(v.Deadlines); { if v.Deadlines[i].AsTime().Before(expiration) { + delete(s.observedBlobs[k], v.NodeIds[i]) // the vote goes, and so does its blob v.NodeIds = slices.Delete(v.NodeIds, i, i+1) v.ObservedAts = slices.Delete(v.ObservedAts, i, i+1) v.Deadlines = slices.Delete(v.Deadlines, i, i+1) - // note: s.observedBlobs tracks blobs while in memory } else { i++ } @@ -520,7 +558,7 @@ func (s *kvState) pruneExpiredObservations(expiration time.Time) { // addObserved adds the observed events to the set, promoting to the priority queue on 2f+1 and calling onQueued. // Events with fewer than f+1 observations are ignored. -func (s *kvState) addObservedEvents(f int, toAdd map[string]*pb.ConsensusQueueObservedEvent, observedBlobs blobHandleMap, onQueued func(event *pb.ConsensusQueueEvent)) { +func (s *kvState) addObservedEvents(f int, toAdd map[string]*pb.ConsensusQueueObservedEvent, observedBlobs voterBlobs, onQueued func(event *pb.ConsensusQueueEvent)) { alreadyQueued := make(map[string]struct{}, len(s.queuedEvents)) for _, e := range s.queuedEvents { alreadyQueued[string(e.TimelessHash)] = struct{}{} @@ -537,12 +575,12 @@ func (s *kvState) addObservedEvents(f int, toAdd map[string]*pb.ConsensusQueueOb switch { case len(eventToAdd.NodeIds) >= 2*f+1: // new proposal straight to priority queue - s.queuedBlobs.addAll(eventHash, observedBlobs[eventHash]) + 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.addAll(eventHash, observedBlobs[eventHash]) + s.observedBlobs[eventHash] = maps.Clone(observedBlobs[eventHash]) s.observedEvents[eventHash] = eventToAdd default: // new proposal without enough observations < f + 1 @@ -555,20 +593,21 @@ func (s *kvState) addObservedEvents(f int, toAdd map[string]*pb.ConsensusQueueOb obsEvent.NodeIds = append(obsEvent.NodeIds, node) obsEvent.ObservedAts = append(obsEvent.ObservedAts, eventToAdd.ObservedAts[i]) obsEvent.Deadlines = append(obsEvent.Deadlines, eventToAdd.Deadlines[i]) - // note: s.observedBlobs tracks blobs while in memory } else { // overwrite previous observation obsEvent.ObservedAts[prev] = eventToAdd.ObservedAts[i] obsEvent.Deadlines[prev] = eventToAdd.Deadlines[i] - // note: s.observedBlobs tracks blobs while in memory } - } - s.observedBlobs.addAll(eventHash, observedBlobs[eventHash]) + // 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[eventHash] = s.observedBlobs[eventHash] + s.queuedBlobs.addAll(eventHash, s.observedBlobs.handles(eventHash)) delete(s.observedBlobs, eventHash) event := s.queueObservations(eventHash, obsEvent) onQueued(event) diff --git a/core/services/ocr3_1/plugins/queue/kvstate_test.go b/core/services/ocr3_1/plugins/queue/kvstate_test.go index 5be6f3be2d3..ad4c5a7c48a 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate_test.go +++ b/core/services/ocr3_1/plugins/queue/kvstate_test.go @@ -49,7 +49,7 @@ func obsEvent(wf, execID string, base int64, nodes ...byte) *pb.ConsensusQueueOb func newKVState() *kvState { return &kvState{ observedEvents: map[string]*pb.ConsensusQueueObservedEvent{}, - observedBlobs: blobHandleMap{}, + observedBlobs: voterBlobs{}, queuedBlobs: blobHandleMap{}, } } @@ -131,6 +131,57 @@ func TestBlobHandleMap(t *testing.T) { 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)) + } + 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() @@ -186,7 +237,7 @@ func TestAddObservedEvents(t *testing.T) { t.Parallel() s := newKVState() var queued []*pb.ConsensusQueueEvent - s.addObservedEvents(f, map[string]*pb.ConsensusQueueObservedEvent{"h": obsEvent("wf", "e", 100, 1)}, blobHandleMap{}, collect(&queued)) + 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) @@ -196,21 +247,24 @@ func TestAddObservedEvents(t *testing.T) { t.Parallel() s := newKVState() var queued []*pb.ConsensusQueueEvent - blobs := blobHandleMap{} - blobs.add("h", "blob", 0) + 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[string]uint32{"blob": 0}, s.observedBlobs["h"]) + 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 := blobHandleMap{} - blobs.add("h", "blob", 0) + 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) @@ -224,12 +278,14 @@ func TestAddObservedEvents(t *testing.T) { t.Parallel() s := newKVState() var queued []*pb.ConsensusQueueEvent - // previously observed by nodes 1 & 2 (with their blob) + // previously observed by nodes 1 & 2 (with their blobs) s.observedEvents["h"] = obsEvent("wf", "e", 100, 1, 2) - s.observedBlobs.add("h", "old-blob", 1) + s.observedBlobs.add("h", 1, "blob-1", 1) + s.observedBlobs.add("h", 2, "old-blob-2", 2) - newBlobs := blobHandleMap{} - newBlobs.add("h", "new-blob", 5) + 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) @@ -238,7 +294,7 @@ func TestAddObservedEvents(t *testing.T) { 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{"old-blob": 1, "new-blob": 5}, s.queuedBlobs["h"]) + 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) { @@ -247,7 +303,7 @@ func TestAddObservedEvents(t *testing.T) { 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}, blobHandleMap{}, func(*pb.ConsensusQueueEvent) {}) + s.addObservedEvents(f, map[string]*pb.ConsensusQueueObservedEvent{"h": toAdd}, voterBlobs{}, func(*pb.ConsensusQueueEvent) {}) }) got := s.observedEvents["h"] require.NotNil(t, got) @@ -261,7 +317,8 @@ func TestKVState_RoundTrip(t *testing.T) { s := newKVState() s.observedEvents["obs"] = obsEvent("wf", "e-obs", 100, 1, 2) - s.observedBlobs.add("obs", "blobA", 0) + 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)) @@ -276,7 +333,7 @@ func TestKVState_RoundTrip(t *testing.T) { var loaded kvState require.NoError(t, loaded.loadFrom(kv)) require.Contains(t, loaded.observedEvents, "obs") - assert.Equal(t, map[string]uint32{"blobA": 0}, loaded.observedBlobs["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"]) @@ -295,7 +352,8 @@ func TestKVState_WriteToWithoutSizeCheck(t *testing.T) { s := newKVState() s.observedEvents["obs"] = obsEvent("wf", "e-obs", 100, 1, 2) - s.observedBlobs.add("obs", "blobA", 0) + 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) @@ -507,8 +565,12 @@ func TestKVState_SizeOfMatchesWrittenBytes(t *testing.T) { s := newKVState() s.observedEvents["o1"] = obsEvent("wf", "e-o1", 100, 1, 2) s.observedEvents["o2"] = obsEvent("wf", "e-o2", 100, 1, 2, 3) - s.observedBlobs.add("o1", "blobA", 0) - s.observedBlobs.add("o2", "blobA", 1) + 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)) @@ -578,20 +640,22 @@ func TestPrepareWriteObservedEvents_SharedBlobs(t *testing.T) { s := newKVState() s.observedEvents["h1"] = obsEvent("wf", "e1", 100, 1, 2) s.observedEvents["h2"] = obsEvent("wf", "e2", 100, 1, 2) - s.observedBlobs.add("h1", "blobX", 0) - s.observedBlobs.add("h2", "blobX", 1) - s.observedBlobs.add("h2", "blobY", 0) // two observers used different blobs + 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) + 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 { - got := map[string]uint32{} - for _, b := range entry.Event.Blobs { - got[string(s.observedBlobHandles[b.Blob])] = b.Element + 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, s.observedBlobs[hash][voter], blobRef{string(s.observedBlobHandles[b.Blob]), b.Element}, "event %s voter %d", hash, voter) } - assert.Equal(t, s.observedBlobs[string(entry.TimelessHash)], got) } } @@ -625,7 +689,7 @@ func TestAddObservedEvents_Order(t *testing.T) { for range 20 { // map iteration is random; callbacks must not depend on it s := newKVState() var got []string - s.addObservedEvents(1, toAdd, blobHandleMap{}, func(e *pb.ConsensusQueueEvent) { got = append(got, string(e.TimelessHash)) }) + 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) } } @@ -641,7 +705,7 @@ func TestAddObservedEvents_AlreadyQueued(t *testing.T) { var queued int s.addObservedEvents(1, map[string]*pb.ConsensusQueueObservedEvent{"h": obsEvent("wf", "exec", 100, 1, 2, 3)}, - blobHandleMap{}, func(*pb.ConsensusQueueEvent) { queued++ }) + voterBlobs{}, func(*pb.ConsensusQueueEvent) { queued++ }) assert.Zero(t, queued, "already queued") assert.Len(t, s.queuedEvents, 1, "no duplicate in the priority queue") @@ -652,7 +716,7 @@ func TestAddObservedEvents_UpdateDeduplicatesNodes(t *testing.T) { 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)}, blobHandleMap{}, func(*pb.ConsensusQueueEvent) {}) + 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) } @@ -720,8 +784,8 @@ func randomState(seed int64) (s *kvState, newlyQueued []string) { nodes[v] = byte(v) } s.observedEvents[hash] = obsEvent(hexID("wf", i%7), hexID("exec-o", i), int64(100+rng.Intn(1000)), nodes...) - for range 1 + rng.Intn(2) { - s.observedBlobs.add(hash, pool[rng.Intn(len(pool))], uint32(rng.Intn(1000))) + for _, node := range nodes { + s.observedBlobs.add(hash, node, pool[rng.Intn(len(pool))], uint32(rng.Intn(1000))) } } for i := range 5 + rng.Intn(200) { @@ -770,3 +834,140 @@ func TestPruneToFit_MatchesNaive(t *testing.T) { } } } + +// 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)) + } + } + 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 + for _, event := range singlePass.popEligible(want, capsB, expiration) { + 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)) + assert.Empty(t, pq.popEligible(0, map[string]uint32{testWF: 5}, time.Unix(0, 0)), "nothing wanted") + assert.Empty(t, pq.popEligible(-3, map[string]uint32{testWF: 5}, time.Unix(0, 0)), "a negative amount is nothing") + assert.Equal(t, 1, pq.Len()) + assert.Empty(t, (&priorityQueue{}).popEligible(5, nil, time.Unix(0, 0)), "an empty queue") +} + +// 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)) + } + } + }) + } + } +} diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index 079c16bf96a..9ec72ba5ee4 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -592,7 +592,7 @@ type observations struct { medianCap uint32 medianCapPerWF map[string]uint32 // wf ID -> capacity newObservedEvents map[string]*pb.ConsensusQueueObservedEvent // key: timeless hash - observedBlobs blobHandleMap + observedBlobs voterBlobs err error } @@ -600,7 +600,7 @@ type observations struct { func (res *observations) aggregate(ctx context.Context, f int, aos []ocrtypes.AttributedObservation) { res.medianCapPerWF = make(map[string]uint32) res.newObservedEvents = make(map[string]*pb.ConsensusQueueObservedEvent) - res.observedBlobs = make(blobHandleMap) + 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 @@ -652,7 +652,7 @@ func (res *observations) aggregate(ctx context.Context, f int, aos []ocrtypes.At // 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), string(blobHandles[event.Blobs[0].Blob]), event.Blobs[0].Element) + 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{ @@ -720,7 +720,9 @@ func (c *consensusQueuePlugin) tryStartExecutions(ctx context.Context, done chan var wg sync.WaitGroup for _, consensusEvent := range consensusEvents { wg.Add(1) - c.eng.GoCtx(ctx, func(ctx context.Context) { + // 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 { @@ -735,27 +737,11 @@ func (c *consensusQueuePlugin) tryStartExecutions(ctx context.Context, done chan } func (c *consensusQueuePlugin) tryStartExecution(ctx context.Context, fetcher *blobCache, consensusEvent *pb.ConsensusQueueEvent, blobHandles [][]byte) error { - // any blob will do, first that exists - var pbEvent *pb.CoordinatedEvent - var errs []error - for _, blob := range consensusEvent.Blobs { - var err error - if int(blob.Blob) >= len(blobHandles) { - c.lggr.Errorw("Blob handle index out of bounds", "index", int(blob.Blob), "len", len(blobHandles)) - continue - } - blobHandle := blobHandles[int(blob.Blob)] - pbEvent, _, err = fetchCoordinatedEventFromBlob(ctx, fetcher, blobHandle, int(blob.Element)) - if err != nil { - errs = append(errs, fmt.Errorf("failed to fetch blob: %w", err)) - c.lggr.Errorw("Failed to fetch blob", "handle", blobHandle, "index", blob.Element, "err", err) - continue // try next blob - } - break - } - if pbEvent == nil { - return fmt.Errorf("failed to fetch blob from all %d handles: %w", len(consensusEvent.Blobs), errors.Join(errs...)) + 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 @@ -769,6 +755,49 @@ func (c *consensusQueuePlugin) tryStartExecution(ctx context.Context, fetcher *b 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, and cancelling would cache the cancellation as the result for all of them. 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, _ uint64, _ ocr3_1types.ReportsPlusPrecursor) ([]ocr3types.ReportPlus[[]byte], error) { return nil, nil } diff --git a/core/services/ocr3_1/plugins/queue/queue_test.go b/core/services/ocr3_1/plugins/queue/queue_test.go index da50b2ebd17..e35df710b03 100644 --- a/core/services/ocr3_1/plugins/queue/queue_test.go +++ b/core/services/ocr3_1/plugins/queue/queue_test.go @@ -21,6 +21,7 @@ import ( "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/timestamppb" @@ -338,7 +339,7 @@ func TestObservationsAggregate(t *testing.T) { require.NotNil(t, got) assert.Equal(t, []byte{0, 1, 3}, got.NodeIds) assert.Len(t, got.Deadlines, 3) - assert.Equal(t, map[string]uint32{"handle": 0}, res.observedBlobs[string(hash)]) + assert.Equal(t, map[uint8]blobRef{0: {"handle", 0}, 1: {"handle", 0}, 3: {"handle", 0}}, res.observedBlobs[string(hash)], "each voter's blob") }) } @@ -796,7 +797,7 @@ func TestStateTransition_Lifecycle(t *testing.T) { 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[string]uint32{string(handleBytes(1)): 0}, st.observedBlobs[string(e[0].hash)]) + 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)) @@ -2306,3 +2307,153 @@ func BenchmarkFullStateTransitionOverLimit(b *testing.B) { 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)) // 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") +} From 408446623330de38ec60372cf879db84e38dda84 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Sun, 22 Nov 2026 16:04:38 -0600 Subject: [PATCH 26/38] metrics --- core/cmd/shell.go | 2 + core/services/chainlink/application.go | 1 + core/services/ocr2/delegate.go | 10 +- .../ocr3_1/beholderwrapper/factory.go | 16 +- .../ocr3_1/beholderwrapper/factory_test.go | 7 +- .../services/ocr3_1/beholderwrapper/plugin.go | 2 + .../ocr3_1/beholderwrapper/plugin_test.go | 75 ++++- core/services/ocr3_1/beholderwrapper/types.go | 37 ++- core/services/ocr3_1/plugins/queue/kvstate.go | 31 +- .../ocr3_1/plugins/queue/kvstate_test.go | 60 +++- core/services/ocr3_1/plugins/queue/metrics.go | 171 +++++++++++ .../ocr3_1/plugins/queue/metrics_test.go | 273 ++++++++++++++++++ core/services/ocr3_1/plugins/queue/queue.go | 45 ++- .../ocr3_1/plugins/queue/queue_test.go | 26 +- .../central_trigger_queue_metrics.go | 15 + .../workflows/monitoring/monitoring.go | 6 + .../workflows/v2/triggers/coordinator.go | 12 + .../workflows/v2/triggers/coordinator_test.go | 20 ++ core/services/workflows/v2/triggers/queue.go | 3 +- .../workflows/v2/triggers/queue_test.go | 32 ++ deployment/cre/jobs/propose_job_spec_test.go | 2 - 21 files changed, 798 insertions(+), 48 deletions(-) create mode 100644 core/services/ocr3_1/plugins/queue/metrics.go create mode 100644 core/services/ocr3_1/plugins/queue/metrics_test.go diff --git a/core/cmd/shell.go b/core/cmd/shell.go index 9f2f36fed74..fc9e91f3e16 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/services/chainlink/application.go b/core/services/chainlink/application.go index 855f6313efb..f0d02863f76 100644 --- a/core/services/chainlink/application.go +++ b/core/services/chainlink/application.go @@ -843,6 +843,7 @@ func NewApplication(ctx context.Context, opts ApplicationOpts) (Application, err 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/ocr2/delegate.go b/core/services/ocr2/delegate.go index 3f55eee07b8..302355df19e 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" @@ -161,6 +162,7 @@ type Delegate struct { 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 @@ -316,6 +318,8 @@ type DelegateOpts struct { 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). @@ -367,6 +371,7 @@ func NewDelegate( ocrConfigService: opts.OCRConfigService, triggerCoordinator: opts.TriggerCoordinator, triggerQueue: opts.TriggerQueue, + meter: opts.Meter, defaultBootstrappers: opts.DefaultBootstrappers, capRegistryAddress: opts.CapRegistryAddress, capRegistryChainID: opts.CapRegistryChainID, @@ -915,12 +920,12 @@ func (d *Delegate) newServicesConsensusQueue( MetricsRegisterer: prometheus.WrapRegistererWith(map[string]string{"job_name": jb.Name.ValueOrZero()}, prometheus.DefaultRegisterer), } - rpf, err := queue.NewConsensusQueuePluginFactory(lggr, cfg, d.limitsFactory, d.triggerCoordinator, d.triggerQueue) + rpf, err := queue.NewConsensusQueuePluginFactory(lggr, cfg, 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) @@ -1123,6 +1128,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..e828a68f803 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,51 @@ 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) { + 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") + } + + // 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..8c0b9b86507 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( + 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/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index 0aef2ac23a1..c8e9346aeb2 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -36,7 +36,8 @@ const ( ) type stateWriter struct { - kv ocr3_1types.KeyValueStateReadWriter + kv ocr3_1types.KeyValueStateReadWriter + sizes map[string]int // key -> bytes written } func (s *stateWriter) writeValue[M proto.Message](key string, m M) error { @@ -45,6 +46,10 @@ func (s *stateWriter) writeValue[M proto.Message](key string, m M) error { 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) } @@ -117,8 +122,8 @@ func (p *priorityQueue) mustPop() *pb.ConsensusQueueEvent { // 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) []*pb.ConsensusQueueEvent { - var popped, skipped []*pb.ConsensusQueueEvent +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 { @@ -126,6 +131,7 @@ func (p *priorityQueue) popEligible(n int, capPerWF map[string]uint32, expiratio } if event.Deadline.AsTime().Before(expiration) { + expired++ continue // drop expired } @@ -142,7 +148,7 @@ func (p *priorityQueue) popEligible(n int, capPerWF map[string]uint32, expiratio p.push(event) } - return popped + return popped, expired } type blobHandleMap map[string]map[string]uint32 // eventHash -> blobHandle -> idx @@ -196,7 +202,17 @@ func (m voterBlobs) handles(eventHash string) map[string]uint32 { 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 @@ -429,7 +445,9 @@ func (s *kvState) trimConsensusEvents(maxTotalBytes int) { // 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) { - s.consensusEvents = append(s.consensusEvents, s.queuedEvents.popEligible(capacity-len(s.consensusEvents), capPerWF, expiration)...) + popped, expired := s.queuedEvents.popEligible(capacity-len(s.consensusEvents), capPerWF, expiration) + s.stats.expiredQueued += expired + s.consensusEvents = append(s.consensusEvents, popped...) s.trimConsensusEvents(maxTotalBytes) } @@ -458,6 +476,7 @@ func (s *kvState) pruneObservedToFit(maxTotalBytes int) { 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 @@ -496,6 +515,7 @@ func (s *kvState) pruneQueuedToFit(newlyQueued []string, maxTotalBytes int) { return fits() }) drop(n) + s.stats.prunedQueued += n // rebuild the priority queue heap.Init(&s.queuedEvents) @@ -537,6 +557,7 @@ func (s *kvState) pruneExpiredObservations(expiration time.Time) { return !t.AsTime().Before(expiration) }) { delete(s.observedBlobs, k) + s.stats.expiredObserved++ return true // all deadlines expired, so delete the whole thing } diff --git a/core/services/ocr3_1/plugins/queue/kvstate_test.go b/core/services/ocr3_1/plugins/queue/kvstate_test.go index ad4c5a7c48a..29bdccaaf96 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate_test.go +++ b/core/services/ocr3_1/plugins/queue/kvstate_test.go @@ -906,7 +906,8 @@ func TestPopEligible_MatchesPoppingOneAtATime(t *testing.T) { wantPopped = append(wantPopped, event.ExecutionID) } var gotPopped []string - for _, event := range singlePass.popEligible(want, capsB, expiration) { + popped, _ := singlePass.popEligible(want, capsB, expiration) + for _, event := range popped { gotPopped = append(gotPopped, event.ExecutionID) } @@ -928,10 +929,14 @@ func TestPopEligible_Edges(t *testing.T) { var pq priorityQueue pq.push(qEvent(testWF, "a", "h1", 200)) - assert.Empty(t, pq.popEligible(0, map[string]uint32{testWF: 5}, time.Unix(0, 0)), "nothing wanted") - assert.Empty(t, pq.popEligible(-3, map[string]uint32{testWF: 5}, time.Unix(0, 0)), "a negative amount is nothing") + popped, expired := 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()) - assert.Empty(t, (&priorityQueue{}).popEligible(5, nil, time.Unix(0, 0)), "an empty queue") + 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 @@ -971,3 +976,50 @@ func BenchmarkPopEligible_StuckEvents(b *testing.B) { } } } + +// 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/metrics.go b/core/services/ocr3_1/plugins/queue/metrics.go new file mode 100644 index 00000000000..ef5ac42b947 --- /dev/null +++ b/core/services/ocr3_1/plugins/queue/metrics.go @@ -0,0 +1,171 @@ +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 + 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.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()) +} + +// 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..35670240c64 --- /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, int64(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 9ec72ba5ee4..22bc9984968 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -20,6 +20,7 @@ import ( "time" "github.com/smartcontractkit/libocr/commontypes" + "go.opentelemetry.io/otel/metric" "golang.org/x/sync/errgroup" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" @@ -47,6 +48,7 @@ type consensusQueuePluginFactory struct { triggerCoordinator triggers.Coordinator triggerQueue triggers.Queue expirationDur func(context.Context) (time.Duration, error) + meter metric.Meter } func NewConsensusQueuePluginFactory( @@ -55,6 +57,7 @@ func NewConsensusQueuePluginFactory( limitsFactory limits.Factory, triggerCoordinator triggers.Coordinator, triggerQueue triggers.Queue, + meter metric.Meter, ) (ocr3_1types.ReportingPluginFactory[[]byte], error) { if cfg == nil { return nil, errors.New("cfg cannot be nil") @@ -65,17 +68,25 @@ func NewConsensusQueuePluginFactory( 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, cfg: cfg, triggerCoordinator: triggerCoordinator, triggerQueue: triggerQueue, expirationDur: triggers.ConsensusQueueExpirationGrace(limitsFactory), + meter: meter, }, nil } func (c *consensusQueuePluginFactory) NewReportingPlugin(ctx context.Context, config ocr3types.ReportingPluginConfig, blobs ocr3_1types.BlobBroadcastFetcher) (ocr3_1types.ReportingPlugin[[]byte], ocr3_1types.ReportingPluginInfo, error) { - plugin := newConsensusQueuePlugin(c.lggr, config, c.cfg.Limits, c.triggerCoordinator, c.triggerQueue, c.expirationDur, blobs) + metrics, err := newPluginMetrics(c.meter, config.ConfigDigest.String()) + if err != nil { + return nil, nil, err + } + plugin := newConsensusQueuePlugin(c.lggr, config, c.cfg.Limits, c.triggerCoordinator, c.triggerQueue, c.expirationDur, blobs, metrics) pluginInfo := ocr3_1types.ReportingPluginInfo1{ Name: "ConsensusQueueReportingPlugin", Limits: c.cfg.Limits, @@ -96,12 +107,13 @@ type consensusQueuePlugin struct { triggerQueue triggers.Queue blobBroadcastFetcher ocr3_1types.BlobBroadcastFetcher expirationDur func(context.Context) (time.Duration, error) + metrics *pluginMetrics } 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, + blobs ocr3_1types.BlobBroadcastFetcher, metrics *pluginMetrics, ) *consensusQueuePlugin { c := &consensusQueuePlugin{ lggr: logger.Named(lggr, "ConsensusQueuePlugin"), @@ -112,6 +124,7 @@ func newConsensusQueuePlugin( triggerQueue: triggerQueue, blobBroadcastFetcher: blobs, expirationDur: expirationGraceDur, + metrics: metrics, } c.Service, c.eng = services.Config{ Name: "ConsensusQueueReportingPlugin", @@ -176,6 +189,7 @@ func (c *consensusQueuePlugin) Observation( } } + c.metrics.recordObservation(ctx, len(obs.Events)) return proto.MarshalOptions{Deterministic: true}.Marshal(obs) } @@ -571,22 +585,47 @@ func (c *consensusQueuePlugin) StateTransition( // update state state.pruneExpiredObservations(obs.medianExpiration) var queuedTimelessHashes []string // eligible for pruning later if necessary + var admitted int state.addObservedEvents(c.onchainCfg.F, obs.newObservedEvents, obs.observedBlobs, func(event *pb.ConsensusQueueEvent) { queuedTimelessHashes = append(queuedTimelessHashes, string(event.TimelessHash)) + admitted++ }) state.popConsensusEvents(int(obs.medianCap), obs.medianCapPerWF, 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 - if err := state.writeTo(&stateWriter{kv: kvReaderWriter}); err != nil { + 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 } +// 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 medianCap uint32 diff --git a/core/services/ocr3_1/plugins/queue/queue_test.go b/core/services/ocr3_1/plugins/queue/queue_test.go index e35df710b03..cf8068df793 100644 --- a/core/services/ocr3_1/plugins/queue/queue_test.go +++ b/core/services/ocr3_1/plugins/queue/queue_test.go @@ -21,6 +21,7 @@ import ( "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" @@ -43,7 +44,7 @@ func TestConsensusQueuePluginFactory_NewReportingPlugin(t *testing.T) { t.Parallel() cfg := &PluginConfig{Limits: ocr3_1types.ReportingPluginLimits{MaxKeyValueModifiedKeys: 1}} - factory, err := NewConsensusQueuePluginFactory(logger.Test(t), cfg, limits.Factory{}, noopCoordinator{}, noopQueue{}) + factory, err := NewConsensusQueuePluginFactory(logger.Test(t), cfg, 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}, nil) @@ -100,6 +101,8 @@ func (n noopCoordinator) StartExecution(ctx context.Context, event triggers.Coor 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 { @@ -239,7 +242,15 @@ func testPlugin(t testing.TB, q sliceQueue, blobs ocr3_1types.BlobBroadcastFetch 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) + 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) { @@ -1185,7 +1196,7 @@ func newCommitPlugin(t testing.TB, coord triggers.Coordinator, q triggers.Queue, } 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) + 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 @@ -1682,13 +1693,20 @@ func TestNewConsensusQueuePluginFactory_Validation(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - f, err := NewConsensusQueuePluginFactory(logger.Test(t), tt.cfg, limits.Factory{}, tt.coord, tt.queue) + f, err := NewConsensusQueuePluginFactory(logger.Test(t), tt.cfg, 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), &PluginConfig{}, limits.Factory{}, noopCoordinator{}, noopQueue{}, nil) + require.ErrorContains(t, err, "meter") + assert.Nil(t, f) +} + func TestBroadcastAsBlob_LargestFit(t *testing.T) { t.Parallel() diff --git a/core/services/workflows/monitoring/central_trigger_queue_metrics.go b/core/services/workflows/monitoring/central_trigger_queue_metrics.go index 25150404aa5..c03775a66a1 100644 --- a/core/services/workflows/monitoring/central_trigger_queue_metrics.go +++ b/core/services/workflows/monitoring/central_trigger_queue_metrics.go @@ -26,6 +26,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. @@ -78,6 +79,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 } @@ -115,6 +125,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 bc2fecc1448..529a7191021 100644 --- a/core/services/workflows/monitoring/monitoring.go +++ b/core/services/workflows/monitoring/monitoring.go @@ -567,6 +567,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{ diff --git a/core/services/workflows/v2/triggers/coordinator.go b/core/services/workflows/v2/triggers/coordinator.go index 5c99647df77..cd547760c1c 100644 --- a/core/services/workflows/v2/triggers/coordinator.go +++ b/core/services/workflows/v2/triggers/coordinator.go @@ -91,6 +91,10 @@ type Coordinator interface { // 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 @@ -553,6 +557,14 @@ func (c *coordinator) Ack(ctx context.Context, triggerCapID, triggerRegistration return Ack(ctx, lggr, wfMetrics, triggerCapID, triggerRegistrationID, eventID, handle) } +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 { diff --git a/core/services/workflows/v2/triggers/coordinator_test.go b/core/services/workflows/v2/triggers/coordinator_test.go index 6d1b2b05b77..597439ebbb8 100644 --- a/core/services/workflows/v2/triggers/coordinator_test.go +++ b/core/services/workflows/v2/triggers/coordinator_test.go @@ -1418,3 +1418,23 @@ func TestCoordinator_LearnsEventLifetime(t *testing.T) { 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/queue.go b/core/services/workflows/v2/triggers/queue.go index ff247247da3..390d2e03116 100644 --- a/core/services/workflows/v2/triggers/queue.go +++ b/core/services/workflows/v2/triggers/queue.go @@ -12,6 +12,7 @@ import ( "maps" "slices" "sync" + "time" "google.golang.org/protobuf/proto" @@ -182,7 +183,7 @@ func (q *CentralQueue) Remove(ctx context.Context, executionIDs iter.Seq[string] deleted++ q.depthByWorkflow[cqe.WorkflowID]-- q.depthByTriggerType[cqe.TriggerCapID]-- - //TODO emit metric for time.Since(e.ObservedAt) + q.metrics.RecordEventAge(ctx, time.Since(cqe.ObservedAt).Seconds()) } return ok }) diff --git a/core/services/workflows/v2/triggers/queue_test.go b/core/services/workflows/v2/triggers/queue_test.go index 8f34e6dad00..591aeb764a9 100644 --- a/core/services/workflows/v2/triggers/queue_test.go +++ b/core/services/workflows/v2/triggers/queue_test.go @@ -3,6 +3,7 @@ package triggers import ( "context" "fmt" + "slices" "strings" "sync" "testing" @@ -585,3 +586,34 @@ func TestQueue_SortedDropsOversize(t *testing.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") +} diff --git a/deployment/cre/jobs/propose_job_spec_test.go b/deployment/cre/jobs/propose_job_spec_test.go index 684e20f69cc..898fc65f1fd 100644 --- a/deployment/cre/jobs/propose_job_spec_test.go +++ b/deployment/cre/jobs/propose_job_spec_test.go @@ -31,7 +31,6 @@ import ( "github.com/smartcontractkit/chainlink/deployment/cre/test" ) -// TODO add a subtest for ConsensusQueue func TestProposeJobSpec_VerifyPreconditions(t *testing.T) { j := jobs.ProposeJobSpec{} var env cldf.Environment @@ -531,7 +530,6 @@ func TestProposeJobSpec_VerifyPreconditions_Aptos(t *testing.T) { } } -// TODO add a subtest for ConsensusQueue func TestProposeJobSpec_Apply(t *testing.T) { h := test.NewTestHarness(t) env := new(h.Runtime.Environment()) From dca58bc6df49f5216f0e9706e641dfee5703f194 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Sun, 22 Nov 2026 17:02:02 -0600 Subject: [PATCH 27/38] make coordinator.TryStartExecute respect shadow mode --- core/scripts/go.mod | 2 +- core/scripts/go.sum | 4 +- core/services/cre/cre.go | 3 +- .../workflows/monitoring/monitoring.go | 16 ++++++++ .../workflows/v2/triggers/coordinator.go | 39 +++++++++++++++---- .../v2/triggers/coordinator_shadow_test.go | 25 ++++++++++++ deployment/go.mod | 2 +- deployment/go.sum | 4 +- go.mod | 2 +- go.sum | 4 +- integration-tests/go.mod | 2 +- integration-tests/go.sum | 4 +- integration-tests/load/go.mod | 2 +- integration-tests/load/go.sum | 4 +- system-tests/lib/go.mod | 2 +- system-tests/lib/go.sum | 4 +- system-tests/tests/go.mod | 2 +- system-tests/tests/go.sum | 4 +- 18 files changed, 95 insertions(+), 30 deletions(-) diff --git a/core/scripts/go.mod b/core/scripts/go.mod index 3fcc2bdb990..6794c6b6071 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.20261122152418-5c828021e8f7 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c 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.20261112211734-e640e1c12078 diff --git a/core/scripts/go.sum b/core/scripts/go.sum index 5a7af3f3c9e..56ee23e1e49 100644 --- a/core/scripts/go.sum +++ b/core/scripts/go.sum @@ -1686,8 +1686,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.20261122152418-5c828021e8f7 h1:YklE92DmcDaBVTWFe2woSPHE9fHQtYl+MZg6/60oYY4= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c h1:ncIJMkED4LMcxmvcFT1RNJWGvv1HMRXml9dhUt5FPn4= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/core/services/cre/cre.go b/core/services/cre/cre.go index 3a12cd16865..2057f298c88 100644 --- a/core/services/cre/cre.go +++ b/core/services/cre/cre.go @@ -926,7 +926,8 @@ func newWorkflowRegistrySyncerV2( // 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. eventLifetime := triggers.NewEventLifetime(triggers.ConsensusQueueExpirationGrace(lf)) centralQueue := triggers.NewQueue(engineLimiters.CentralTriggerEventQueue, wfmonitoring.NewCentralTriggerQueueMetricLabeler(commonmetrics.NewLabeler(), centralQueueMetrics), lggr) diff --git a/core/services/workflows/monitoring/monitoring.go b/core/services/workflows/monitoring/monitoring.go index 529a7191021..3630d93caa6 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 @@ -404,6 +405,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"), @@ -896,6 +905,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/v2/triggers/coordinator.go b/core/services/workflows/v2/triggers/coordinator.go index cd547760c1c..84efcb157c6 100644 --- a/core/services/workflows/v2/triggers/coordinator.go +++ b/core/services/workflows/v2/triggers/coordinator.go @@ -578,6 +578,17 @@ func (c *coordinator) StartExecution(ctx context.Context, event CoordinatedEvent 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. @@ -679,22 +690,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) diff --git a/core/services/workflows/v2/triggers/coordinator_shadow_test.go b/core/services/workflows/v2/triggers/coordinator_shadow_test.go index a13f453f311..aae934f035e 100644 --- a/core/services/workflows/v2/triggers/coordinator_shadow_test.go +++ b/core/services/workflows/v2/triggers/coordinator_shadow_test.go @@ -478,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/deployment/go.mod b/deployment/go.mod index f2d6bb69f9f..79e895003a4 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.20261122152418-5c828021e8f7 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c 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 e6963895ea0..bf2daf50c09 100644 --- a/deployment/go.sum +++ b/deployment/go.sum @@ -1411,8 +1411,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.20261122152418-5c828021e8f7 h1:YklE92DmcDaBVTWFe2woSPHE9fHQtYl+MZg6/60oYY4= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c h1:ncIJMkED4LMcxmvcFT1RNJWGvv1HMRXml9dhUt5FPn4= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/go.mod b/go.mod index 4c814d66dba..929b00abafa 100644 --- a/go.mod +++ b/go.mod @@ -82,7 +82,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.20261122152418-5c828021e8f7 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 github.com/smartcontractkit/chainlink-data-streams v1.1.3 diff --git a/go.sum b/go.sum index 9e99f147ded..520cd188aa3 100644 --- a/go.sum +++ b/go.sum @@ -1102,8 +1102,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.20261122152418-5c828021e8f7 h1:YklE92DmcDaBVTWFe2woSPHE9fHQtYl+MZg6/60oYY4= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c h1:ncIJMkED4LMcxmvcFT1RNJWGvv1HMRXml9dhUt5FPn4= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/integration-tests/go.mod b/integration-tests/go.mod index cd4ec88fca8..d4dd356d04d 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.20261122152418-5c828021e8f7 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c 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.20261112211734-e640e1c12078 diff --git a/integration-tests/go.sum b/integration-tests/go.sum index 0291c887708..04bb3a4a978 100644 --- a/integration-tests/go.sum +++ b/integration-tests/go.sum @@ -1396,8 +1396,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.20261122152418-5c828021e8f7 h1:YklE92DmcDaBVTWFe2woSPHE9fHQtYl+MZg6/60oYY4= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c h1:ncIJMkED4LMcxmvcFT1RNJWGvv1HMRXml9dhUt5FPn4= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/integration-tests/load/go.mod b/integration-tests/load/go.mod index 5a7a9ab1c7a..b1011f6a5ef 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.20261122152418-5c828021e8f7 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261112211734-e640e1c12078 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 ddebc853988..b764043f3de 100644 --- a/integration-tests/load/go.sum +++ b/integration-tests/load/go.sum @@ -1636,8 +1636,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.20261122152418-5c828021e8f7 h1:YklE92DmcDaBVTWFe2woSPHE9fHQtYl+MZg6/60oYY4= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c h1:ncIJMkED4LMcxmvcFT1RNJWGvv1HMRXml9dhUt5FPn4= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/system-tests/lib/go.mod b/system-tests/lib/go.mod index 6c44cc3200d..16b15240bc7 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.20261122152418-5c828021e8f7 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c 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 2687e3dec0f..6a9556e4eae 100644 --- a/system-tests/lib/go.sum +++ b/system-tests/lib/go.sum @@ -1657,8 +1657,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.20261122152418-5c828021e8f7 h1:YklE92DmcDaBVTWFe2woSPHE9fHQtYl+MZg6/60oYY4= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c h1:ncIJMkED4LMcxmvcFT1RNJWGvv1HMRXml9dhUt5FPn4= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/system-tests/tests/go.mod b/system-tests/tests/go.mod index e71f44fdf02..f8d2d14612c 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.20261122152418-5c828021e8f7 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 github.com/smartcontractkit/chainlink-confidential-compute v1.3.0 diff --git a/system-tests/tests/go.sum b/system-tests/tests/go.sum index 002af4b9143..9cd4510ea19 100644 --- a/system-tests/tests/go.sum +++ b/system-tests/tests/go.sum @@ -1836,8 +1836,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.20261122152418-5c828021e8f7 h1:YklE92DmcDaBVTWFe2woSPHE9fHQtYl+MZg6/60oYY4= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122152418-5c828021e8f7/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c h1:ncIJMkED4LMcxmvcFT1RNJWGvv1HMRXml9dhUt5FPn4= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= From 8874411f877885471175d5b6b3d83a7799cd3c3e Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Sun, 22 Nov 2026 17:36:32 -0600 Subject: [PATCH 28/38] use FeatureConsensusQueueKVDrainActivePeriod --- core/scripts/go.mod | 2 +- core/scripts/go.sum | 4 +- core/services/ocr3_1/plugins/queue/kvstate.go | 9 + core/services/ocr3_1/plugins/queue/metrics.go | 7 + core/services/ocr3_1/plugins/queue/queue.go | 106 +++++++++- .../ocr3_1/plugins/queue/queue_test.go | 189 ++++++++++++++++++ deployment/go.mod | 2 +- deployment/go.sum | 4 +- go.mod | 2 +- go.sum | 4 +- integration-tests/go.mod | 2 +- integration-tests/go.sum | 4 +- integration-tests/load/go.mod | 2 +- integration-tests/load/go.sum | 4 +- system-tests/lib/go.mod | 2 +- system-tests/lib/go.sum | 4 +- system-tests/tests/go.mod | 2 +- system-tests/tests/go.sum | 4 +- 18 files changed, 322 insertions(+), 31 deletions(-) diff --git a/core/scripts/go.mod b/core/scripts/go.mod index 6794c6b6071..4801c9c9ecd 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.20261122225510-4dee493c752c + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4 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.20261112211734-e640e1c12078 diff --git a/core/scripts/go.sum b/core/scripts/go.sum index 56ee23e1e49..db85f9630bb 100644 --- a/core/scripts/go.sum +++ b/core/scripts/go.sum @@ -1686,8 +1686,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.20261122225510-4dee493c752c h1:ncIJMkED4LMcxmvcFT1RNJWGvv1HMRXml9dhUt5FPn4= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4 h1:t9f20+j6/st4YXB652UqKRpAPUPNzM5dw74dks6YJ/U= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index c8e9346aeb2..053095cc992 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -442,6 +442,15 @@ func (s *kvState) trimConsensusEvents(maxTotalBytes int) { 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) { diff --git a/core/services/ocr3_1/plugins/queue/metrics.go b/core/services/ocr3_1/plugins/queue/metrics.go index ef5ac42b947..1debd406d20 100644 --- a/core/services/ocr3_1/plugins/queue/metrics.go +++ b/core/services/ocr3_1/plugins/queue/metrics.go @@ -45,6 +45,7 @@ type pluginMetrics struct { 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 @@ -72,6 +73,7 @@ func newPluginMetrics(meter metric.Meter, configDigest string) (*pluginMetrics, 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") @@ -97,6 +99,11 @@ func (m *pluginMetrics) recordObservation(ctx context.Context, events int) { 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 diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index 22bc9984968..481a3fefa14 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -32,8 +32,10 @@ import ( "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/workflows/types" @@ -48,9 +50,23 @@ type consensusQueuePluginFactory struct { 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 } +// 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, cfg *PluginConfig, @@ -77,6 +93,7 @@ func NewConsensusQueuePluginFactory( triggerCoordinator: triggerCoordinator, triggerQueue: triggerQueue, expirationDur: triggers.ConsensusQueueExpirationGrace(limitsFactory), + kvDrain: KVDrainActive(limitsFactory), meter: meter, }, nil } @@ -87,6 +104,7 @@ func (c *consensusQueuePluginFactory) NewReportingPlugin(ctx context.Context, co return nil, nil, err } plugin := newConsensusQueuePlugin(c.lggr, config, c.cfg.Limits, c.triggerCoordinator, c.triggerQueue, c.expirationDur, blobs, metrics) + plugin.kvDrain = c.kvDrain pluginInfo := ocr3_1types.ReportingPluginInfo1{ Name: "ConsensusQueueReportingPlugin", Limits: c.cfg.Limits, @@ -107,7 +125,31 @@ type consensusQueuePlugin struct { triggerQueue triggers.Queue blobBroadcastFetcher ocr3_1types.BlobBroadcastFetcher expirationDur func(context.Context) (time.Duration, error) - metrics *pluginMetrics + // 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 +} + +// 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( @@ -161,13 +203,25 @@ func (c *consensusQueuePlugin) Observation( 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(time.Now().Add(-expirationGraceDur)), + 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) @@ -193,6 +247,21 @@ func (c *consensusQueuePlugin) Observation( 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. @@ -403,6 +472,10 @@ func (c *consensusQueuePlugin) ValidateObservation( } } + 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)) } @@ -586,11 +659,16 @@ func (c *consensusQueuePlugin) StateTransition( state.pruneExpiredObservations(obs.medianExpiration) var queuedTimelessHashes []string // eligible for pruning later if necessary var admitted int - state.addObservedEvents(c.onchainCfg.F, obs.newObservedEvents, obs.observedBlobs, func(event *pb.ConsensusQueueEvent) { - queuedTimelessHashes = append(queuedTimelessHashes, string(event.TimelessHash)) - admitted++ - }) - state.popConsensusEvents(int(obs.medianCap), obs.medianCapPerWF, obs.medianExpiration, c.limits.MaxKeyValueModifiedKeysPlusValuesBytes) + if obs.kvDrain { + // 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.popConsensusEvents(int(obs.medianCap), obs.medianCapPerWF, 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 @@ -627,9 +705,12 @@ func (c *consensusQueuePlugin) recordTransition(ctx context.Context, state *kvSt } type observations struct { - medianExpiration time.Time - medianCap uint32 - medianCapPerWF map[string]uint32 // wf ID -> capacity + medianExpiration time.Time + medianCap uint32 + medianCapPerWF 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 @@ -649,6 +730,7 @@ func (res *observations) aggregate(ctx context.Context, f int, aos []ocrtypes.At 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 { @@ -663,6 +745,9 @@ func (res *observations) aggregate(ctx context.Context, f int, aos []ocrtypes.At 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) @@ -676,6 +761,7 @@ func (res *observations) aggregate(ctx context.Context, f int, aos []ocrtypes.At } } 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. diff --git a/core/services/ocr3_1/plugins/queue/queue_test.go b/core/services/ocr3_1/plugins/queue/queue_test.go index cf8068df793..db3a2d8d208 100644 --- a/core/services/ocr3_1/plugins/queue/queue_test.go +++ b/core/services/ocr3_1/plugins/queue/queue_test.go @@ -33,6 +33,7 @@ import ( "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/workflows/v2/triggers" @@ -692,6 +693,7 @@ 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} @@ -704,6 +706,7 @@ func nodeObs(t testing.TB, o nodeOpts, events ...hashedEvent) *pb.ConsensusQueue Expiration: ts(o.expiration), Capacity: o.capacity, WorkflowCapacities: maps.Clone(o.wfCaps), + KvDrainActive: o.drain, } if obs.WorkflowCapacities == nil { obs.WorkflowCapacities = map[string]uint32{} @@ -2475,3 +2478,189 @@ func TestCommitted_FetchesAnEventsBlobsConcurrently(t *testing.T) { 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, int64(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) + + var aos []ocrtypes.AttributedObservation + 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)...) + assert.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/deployment/go.mod b/deployment/go.mod index 79e895003a4..ebc1534320b 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.20261122225510-4dee493c752c + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4 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 bf2daf50c09..ceff07d7896 100644 --- a/deployment/go.sum +++ b/deployment/go.sum @@ -1411,8 +1411,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.20261122225510-4dee493c752c h1:ncIJMkED4LMcxmvcFT1RNJWGvv1HMRXml9dhUt5FPn4= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4 h1:t9f20+j6/st4YXB652UqKRpAPUPNzM5dw74dks6YJ/U= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/go.mod b/go.mod index 929b00abafa..d86ffcf64c1 100644 --- a/go.mod +++ b/go.mod @@ -82,7 +82,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.20261122225510-4dee493c752c + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 github.com/smartcontractkit/chainlink-data-streams v1.1.3 diff --git a/go.sum b/go.sum index 520cd188aa3..0ef46e28a49 100644 --- a/go.sum +++ b/go.sum @@ -1102,8 +1102,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.20261122225510-4dee493c752c h1:ncIJMkED4LMcxmvcFT1RNJWGvv1HMRXml9dhUt5FPn4= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4 h1:t9f20+j6/st4YXB652UqKRpAPUPNzM5dw74dks6YJ/U= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/integration-tests/go.mod b/integration-tests/go.mod index d4dd356d04d..b406ce525e9 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.20261122225510-4dee493c752c + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4 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.20261112211734-e640e1c12078 diff --git a/integration-tests/go.sum b/integration-tests/go.sum index 04bb3a4a978..a2ca878eb42 100644 --- a/integration-tests/go.sum +++ b/integration-tests/go.sum @@ -1396,8 +1396,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.20261122225510-4dee493c752c h1:ncIJMkED4LMcxmvcFT1RNJWGvv1HMRXml9dhUt5FPn4= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4 h1:t9f20+j6/st4YXB652UqKRpAPUPNzM5dw74dks6YJ/U= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/integration-tests/load/go.mod b/integration-tests/load/go.mod index b1011f6a5ef..ade15887e6b 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.20261122225510-4dee493c752c + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4 github.com/smartcontractkit/chainlink-deployments-framework v0.126.0 github.com/smartcontractkit/chainlink-evm v0.3.4-0.20261112211734-e640e1c12078 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 b764043f3de..594cbd141e0 100644 --- a/integration-tests/load/go.sum +++ b/integration-tests/load/go.sum @@ -1636,8 +1636,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.20261122225510-4dee493c752c h1:ncIJMkED4LMcxmvcFT1RNJWGvv1HMRXml9dhUt5FPn4= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4 h1:t9f20+j6/st4YXB652UqKRpAPUPNzM5dw74dks6YJ/U= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/system-tests/lib/go.mod b/system-tests/lib/go.mod index 16b15240bc7..8f47ca47e6e 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.20261122225510-4dee493c752c + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4 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 6a9556e4eae..b3c6a19d2c7 100644 --- a/system-tests/lib/go.sum +++ b/system-tests/lib/go.sum @@ -1657,8 +1657,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.20261122225510-4dee493c752c h1:ncIJMkED4LMcxmvcFT1RNJWGvv1HMRXml9dhUt5FPn4= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4 h1:t9f20+j6/st4YXB652UqKRpAPUPNzM5dw74dks6YJ/U= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= diff --git a/system-tests/tests/go.mod b/system-tests/tests/go.mod index f8d2d14612c..1cc5f2a78dd 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.20261122225510-4dee493c752c + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4 github.com/smartcontractkit/chainlink-common/keystore v1.3.1-0.20261111193935-c83f8e2996fb github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261106154152-9426766b30a9 github.com/smartcontractkit/chainlink-confidential-compute v1.3.0 diff --git a/system-tests/tests/go.sum b/system-tests/tests/go.sum index 9cd4510ea19..85ef67e4199 100644 --- a/system-tests/tests/go.sum +++ b/system-tests/tests/go.sum @@ -1836,8 +1836,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.20261122225510-4dee493c752c h1:ncIJMkED4LMcxmvcFT1RNJWGvv1HMRXml9dhUt5FPn4= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122225510-4dee493c752c/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4 h1:t9f20+j6/st4YXB652UqKRpAPUPNzM5dw74dks6YJ/U= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= 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.20261106154152-9426766b30a9 h1:rs2zmGoDw4AHaJ2Y76J46slPPE3iL801sWPgOTCyDZc= From 2e10130ad4fc99c5fb6d8b2e3c7c95b0b68c847a Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Sun, 22 Nov 2026 17:55:06 -0600 Subject: [PATCH 29/38] docs & diagrams --- core/services/ocr3_1/plugins/queue/README.md | 174 ++++++++++++++++++ core/services/ocr3_1/plugins/queue/kvstate.go | 3 +- core/services/ocr3_1/plugins/queue/queue.go | 32 +++- .../ocr3_1/plugins/queue/queue_test.go | 3 +- 4 files changed, 203 insertions(+), 9 deletions(-) create mode 100644 core/services/ocr3_1/plugins/queue/README.md 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..f4621ea594d --- /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 fewer than F+1 votes for an event + StateTransition->>observed: Write(): the vote and its blob + else F+1 votes + StateTransition->>queued: Write(): by deadline, then hash + 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: 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 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/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index 053095cc992..aafebde79fe 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -350,7 +350,8 @@ func (s *kvState) prepareWriteObservedEvents() { // 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] - //TODO can we use deadline here? is median valid & best option? (only have f+1) + // 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] diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index 481a3fefa14..d39cb777cd3 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -1,9 +1,29 @@ -// Package queue contains the consensus queue OCR 3.1 reporting plugin, for coordinating execution of triggered events. -// Each node has a local [triggers.Queue] of [triggers.CoordinatedEvent], which are observed (and broadcast) by the plugin. -// When consensus is reached, events are put in to the KeyValueState priority queue (and removed from the [triggers.Queue]). -// The priority queue is ordered by deadline (with nanosecond precision) and then by trigger event ID. -// Each round, as many events as possible are popped from the priority queue and then (fetched and) executed via [triggers.Coordinator.Deliver]. -// Capacity, both overall and per-workflow, limits what may execute. Capacities are observed and medianized. +// 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 ( diff --git a/core/services/ocr3_1/plugins/queue/queue_test.go b/core/services/ocr3_1/plugins/queue/queue_test.go index db3a2d8d208..2e15cd3f350 100644 --- a/core/services/ocr3_1/plugins/queue/queue_test.go +++ b/core/services/ocr3_1/plugins/queue/queue_test.go @@ -638,8 +638,7 @@ func TestValidateObservation(t *testing.T) { require.NoError(t, validate(t, c, blobs, obs)) }) - // Completeness (C4): fields that feed StateTransition but are not bound to the honest value. - // These document the open TODOs in ValidateObservation; they fail until each field is bounded. + // 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) From e0e5799c0870509dfcab317e8fdf03e53c3154f2 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Sun, 22 Nov 2026 19:51:34 -0600 Subject: [PATCH 30/38] consensus queue: do not keep a cancelled blob fetch as the result for others The blob cache shares one fetch of a blob between every caller, but makes it with the first caller's context. If that context ended, its cancellation became the result for every caller after it. A cancellation is now evicted, and a caller whose own context is still live fetches again, once, with it. Other errors are kept as before. Co-Authored-By: Claude Sonnet 5.5 --- core/services/ocr3_1/plugins/queue/blobs.go | 41 +++++++ .../ocr3_1/plugins/queue/blobs_test.go | 111 ++++++++++++++++++ core/services/ocr3_1/plugins/queue/queue.go | 5 +- 3 files changed, 155 insertions(+), 2 deletions(-) diff --git a/core/services/ocr3_1/plugins/queue/blobs.go b/core/services/ocr3_1/plugins/queue/blobs.go index 039edeac83b..0a1fa19c355 100644 --- a/core/services/ocr3_1/plugins/queue/blobs.go +++ b/core/services/ocr3_1/plugins/queue/blobs.go @@ -2,6 +2,7 @@ package queue import ( "context" + "errors" "fmt" "sort" "sync" @@ -24,7 +25,39 @@ type blobCache struct { 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() @@ -57,6 +90,14 @@ func (c *blobCache) fetchBlob(ctx context.Context, handle []byte) ([]byte, error // 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 { diff --git a/core/services/ocr3_1/plugins/queue/blobs_test.go b/core/services/ocr3_1/plugins/queue/blobs_test.go index ed71c6dbaa8..bdfe57f119c 100644 --- a/core/services/ocr3_1/plugins/queue/blobs_test.go +++ b/core/services/ocr3_1/plugins/queue/blobs_test.go @@ -198,6 +198,117 @@ func TestBlobCache_FetchBlob(t *testing.T) { }) } +// 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() diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index d39cb777cd3..b5813520af3 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -905,8 +905,9 @@ func (c *consensusQueuePlugin) tryStartExecution(ctx context.Context, fetcher *b // 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, and cancelling would cache the cancellation as the result for all of them. So ctx -// must outlive this event: it is the commit's, which they end with. +// 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 From c098d9cf749c29513286e6c18294ec18a336e8b8 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Sun, 22 Nov 2026 19:51:45 -0600 Subject: [PATCH 31/38] central queue: drainer yields to the consensus queue plugin The drainer and the plugin both took events from the central queue, so each event went to whichever got it first. The queue now records when it was last read for consensus (Sorted), and the drainer leaves live events alone while that is recent, only dropping those past their deadline plus the grace period. When the plugin goes quiet it drains everything again. The shadow trigger mode smoke test now counts the coordinator's shadow skips, not the drainer's, and waits longer for the first one, as OCR rounds can start minutes after the environment does. Co-Authored-By: Claude Sonnet 5.5 --- core/services/cre/cre.go | 5 +- .../central_trigger_queue_metrics.go | 3 + .../services/workflows/v2/triggers/drainer.go | 58 ++++++++++++++- .../workflows/v2/triggers/drainer_test.go | 72 ++++++++++++++++++- core/services/workflows/v2/triggers/queue.go | 39 ++++++++++ .../workflows/v2/triggers/queue_test.go | 38 ++++++++++ .../smoke/cre/shadow_trigger_mode_test.go | 36 ++++++---- 7 files changed, 232 insertions(+), 19 deletions(-) diff --git a/core/services/cre/cre.go b/core/services/cre/cre.go index 2057f298c88..4af2e59dfe6 100644 --- a/core/services/cre/cre.go +++ b/core/services/cre/cre.go @@ -927,11 +927,12 @@ func newWorkflowRegistrySyncerV2( // 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 coordinator - // also logs instead of starting an event in that window when consensus on the queue chooses it. + // 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{ diff --git a/core/services/workflows/monitoring/central_trigger_queue_metrics.go b/core/services/workflows/monitoring/central_trigger_queue_metrics.go index c03775a66a1..845ee59c6db 100644 --- a/core/services/workflows/monitoring/central_trigger_queue_metrics.go +++ b/core/services/workflows/monitoring/central_trigger_queue_metrics.go @@ -16,6 +16,9 @@ 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 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 7d7f6256d92..9784dfc3ec3 100644 --- a/core/services/workflows/v2/triggers/drainer_test.go +++ b/core/services/workflows/v2/triggers/drainer_test.go @@ -81,6 +81,11 @@ func (q *fakeQueue) Sorted(_ context.Context, limit, _ int) iter.Seq2[[]byte, *p } } +// 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 { @@ -459,7 +464,8 @@ func TestNewCentralQueueDrainer_LogsDrainedEvents(t *testing.T) { 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()) }) @@ -483,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 390d2e03116..262aeb9fdb0 100644 --- a/core/services/workflows/v2/triggers/queue.go +++ b/core/services/workflows/v2/triggers/queue.go @@ -12,6 +12,7 @@ import ( "maps" "slices" "sync" + "sync/atomic" "time" "google.golang.org/protobuf/proto" @@ -80,6 +81,8 @@ type CentralQueue struct { 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 { @@ -194,6 +197,7 @@ func (q *CentralQueue) Remove(ctx context.Context, executionIDs iter.Seq[string] } 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() @@ -251,6 +255,41 @@ func (q *CentralQueue) dropOversize(ctx context.Context, oversize []centralQueue } } +// 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) diff --git a/core/services/workflows/v2/triggers/queue_test.go b/core/services/workflows/v2/triggers/queue_test.go index 591aeb764a9..ff2e926f30c 100644 --- a/core/services/workflows/v2/triggers/queue_test.go +++ b/core/services/workflows/v2/triggers/queue_test.go @@ -617,3 +617,41 @@ func TestQueue_RecordsHowLongRemovedEventsWereQueued(t *testing.T) { 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/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]. From ad4e205f9a575940f40f15bd45429720260c7e5b Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Sun, 22 Nov 2026 19:51:57 -0600 Subject: [PATCH 32/38] consensus queue: fix nil plugin config panic and give the job template limits validateConsensusQueuePluginSpec unmarshaled into &cfg, a pointer to the pointer, so a null plugin config set cfg to nil and Validate dereferenced it, which crashed the node when the job was proposed. It now unmarshals into cfg, and Validate returns an error for a nil receiver. The consensus-queue job template had no limits at all, so every job from it failed validation once that was fixed. It now sets the calibrated limits. Co-Authored-By: Claude Sonnet 5.5 --- core/services/ocr2/validate/validate.go | 2 +- core/services/ocr2/validate/validate_test.go | 40 +++++++++++++++++++ core/services/ocr3_1/plugins/queue/config.go | 3 ++ .../ocr3_1/plugins/queue/config_test.go | 6 +++ .../jobs/pkg/templates/consensus-queue.tmpl | 8 ++++ 5 files changed, 58 insertions(+), 1 deletion(-) diff --git a/core/services/ocr2/validate/validate.go b/core/services/ocr2/validate/validate.go index 687e3eb2a11..2f3551867ce 100644 --- a/core/services/ocr2/validate/validate.go +++ b/core/services/ocr2/validate/validate.go @@ -329,7 +329,7 @@ func validateOCR2LLOSpec(jsonConfig job.JSONConfig) error { func validateConsensusQueuePluginSpec(jsonConfig job.JSONConfig) error { cfg := &queue.PluginConfig{} - if err := json.Unmarshal(jsonConfig.Bytes(), &cfg); err != nil { + if err := json.Unmarshal(jsonConfig.Bytes(), cfg); err != nil { return fmt.Errorf("failed to unmarshal consensus queue plugin config: %w", err) } return cfg.Validate() diff --git a/core/services/ocr2/validate/validate_test.go b/core/services/ocr2/validate/validate_test.go index d145b503472..717dbf049ea 100644 --- a/core/services/ocr2/validate/validate_test.go +++ b/core/services/ocr2/validate/validate_test.go @@ -26,6 +26,46 @@ func TestValidateOracleSpec(t *testing.T) { overrides func(c *chainlink.Config, s *chainlink.Secrets) assertion func(t *testing.T, os job.Job, err error) }{ + { + name: "consensus queue spec without plugin config is rejected, not a panic", + toml: ` +type = "offchainreporting2" +schemaVersion = 1 +pluginType = "consensus-queue" +relay = "evm" +contractID = "0x613a38AC1659769640aaE063C651F48E0250454C" +transmitterID = "0x613a38AC1659769640aaE063C651F48E0250454C" +[relayConfig] +chainID = 1337 +`, + assertion: func(t *testing.T, _ job.Job, err error) { + require.Error(t, err) + assert.Contains(t, err.Error(), "MaxObservationBytes (0) must be positive") + }, + }, + { + name: "consensus queue spec with limits", + toml: ` +type = "offchainreporting2" +schemaVersion = 1 +pluginType = "consensus-queue" +relay = "evm" +contractID = "0x613a38AC1659769640aaE063C651F48E0250454C" +transmitterID = "0x613a38AC1659769640aaE063C651F48E0250454C" +[relayConfig] +chainID = 1337 +[pluginConfig.limits] +MaxObservationBytes = 524288 +MaxKeyValueModifiedKeys = 4 +MaxKeyValueModifiedKeysPlusValuesBytes = 10485760 +MaxBlobPayloadBytes = 5242880 +MaxPerOracleUnexpiredBlobCumulativePayloadBytes = 104857600 +MaxPerOracleUnexpiredBlobCount = 100 +`, + assertion: func(t *testing.T, _ job.Job, err error) { + require.NoError(t, err) + }, + }, { name: "minimal OCR2 oracle spec", toml: ` diff --git a/core/services/ocr3_1/plugins/queue/config.go b/core/services/ocr3_1/plugins/queue/config.go index d3104a17d37..ba457698447 100644 --- a/core/services/ocr3_1/plugins/queue/config.go +++ b/core/services/ocr3_1/plugins/queue/config.go @@ -22,6 +22,9 @@ type PluginConfig struct { // Validate checks the limits are within libocr's bounds, and that this plugin can operate within them. func (c *PluginConfig) Validate() error { + if c == nil { + return errors.New("plugin config is missing") + } if err := c.Limits.Validate(); err != nil { return fmt.Errorf("invalid limits: %w", err) } diff --git a/core/services/ocr3_1/plugins/queue/config_test.go b/core/services/ocr3_1/plugins/queue/config_test.go index 0dd3b68d597..6a1a6be6da2 100644 --- a/core/services/ocr3_1/plugins/queue/config_test.go +++ b/core/services/ocr3_1/plugins/queue/config_test.go @@ -37,6 +37,12 @@ func validLimits() ocr3_1types.ReportingPluginLimits { func TestPluginConfig_Validate(t *testing.T) { t.Parallel() + t.Run("a missing config is an error, not a panic", func(t *testing.T) { + t.Parallel() + var c *PluginConfig + assert.ErrorContains(t, c.Validate(), "missing") + }) + tests := []struct { name string mutate func(l *ocr3_1types.ReportingPluginLimits) diff --git a/deployment/cre/jobs/pkg/templates/consensus-queue.tmpl b/deployment/cre/jobs/pkg/templates/consensus-queue.tmpl index 9f7d38356d8..ac40644a979 100644 --- a/deployment/cre/jobs/pkg/templates/consensus-queue.tmpl +++ b/deployment/cre/jobs/pkg/templates/consensus-queue.tmpl @@ -12,3 +12,11 @@ transmitterID = "{{ .TransmitterID }}" relay = "evm" [relayConfig] chainID = "{{ .ChainID }}" + +[pluginConfig.limits] +MaxObservationBytes = 524288 +MaxKeyValueModifiedKeys = 4 +MaxKeyValueModifiedKeysPlusValuesBytes = 10485760 +MaxBlobPayloadBytes = 5242880 +MaxPerOracleUnexpiredBlobCumulativePayloadBytes = 104857600 +MaxPerOracleUnexpiredBlobCount = 100 From 9d6a4b38d2e0dc3f33fd41dcf6618deb34f63891 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Sun, 22 Nov 2026 20:29:35 -0600 Subject: [PATCH 33/38] bump common --- core/scripts/go.mod | 2 +- core/scripts/go.sum | 4 ++-- deployment/go.mod | 2 +- deployment/go.sum | 4 ++-- go.mod | 2 +- go.sum | 4 ++-- integration-tests/go.mod | 2 +- integration-tests/go.sum | 4 ++-- integration-tests/load/go.mod | 2 +- integration-tests/load/go.sum | 4 ++-- system-tests/lib/go.mod | 2 +- system-tests/lib/go.sum | 4 ++-- system-tests/tests/go.mod | 2 +- system-tests/tests/go.sum | 4 ++-- 14 files changed, 21 insertions(+), 21 deletions(-) diff --git a/core/scripts/go.mod b/core/scripts/go.mod index 06a7248fc32..1c51712f617 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.20261122233039-00a0064c02a4 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f 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 2d5effb52b0..07aca5bad85 100644 --- a/core/scripts/go.sum +++ b/core/scripts/go.sum @@ -1686,8 +1686,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.20261122233039-00a0064c02a4 h1:t9f20+j6/st4YXB652UqKRpAPUPNzM5dw74dks6YJ/U= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f h1:E1+AQ1s3F1goVK1zZxAnPHfD5TV8JVslm0PIyJJtpMs= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f/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/deployment/go.mod b/deployment/go.mod index ecee6e47cec..82e4bf9080a 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.20261122233039-00a0064c02a4 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f 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 b6b0b5d4400..381a33bba1d 100644 --- a/deployment/go.sum +++ b/deployment/go.sum @@ -1411,8 +1411,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.20261122233039-00a0064c02a4 h1:t9f20+j6/st4YXB652UqKRpAPUPNzM5dw74dks6YJ/U= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f h1:E1+AQ1s3F1goVK1zZxAnPHfD5TV8JVslm0PIyJJtpMs= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f/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 40c73bc824b..89efe03457f 100644 --- a/go.mod +++ b/go.mod @@ -82,7 +82,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.20261122233039-00a0064c02a4 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f 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 f42f77dd51e..880b55412cd 100644 --- a/go.sum +++ b/go.sum @@ -1102,8 +1102,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.20261122233039-00a0064c02a4 h1:t9f20+j6/st4YXB652UqKRpAPUPNzM5dw74dks6YJ/U= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f h1:E1+AQ1s3F1goVK1zZxAnPHfD5TV8JVslm0PIyJJtpMs= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f/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 457a097586f..f2237136674 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.20261122233039-00a0064c02a4 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f 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 1c495f9a62a..ce9f16d99d2 100644 --- a/integration-tests/go.sum +++ b/integration-tests/go.sum @@ -1396,8 +1396,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.20261122233039-00a0064c02a4 h1:t9f20+j6/st4YXB652UqKRpAPUPNzM5dw74dks6YJ/U= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f h1:E1+AQ1s3F1goVK1zZxAnPHfD5TV8JVslm0PIyJJtpMs= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f/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 ba7f6373ecb..05cbf651114 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.20261122233039-00a0064c02a4 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f 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 c68faf5f717..233c74e01ff 100644 --- a/integration-tests/load/go.sum +++ b/integration-tests/load/go.sum @@ -1636,8 +1636,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.20261122233039-00a0064c02a4 h1:t9f20+j6/st4YXB652UqKRpAPUPNzM5dw74dks6YJ/U= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f h1:E1+AQ1s3F1goVK1zZxAnPHfD5TV8JVslm0PIyJJtpMs= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f/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 8fea1b88d21..c6e6d724e9c 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.20261122233039-00a0064c02a4 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f 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 6404d65a8e5..e8a7f819b83 100644 --- a/system-tests/lib/go.sum +++ b/system-tests/lib/go.sum @@ -1657,8 +1657,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.20261122233039-00a0064c02a4 h1:t9f20+j6/st4YXB652UqKRpAPUPNzM5dw74dks6YJ/U= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f h1:E1+AQ1s3F1goVK1zZxAnPHfD5TV8JVslm0PIyJJtpMs= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f/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 2c720cb1e90..6f33bde37b2 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.20261122233039-00a0064c02a4 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f 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 c80cccd9759..f8108a7b34d 100644 --- a/system-tests/tests/go.sum +++ b/system-tests/tests/go.sum @@ -1836,8 +1836,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.20261122233039-00a0064c02a4 h1:t9f20+j6/st4YXB652UqKRpAPUPNzM5dw74dks6YJ/U= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261122233039-00a0064c02a4/go.mod h1:81DIRjlxA+Nq4sugpyD0zofdXg46owE/N3eter3+EkI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f h1:E1+AQ1s3F1goVK1zZxAnPHfD5TV8JVslm0PIyJJtpMs= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f/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= From 3030c1796752e066f63e9f0eac64fc3d7d1842a6 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Sun, 22 Nov 2026 21:20:22 -0600 Subject: [PATCH 34/38] lint --- .../ocr3_1/beholderwrapper/plugin_test.go | 3 +- core/services/ocr3_1/beholderwrapper/types.go | 2 +- core/services/ocr3_1/plugins/queue/blobs.go | 10 +-- .../ocr3_1/plugins/queue/blobs_test.go | 17 ++--- core/services/ocr3_1/plugins/queue/config.go | 2 +- .../ocr3_1/plugins/queue/config_test.go | 16 ++--- core/services/ocr3_1/plugins/queue/kvstate.go | 15 ++--- .../ocr3_1/plugins/queue/kvstate_test.go | 16 +++-- .../ocr3_1/plugins/queue/metrics_test.go | 2 +- core/services/ocr3_1/plugins/queue/queue.go | 26 ++++--- .../ocr3_1/plugins/queue/queue_test.go | 67 ++++++++++--------- core/services/workflows/store/store_memory.go | 8 +-- .../workflows/store/store_memory_test.go | 12 ++-- .../workflows/v2/triggers/coordinator_test.go | 6 +- core/services/workflows/v2/triggers/queue.go | 1 - .../workflows/v2/triggers/queue_test.go | 2 +- 16 files changed, 101 insertions(+), 104 deletions(-) diff --git a/core/services/ocr3_1/beholderwrapper/plugin_test.go b/core/services/ocr3_1/beholderwrapper/plugin_test.go index e828a68f803..99f804205c4 100644 --- a/core/services/ocr3_1/beholderwrapper/plugin_test.go +++ b/core/services/ocr3_1/beholderwrapper/plugin_test.go @@ -601,6 +601,7 @@ func (f *fakePlugin[RI]) Close() error { // 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()) }) @@ -637,7 +638,7 @@ func Test_ReportingPlugin_RecordsCommittedSeqNr(t *testing.T) { 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") + 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 diff --git a/core/services/ocr3_1/beholderwrapper/types.go b/core/services/ocr3_1/beholderwrapper/types.go index 8c0b9b86507..fd9b47cb95e 100644 --- a/core/services/ocr3_1/beholderwrapper/types.go +++ b/core/services/ocr3_1/beholderwrapper/types.go @@ -70,7 +70,7 @@ func newPluginMetrics(meter metric.Meter, plugin, configDigest string) (*pluginM } func (m *pluginMetrics) recordCommittedSeqNr(ctx context.Context, seqNr uint64) { - m.committedSeqNr.Record(ctx, int64(seqNr), metric.WithAttributes( + 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), )) diff --git a/core/services/ocr3_1/plugins/queue/blobs.go b/core/services/ocr3_1/plugins/queue/blobs.go index 0a1fa19c355..1e3da60304a 100644 --- a/core/services/ocr3_1/plugins/queue/blobs.go +++ b/core/services/ocr3_1/plugins/queue/blobs.go @@ -152,8 +152,8 @@ func (c *consensusQueuePlugin) maxEventBytes() int { const maxEventsPerBlob = maxObservedEvents // splitEvents splits a blob into its marshaled events, without unmarshaling any of them. It rejects a blob with more -// than max events. -func splitEvents(b []byte, max int) ([][]byte, error) { +// than limit events. +func splitEvents(b []byte, limit int) ([][]byte, error) { var events [][]byte for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) @@ -181,8 +181,8 @@ func splitEvents(b []byte, max int) ([][]byte, error) { return nil, protowire.ParseError(m) } - if len(events) == max { - return nil, fmt.Errorf("blob has more than %d events", max) + if len(events) == limit { + return nil, fmt.Errorf("blob has more than %d events", limit) } events = append(events, v) @@ -212,7 +212,7 @@ 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)) + rounds = max(rounds, uint64((lifetime+roundDur-1)/roundDur)) //nolint:gosec // G115: lifetime and roundDur are positive } return seqNr + rounds diff --git a/core/services/ocr3_1/plugins/queue/blobs_test.go b/core/services/ocr3_1/plugins/queue/blobs_test.go index bdfe57f119c..9a04450f914 100644 --- a/core/services/ocr3_1/plugins/queue/blobs_test.go +++ b/core/services/ocr3_1/plugins/queue/blobs_test.go @@ -22,6 +22,7 @@ import ( ) func Test_extractEvent(t *testing.T) { + t.Parallel() payload, err := anypb.New(timestamppb.New(time.Now())) require.NoError(t, err) event := &pb.CoordinatedEvent{ @@ -68,6 +69,7 @@ func Test_extractEvent(t *testing.T) { {"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 { @@ -89,6 +91,7 @@ func Test_extractEvent(t *testing.T) { } 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()) @@ -150,13 +153,11 @@ func TestBlobCache_FetchBlob(t *testing.T) { var wg sync.WaitGroup results := make([][]byte, 20) for i := range results { - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { b, err := c.fetchBlob(t.Context(), handleBytes(1)) assert.NoError(t, err) results[i] = b - }() + }) } close(f.gate) wg.Wait() @@ -428,7 +429,7 @@ func (h *hintBlobs) BroadcastBlob(ctx context.Context, payload []byte, hint ocr3 func eventsWithDeadline(t testing.TB, n int, deadline time.Time) []*pb.CoordinatedEvent { t.Helper() - var events []*pb.CoordinatedEvent + events := make([]*pb.CoordinatedEvent, 0, n) for i := range n { _, e := newCoordinatedEvent(t, "wf", string(rune('a'+i))) e.Deadline = timestamppb.New(deadline) @@ -507,7 +508,7 @@ func TestBroadcastAsBlob(t *testing.T) { 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) + assert.InDelta(t, 100+150, int(hint.SeqNr), 1) //nolint:gosec // G115: small test values }) } @@ -581,7 +582,7 @@ func TestBlobExpirySeqNr(t *testing.T) { 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) + assert.GreaterOrEqual(t, time.Duration(rounds)*roundDur, remaining+minBlobLifetime, "%s remaining at %s per round", remaining, roundDur) //nolint:gosec // G115: small test values } } }) @@ -609,7 +610,7 @@ func TestBroadcastAsBlob_GraceIsOptional(t *testing.T) { 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) + assert.InDelta(t, tt.want, int(blobs.hints[0].(ocr3_1types.BlobExpirationHintSequenceNumber).SeqNr), 1, tt.name) //nolint:gosec // G115: small test values } } diff --git a/core/services/ocr3_1/plugins/queue/config.go b/core/services/ocr3_1/plugins/queue/config.go index ba457698447..a89761b16db 100644 --- a/core/services/ocr3_1/plugins/queue/config.go +++ b/core/services/ocr3_1/plugins/queue/config.go @@ -12,7 +12,7 @@ const ( maxObservedEvents = 1000 // sanity check events in an observation // These are calibrated by the TestCalibration tests. The limits they must fit in come from the job's PluginConfig. - //TODO connect to cre settings, so that changing them is atomic across the DON + // TODO connect to cre settings, so that changing them is atomic across the DON maxKeyValueValueBytes = ocr3_1types.MaxMaxKeyValueValueBytes ) diff --git a/core/services/ocr3_1/plugins/queue/config_test.go b/core/services/ocr3_1/plugins/queue/config_test.go index 6a1a6be6da2..45872512d08 100644 --- a/core/services/ocr3_1/plugins/queue/config_test.go +++ b/core/services/ocr3_1/plugins/queue/config_test.go @@ -133,7 +133,7 @@ func observedEventFor(rng *rand.Rand, i int) *pb.ConsensusQueueEvent { ObservedAt: randTS(rng), Deadline: randTS(rng), TimelessHash: hash[:], - Blobs: []*pb.CoordinatedEventBlobHandle{{Blob: uint32(rng.Intn(maxObservedBlobHandles)), Element: uint32(rng.Intn(maxObservedEvents))}}, + Blobs: []*pb.CoordinatedEventBlobHandle{{Blob: uint32(rng.Intn(maxObservedBlobHandles)), Element: uint32(rng.Intn(maxObservedEvents))}}, //nolint:gosec // G115: bounded by small constants } } @@ -181,13 +181,13 @@ func TestCalibration_ObservationFitsLimit(t *testing.T) { // 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 { - any, err := anypb.New(wrapperspb.Bytes(make([]byte, payload))) + 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: any}}, + Event: &pb.TriggerResponse{Event: &pb.TriggerEvent{TriggerType: "evm@1.0.0", Id: hexID("evt", i) + ":" + hexID("blk", i) + ":7", Payload: payloadAny}}, } } @@ -249,8 +249,8 @@ func TestCalibration_KVState(t *testing.T) { // 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))}} - return protowire.SizeBytes(proto.Size(e)) + protowire.SizeTag(1) // as an element of ConsensusQueueEventList + 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 @@ -269,7 +269,7 @@ func TestCalibration_KVState(t *testing.T) { 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))}) + 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) @@ -306,8 +306,8 @@ func TestCalibration_BlobLifetime(t *testing.T) { 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), + 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") + 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 index aafebde79fe..41b4426a5d8 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -166,9 +166,7 @@ func (m blobHandleMap) addAll(eventHash string, blobHandles map[string]uint32) { m[eventHash] = make(map[string]uint32) } - for blobHandle, elementIndex := range blobHandles { - m[eventHash][blobHandle] = elementIndex - } + 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 @@ -309,12 +307,11 @@ func readObservedEvents(kv ocr3_1types.KeyValueStateReader) (observedEvents map[ observedEvents = make(map[string]*pb.ConsensusQueueObservedEvent) } - return + 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 @@ -371,7 +368,7 @@ func (s *kvState) prepareWriteObservedEvents() { } event.Blobs = append(event.Blobs, &pb.CoordinatedEventBlobHandle{ - Blob: uint32(idx), + Blob: uint32(idx), //nolint:gosec // G115: an index into at most maxObservedBlobHandles blob handles Element: ref.element, }) } @@ -402,7 +399,7 @@ func (s *kvState) prepareWriteBlobHandles() { } blobHandles = append(blobHandles, &pb.CoordinatedEventBlobHandle{ - Blob: uint32(idx), + Blob: uint32(idx), //nolint:gosec // G115: an index into at most maxObservedBlobHandles blob handles Element: ei, }) } @@ -657,7 +654,7 @@ func readConsensusState(kvReader ocr3_1types.KeyValueStateReader) ([]*pb.Consens var consensusEvents []*pb.ConsensusQueueEvent if v != nil { var pbs pb.ConsensusQueueEventList - if err := proto.Unmarshal(v, &pbs); err != nil { + if err = proto.Unmarshal(v, &pbs); err != nil { return nil, nil, fmt.Errorf("failed to unmarshal consensus events: %w", err) } @@ -682,7 +679,7 @@ func readBlobHandles(kvReader ocr3_1types.KeyValueStateReader) ([][]byte, error) var blobHandles [][]byte if v != nil { var bs pb.ConsensusQueueBlobHandleList - if err := proto.Unmarshal(v, &bs); err != nil { + if err = proto.Unmarshal(v, &bs); err != nil { return nil, fmt.Errorf("failed to unmarshal consensus blob handles: %w", err) } diff --git a/core/services/ocr3_1/plugins/queue/kvstate_test.go b/core/services/ocr3_1/plugins/queue/kvstate_test.go index 29bdccaaf96..c2a901b0ebc 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate_test.go +++ b/core/services/ocr3_1/plugins/queue/kvstate_test.go @@ -148,7 +148,7 @@ func TestVoterBlobs(t *testing.T) { for range 50 { m := voterBlobs{} for _, voter := range rand.Perm(10) { - m.add("h", uint8(voter), "shared", uint32(100+voter)) + 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")) } @@ -616,6 +616,7 @@ func TestPrepareWriteBlobHandles(t *testing.T) { } t.Run("idempotent", func(t *testing.T) { + t.Parallel() handles := slices.Clone(s.queuedBlobHandles) s.prepareWriteBlobHandles() assert.Equal(t, handles, s.queuedBlobHandles) @@ -626,6 +627,7 @@ func TestPrepareWriteBlobHandles(t *testing.T) { }) 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) @@ -654,7 +656,7 @@ func TestPrepareWriteObservedEvents_SharedBlobs(t *testing.T) { 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, s.observedBlobs[hash][voter], blobRef{string(s.observedBlobHandles[b.Blob]), b.Element}, "event %s voter %d", hash, voter) + assert.Equal(t, blobRef{string(s.observedBlobHandles[b.Blob]), b.Element}, s.observedBlobs[hash][voter], "event %s voter %d", hash, voter) } } } @@ -785,7 +787,7 @@ func randomState(seed int64) (s *kvState, newlyQueued []string) { } 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))) + 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) { @@ -795,7 +797,7 @@ func randomState(seed int64) (s *kvState, newlyQueued []string) { 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))) + 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) @@ -872,7 +874,7 @@ func randomQueue(rng *rand.Rand, n int, workflows int) (priorityQueue, map[strin 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)) + caps[hexID("wf", w)] = uint32(rng.Intn(6)) //nolint:gosec // G115: small test values } } for i := range n { @@ -929,12 +931,12 @@ func TestPopEligible_Edges(t *testing.T) { var pq priorityQueue pq.push(qEvent(testWF, "a", "h1", 200)) - popped, expired := pq.popEligible(0, map[string]uint32{testWF: 5}, time.Unix(0, 0)) + 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)) + popped, expired := (&priorityQueue{}).popEligible(5, nil, time.Unix(0, 0)) assert.Empty(t, popped, "an empty queue") assert.Zero(t, expired) } diff --git a/core/services/ocr3_1/plugins/queue/metrics_test.go b/core/services/ocr3_1/plugins/queue/metrics_test.go index 35670240c64..53190f548bf 100644 --- a/core/services/ocr3_1/plugins/queue/metrics_test.go +++ b/core/services/ocr3_1/plugins/queue/metrics_test.go @@ -260,7 +260,7 @@ func TestPluginMetrics_ThroughRounds(t *testing.T) { func TestPluginMetrics_ObservationsAreCounted(t *testing.T) { t.Parallel() - events := mkEvents(t, 4, int64(time.Now().Add(time.Hour).Unix())) + 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) diff --git a/core/services/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index b5813520af3..101bae05fbc 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -39,13 +39,13 @@ import ( "sync" "time" - "github.com/smartcontractkit/libocr/commontypes" "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" @@ -236,7 +236,7 @@ func (c *consensusQueuePlugin) Observation( // 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 { + if err = c.discardQueue(ctx); err != nil { return nil, err } c.metrics.recordObservation(ctx, 0) @@ -379,13 +379,13 @@ func observeEvent( TimelessHash: timelessHash, Blobs: []*pb.CoordinatedEventBlobHandle{{ Blob: 0, - Element: uint32(idx), + 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] = uint32(min(wfCapacities[event.WorkflowID], math.MaxUint32)) + obs.WorkflowCapacities[event.WorkflowID] = clampUint32(wfCapacities[event.WorkflowID]) } return @@ -402,7 +402,7 @@ func (c *consensusQueuePlugin) broadcastObservationBlobs( return true, nil } if len(events) != len(obs.Events) { - return false, fmt.Errorf("number of events and observedEvents must match") + return false, errors.New("number of events and observedEvents must match") } // ends[i] is the index after the last event of blob i. We verified space for maxObservedBlobHandles handles. @@ -503,8 +503,8 @@ func (c *consensusQueuePlugin) ValidateObservation( fetcher := blobCache{fetcher: blobFetcher, cache: make(map[string]func() ([]byte, error))} for i, event := range obs.Events { eg.Go(func() error { - if err := validateObservedEvent(ctx, &fetcher, event, obs.BlobHandles); err != nil { - return fmt.Errorf("event %d failed validation: %w", i, err) + if verr := validateObservedEvent(ctx, &fetcher, event, obs.BlobHandles); verr != nil { + return fmt.Errorf("event %d failed validation: %w", i, verr) } return nil }) @@ -563,7 +563,7 @@ func (c *consensusQueuePlugin) ValidateObservation( // wait to do this since we depend on every event being valid if !slices.IsSortedFunc(obs.Events, (*pb.ConsensusQueueEvent).CompareDeadline) { - return fmt.Errorf("events must be sorted") + return errors.New("events must be sorted") } return nil @@ -590,16 +590,16 @@ func validateObservedEvent(ctx context.Context, fetcher *blobCache, event *pb.Co return fmt.Errorf("invalid event deadline: %w", err) } if len(event.TimelessHash) == 0 { - return fmt.Errorf("event blob hash is missing") + 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 fmt.Errorf("event blob is missing") + return errors.New("event blob is missing") } if len(event.Blobs) > 1 { - return fmt.Errorf("event has more than one blob") + return errors.New("event has more than one blob") } blobIdx := int(event.Blobs[0].Blob) @@ -612,7 +612,7 @@ func validateObservedEvent(ctx context.Context, fetcher *blobCache, event *pb.Co if err != nil { return fmt.Errorf("failed to fetch event from blob: %w", err) } else if coordEvent == nil { - return fmt.Errorf("failed to fetch event from blob: event is nil") + return errors.New("failed to fetch event from blob: event is nil") } if coordEvent.WorkflowID != event.WorkflowID { @@ -792,7 +792,6 @@ func (res *observations) aggregate(ctx context.Context, f int, aos []ocrtypes.At caps = append(caps, make([]uint32, len(aos)-len(caps))...) res.medianCapPerWF[wf] = slices.Sorted(slices.Values(caps))[f] } - return } // addEvent adds the observed event to the observation set, either merging it into an existing event or creating a new one. @@ -878,7 +877,6 @@ func (c *consensusQueuePlugin) tryStartExecutions(ctx context.Context, done chan } wg.Wait() - return } func (c *consensusQueuePlugin) tryStartExecution(ctx context.Context, fetcher *blobCache, consensusEvent *pb.ConsensusQueueEvent, blobHandles [][]byte) error { diff --git a/core/services/ocr3_1/plugins/queue/queue_test.go b/core/services/ocr3_1/plugins/queue/queue_test.go index 2e15cd3f350..70845c74949 100644 --- a/core/services/ocr3_1/plugins/queue/queue_test.go +++ b/core/services/ocr3_1/plugins/queue/queue_test.go @@ -13,6 +13,7 @@ import ( "math/rand" "slices" "sort" + "strconv" "strings" "sync" "sync/atomic" @@ -171,7 +172,7 @@ func (q sliceQueue) Sorted(_ context.Context, limit, _ int) iter.Seq2[[]byte, *p // 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 { + if err := h.UnmarshalBinary(handleBytes(byte(i))); err != nil { //nolint:gosec // G115: a small test value panic(err) } return h @@ -371,7 +372,7 @@ func TestBroadcastObservationBlobs(t *testing.T) { blobs := &memBlobs{} c := testPlugin(t, sliceQueue{}, blobs, ocr3_1types.MaxMaxObservationBytes) obs := &pb.ConsensusQueueObservation{WorkflowCapacities: map[string]uint32{}} - var events []*pb.CoordinatedEvent + events := make([]*pb.CoordinatedEvent, 0, 3) for _, id := range []string{"a", "b", "c"} { h, e := newCoordinatedEvent(t, testWF, id) events = append(events, e) @@ -400,7 +401,7 @@ func TestBroadcastObservationBlobs(t *testing.T) { func TestObservation_PassesValidateObservation(t *testing.T) { t.Parallel() - var events []hashedEvent + events := make([]hashedEvent, 0, 2) for _, id := range []string{"a", "b"} { h, e := newCoordinatedEvent(t, testWF, id) events = append(events, hashedEvent{h, e}) @@ -433,7 +434,7 @@ func TestObservation_NoEvents(t *testing.T) { var obs pb.ConsensusQueueObservation require.NoError(t, proto.Unmarshal(raw, &obs)) assert.Empty(t, obs.Events) - assert.Zero(t, len(obs.BlobHandles), "size-estimation placeholders must not be sent") + 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{})) } @@ -441,7 +442,7 @@ func TestObservation_NoEvents(t *testing.T) { func TestObservation_SizeLimited(t *testing.T) { t.Parallel() - var events []hashedEvent + events := make([]hashedEvent, 0, 3) for _, id := range []string{"a", "b", "c"} { h, e := newCoordinatedEvent(t, testWF, id) events = append(events, hashedEvent{h, e}) @@ -515,7 +516,7 @@ func TestValidateObservedEvent(t *testing.T) { {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"}, + {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"}, @@ -562,7 +563,7 @@ func TestValidateObservedEvent(t *testing.T) { // 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() - var events []hashedEvent + 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)) @@ -721,13 +722,13 @@ func ao(t testing.TB, id int, obs *pb.ConsensusQueueObservation) ocrtypes.Attrib t.Helper() b, err := proto.Marshal(obs) require.NoError(t, err) - return ocrtypes.AttributedObservation{Observer: commontypes.OracleID(id), Observation: b} + 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() - var out []hashedEvent + 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)) @@ -761,7 +762,7 @@ func consensusIDs(t *testing.T, kv memKV) []string { t.Helper() events, handles, err := readConsensusState(kv) require.NoError(t, err) - var ids []string + 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 { @@ -776,7 +777,7 @@ func consensusIDs(t *testing.T, kv memKV) []string { func queuedIDs(t *testing.T, kv memKV) []string { t.Helper() s := loadState(t, kv) - var ids []string + 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) @@ -1057,12 +1058,12 @@ func TestStateTransition_SizeLimits(t *testing.T) { 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 - var all []string + all := make([]string, 0, len(e)) for _, ev := range e { all = append(all, string(ev.hash)) } slices.Sort(all) - var kept []string + kept := make([]string, 0, len(st.observedEvents)) for h := range st.observedEvents { kept = append(kept, h) } @@ -1087,7 +1088,7 @@ func TestStateTransition_SizeLimits(t *testing.T) { got := queuedIDs(t, kv) require.NotEmpty(t, got) require.Less(t, len(got), 30) - var want []string + want := make([]string, 0, len(got)) for i := range got { // the earliest deadlines survive want = append(want, execIDOf(t, fmt.Sprintf("evt-%02d", i))) } @@ -1209,7 +1210,7 @@ func newCommitPlugin(t testing.TB, coord triggers.Coordinator, q triggers.Queue, func seedKV(t testing.TB, kv memKV, blobs *memBlobs, consensus, queued []string) (execIDs []string) { t.Helper() s := newKVState() - var ces []*pb.CoordinatedEvent + 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)) @@ -1437,7 +1438,7 @@ func TestObservation_Fields(t *testing.T) { obs, err := observe(t, c, kv, blobs) require.NoError(t, err) - var got [][]byte + got := make([][]byte, 0, len(obs.Events)) for _, e := range obs.Events { got = append(got, e.TimelessHash) } @@ -1465,7 +1466,7 @@ func TestObservation_BlobBatching(t *testing.T) { } } events := func(t *testing.T, n int) []hashedEvent { - return mkEvents(t, n, int64(time.Now().Add(time.Hour).Unix())) + return mkEvents(t, n, time.Now().Add(time.Hour).Unix()) } t.Run("events spread over several blobs keep correct refs", func(t *testing.T) { @@ -1537,7 +1538,7 @@ func TestObservation_BlobFailuresAreNotFatal(t *testing.T) { t.Run("broadcast error", func(t *testing.T) { t.Parallel() blobs := &hintBlobs{err: errBoom} - c := testPlugin(t, sliceQueue{events: mkEvents(t, 2, int64(time.Now().Add(time.Hour).Unix()))}, blobs, ocr3_1types.MaxMaxObservationBytes) + 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) @@ -1546,7 +1547,7 @@ func TestObservation_BlobFailuresAreNotFatal(t *testing.T) { t.Run("event larger than a blob", func(t *testing.T) { t.Parallel() blobs := &memBlobs{} - c := testPlugin(t, sliceQueue{events: mkEvents(t, 2, int64(time.Now().Add(time.Hour).Unix()))}, blobs, ocr3_1types.MaxMaxObservationBytes) + 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") @@ -1585,7 +1586,7 @@ func TestMaxEventBytes(t *testing.T) { return e } for _, limit := range []int{6, 127, 128, 129, 1 << 14, 1<<21 - 1, 1 << 21, ocr3_1types.MaxMaxBlobPayloadBytes} { - t.Run(fmt.Sprint(limit), func(t *testing.T) { + t.Run(strconv.Itoa(limit), func(t *testing.T) { t.Parallel() c := testPlugin(t, sliceQueue{}, &memBlobs{}, ocr3_1types.MaxMaxObservationBytes) c.limits.MaxBlobPayloadBytes = limit @@ -1735,7 +1736,7 @@ func TestBroadcastAsBlob_LargestFit(t *testing.T) { // 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, int64(time.Now().Add(time.Hour).Unix())) + 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}}) @@ -1798,7 +1799,7 @@ func (f *fetchCountingBlobs) FetchBlob(ctx context.Context, h ocr3_1types.BlobHa } // ctxBlobs fails like libocr does when its context is done. -type ctxBlobs struct{ memBlobs } +type ctxBlobs struct{} func (ctxBlobs) BroadcastBlob(ctx context.Context, _ []byte, _ ocr3_1types.BlobExpirationHint) (ocr3_1types.BlobHandle, error) { return ocr3_1types.BlobHandle{}, ctx.Err() @@ -1855,7 +1856,7 @@ func TestContextCancellation(t *testing.T) { t.Run("Observation fails instead of degrading to an observation without events", func(t *testing.T) { t.Parallel() - ev := mkEvents(t, 2, int64(time.Now().Add(time.Hour).Unix())) + 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) @@ -1863,7 +1864,7 @@ func TestContextCancellation(t *testing.T) { t.Run("Observation fails if one of several blob broadcasts is cancelled", func(t *testing.T) { t.Parallel() - ev := mkEvents(t, 4, int64(time.Now().Add(time.Hour).Unix())) + 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) @@ -1914,7 +1915,7 @@ func (f *failBlobsWith) BroadcastBlob(ctx context.Context, payload []byte, hint func TestObservation_PartialBlobFailure(t *testing.T) { t.Parallel() - ev := mkEvents(t, 6, int64(time.Now().Add(time.Hour).Unix())) // two events per blob + 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 { @@ -2255,7 +2256,7 @@ func TestObservationSize(t *testing.T) { 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)))) + 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) } @@ -2284,7 +2285,7 @@ func BenchmarkFullStateTransitionOverLimit(b *testing.B) { none.wfCaps[e.event.WorkflowID] = 1 << 20 } round := func(b *testing.B, o nodeOpts, events []hashedEvent, nodes int) []ocrtypes.AttributedObservation { - var aos []ocrtypes.AttributedObservation + aos := make([]ocrtypes.AttributedObservation, 0, n) for node := range n { var seen []hashedEvent if node < nodes { @@ -2319,7 +2320,7 @@ func BenchmarkFullStateTransitionOverLimit(b *testing.B) { b.Run("full queue receives 3000 more", func(b *testing.B) { c := newSTPlugin(b) seed := memKV{} - for i := 0; i < 9; i++ { // fill the queue to just under its value limit + 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)) } @@ -2348,7 +2349,7 @@ func TestValidateObservation_RejectsBlobPaddedWithEmptyEvents(t *testing.T) { 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)[:]...) + payload = append(payload, marshalEvents(t, ce)...) obs.Events = append(obs.Events, qe) } blobs.store(handleBytes(1), payload) @@ -2369,7 +2370,7 @@ func TestStateTransition_RepeatedVotesDoNotGrowState(t *testing.T) { 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)) // a new blob each round + 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)) } @@ -2532,7 +2533,7 @@ func TestKVDrainActive(t *testing.T) { func TestObservation_KVDrain(t *testing.T) { t.Parallel() - events := mkEvents(t, 3, int64(time.Now().Add(time.Hour).Unix())) + 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) @@ -2609,7 +2610,7 @@ func TestStateTransition_KVDrainNeedsFPlusOneVotes(t *testing.T) { 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) - var aos []ocrtypes.AttributedObservation + aos := make([]ocrtypes.AttributedObservation, 0, 3) for i := range 3 { o := noCapacity o.drain = i < votes @@ -2656,7 +2657,7 @@ func TestValidateObservation_KVDrain(t *testing.T) { require.NoError(t, validate(empty), "no events and no blob handles") withEvents := nodeObs(t, drain, mkEvents(t, 1, 2000)...) - assert.ErrorContains(t, validate(withEvents), "KV drain mode reports no new events") + require.ErrorContains(t, validate(withEvents), "KV drain mode reports no new events") withHandles := nodeObs(t, drain) withHandles.Events = nil diff --git a/core/services/workflows/store/store_memory.go b/core/services/workflows/store/store_memory.go index 75e247428c6..a3d973d9324 100644 --- a/core/services/workflows/store/store_memory.go +++ b/core/services/workflows/store/store_memory.go @@ -55,11 +55,11 @@ type InMemoryStore struct { minimumCompletedRetention func() time.Duration } -// SetMinimumCompletedRetention makes the store keep a completed execution for at least as long as min returns, if that +// 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. min is called on each sweep, and must be set before Start. -func (s *InMemoryStore) SetMinimumCompletedRetention(min func() time.Duration) { - s.minimumCompletedRetention = min +// 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 { diff --git a/core/services/workflows/store/store_memory_test.go b/core/services/workflows/store/store_memory_test.go index 1c5c741ce2e..6e7bbb02695 100644 --- a/core/services/workflows/store/store_memory_test.go +++ b/core/services/workflows/store/store_memory_test.go @@ -237,10 +237,10 @@ func TestInMemoryStore_MinimumCompletedRetention(t *testing.T) { isPruned := func(store *InMemoryStore) func() bool { return func() bool { _, err := store.Get(t.Context(), "test-id"); return err != nil } } - newStore := func(t *testing.T, min func() time.Duration) (*InMemoryStore, *clockwork.FakeClock) { + 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(min) + store.SetMinimumCompletedRetention(retention) servicetest.Run(t, store) _, err := store.Add(t.Context(), nil, "test-id", "w1", StatusStarted) require.NoError(t, err) @@ -270,11 +270,11 @@ func TestInMemoryStore_MinimumCompletedRetention(t *testing.T) { t.Run("follows a minimum that grows after the execution completed", func(t *testing.T) { t.Parallel() - var min atomic.Int64 - min.Store(int64(time.Minute)) - store, fakeClock := newStore(t, func() time.Duration { return time.Duration(min.Load()) }) + var retention atomic.Int64 + retention.Store(int64(time.Minute)) + store, fakeClock := newStore(t, func() time.Duration { return time.Duration(retention.Load()) }) - min.Store(int64(3 * time.Hour)) // a workflow with a long timeout was seen + 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) diff --git a/core/services/workflows/v2/triggers/coordinator_test.go b/core/services/workflows/v2/triggers/coordinator_test.go index 597439ebbb8..d73fea9d324 100644 --- a/core/services/workflows/v2/triggers/coordinator_test.go +++ b/core/services/workflows/v2/triggers/coordinator_test.go @@ -1387,12 +1387,10 @@ func TestEventLifetime(t *testing.T) { l := NewEventLifetime(graceOf(0, nil)) var wg sync.WaitGroup for i := range 50 { - wg.Add(1) - go func() { - defer wg.Done() + 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())) diff --git a/core/services/workflows/v2/triggers/queue.go b/core/services/workflows/v2/triggers/queue.go index 262aeb9fdb0..b0720d4825a 100644 --- a/core/services/workflows/v2/triggers/queue.go +++ b/core/services/workflows/v2/triggers/queue.go @@ -193,7 +193,6 @@ func (q *CentralQueue) Remove(ctx context.Context, executionIDs iter.Seq[string] q.metrics.IncrementDrainedEventsCounter(ctx, deleted) q.metrics.RecordDepth(ctx, len(q.events)) q.metrics.RecordCapacity(ctx, q.effectiveCapacity(capacity)) - return } func (q *CentralQueue) Sorted(ctx context.Context, limit, maxEventBytes int) iter.Seq2[[]byte, *pb.CoordinatedEvent] { diff --git a/core/services/workflows/v2/triggers/queue_test.go b/core/services/workflows/v2/triggers/queue_test.go index ff2e926f30c..488475a107e 100644 --- a/core/services/workflows/v2/triggers/queue_test.go +++ b/core/services/workflows/v2/triggers/queue_test.go @@ -543,7 +543,7 @@ func TestQueue_SortedDropsOversize(t *testing.T) { t.Parallel() q, maxSmall := newQueue(t) assert.Len(t, ids(q, 10, maxSmall), 2) - assert.Len(t, ids(q, 10, maxSmall-1), 0, "one byte less and the small events no longer fit") + 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) { From 9a042f12cb2961545c39970bfe98e7e03ba51f91 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Mon, 23 Nov 2026 14:52:23 -0600 Subject: [PATCH 35/38] never observe duplicate events; ensure no repeated blob handles --- core/scripts/go.mod | 2 +- core/scripts/go.sum | 4 +- core/services/ocr3_1/plugins/queue/queue.go | 48 ++++++++++++++------- deployment/go.mod | 2 +- deployment/go.sum | 4 +- go.mod | 2 +- go.sum | 4 +- integration-tests/go.mod | 2 +- integration-tests/go.sum | 4 +- integration-tests/load/go.mod | 2 +- integration-tests/load/go.sum | 4 +- system-tests/lib/go.mod | 2 +- system-tests/lib/go.sum | 4 +- system-tests/tests/go.mod | 2 +- system-tests/tests/go.sum | 4 +- 15 files changed, 54 insertions(+), 36 deletions(-) diff --git a/core/scripts/go.mod b/core/scripts/go.mod index 1c51712f617..8da158b2cc3 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.20261123022730-576156afb51f + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9 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 07aca5bad85..a4c568645f6 100644 --- a/core/scripts/go.sum +++ b/core/scripts/go.sum @@ -1686,8 +1686,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.20261123022730-576156afb51f h1:E1+AQ1s3F1goVK1zZxAnPHfD5TV8JVslm0PIyJJtpMs= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f/go.mod h1:Gv+qglZ5Kxtf4pvpYIx/FBbntZDuvxVH0a6zFNuG+e8= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9 h1:7mCg2xaRhnXNK5Ql7a4iZIjz3LTMgdgkOIQm9BLCMT4= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9/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/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index 101bae05fbc..9d82c0ee2d3 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -309,8 +309,14 @@ 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)) { @@ -394,6 +400,8 @@ func observeEvent( // 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 are divided between blobs first, so that the blobs can be broadcast concurrently. +// opt: remember blobs so we don't have to rebroadcast 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 { @@ -546,21 +579,6 @@ func (c *consensusQueuePlugin) ValidateObservation( } } - // ensure no duplicate execution ID or timelessHash - execIDs, timelessHashes := make(map[string]struct{}), make(map[string]struct{}) - for _, 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{}{} - } - // 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") diff --git a/deployment/go.mod b/deployment/go.mod index 82e4bf9080a..66158774d03 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.20261123022730-576156afb51f + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9 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 381a33bba1d..04056fdc4d0 100644 --- a/deployment/go.sum +++ b/deployment/go.sum @@ -1411,8 +1411,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.20261123022730-576156afb51f h1:E1+AQ1s3F1goVK1zZxAnPHfD5TV8JVslm0PIyJJtpMs= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f/go.mod h1:Gv+qglZ5Kxtf4pvpYIx/FBbntZDuvxVH0a6zFNuG+e8= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9 h1:7mCg2xaRhnXNK5Ql7a4iZIjz3LTMgdgkOIQm9BLCMT4= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9/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 89efe03457f..de8717bc30a 100644 --- a/go.mod +++ b/go.mod @@ -82,7 +82,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.20261123022730-576156afb51f + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9 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 880b55412cd..9cc7e6019e6 100644 --- a/go.sum +++ b/go.sum @@ -1102,8 +1102,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.20261123022730-576156afb51f h1:E1+AQ1s3F1goVK1zZxAnPHfD5TV8JVslm0PIyJJtpMs= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f/go.mod h1:Gv+qglZ5Kxtf4pvpYIx/FBbntZDuvxVH0a6zFNuG+e8= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9 h1:7mCg2xaRhnXNK5Ql7a4iZIjz3LTMgdgkOIQm9BLCMT4= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9/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 f2237136674..90f78552564 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.20261123022730-576156afb51f + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9 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 ce9f16d99d2..6257431b993 100644 --- a/integration-tests/go.sum +++ b/integration-tests/go.sum @@ -1396,8 +1396,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.20261123022730-576156afb51f h1:E1+AQ1s3F1goVK1zZxAnPHfD5TV8JVslm0PIyJJtpMs= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f/go.mod h1:Gv+qglZ5Kxtf4pvpYIx/FBbntZDuvxVH0a6zFNuG+e8= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9 h1:7mCg2xaRhnXNK5Ql7a4iZIjz3LTMgdgkOIQm9BLCMT4= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9/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 05cbf651114..db082451584 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.20261123022730-576156afb51f + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9 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 233c74e01ff..fc628d78d0b 100644 --- a/integration-tests/load/go.sum +++ b/integration-tests/load/go.sum @@ -1636,8 +1636,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.20261123022730-576156afb51f h1:E1+AQ1s3F1goVK1zZxAnPHfD5TV8JVslm0PIyJJtpMs= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f/go.mod h1:Gv+qglZ5Kxtf4pvpYIx/FBbntZDuvxVH0a6zFNuG+e8= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9 h1:7mCg2xaRhnXNK5Ql7a4iZIjz3LTMgdgkOIQm9BLCMT4= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9/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 c6e6d724e9c..a72143d838b 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.20261123022730-576156afb51f + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9 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 e8a7f819b83..846b3f90832 100644 --- a/system-tests/lib/go.sum +++ b/system-tests/lib/go.sum @@ -1657,8 +1657,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.20261123022730-576156afb51f h1:E1+AQ1s3F1goVK1zZxAnPHfD5TV8JVslm0PIyJJtpMs= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f/go.mod h1:Gv+qglZ5Kxtf4pvpYIx/FBbntZDuvxVH0a6zFNuG+e8= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9 h1:7mCg2xaRhnXNK5Ql7a4iZIjz3LTMgdgkOIQm9BLCMT4= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9/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 6f33bde37b2..59c88055388 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.20261123022730-576156afb51f + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9 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 f8108a7b34d..a71e78f0f6a 100644 --- a/system-tests/tests/go.sum +++ b/system-tests/tests/go.sum @@ -1836,8 +1836,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.20261123022730-576156afb51f h1:E1+AQ1s3F1goVK1zZxAnPHfD5TV8JVslm0PIyJJtpMs= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123022730-576156afb51f/go.mod h1:Gv+qglZ5Kxtf4pvpYIx/FBbntZDuvxVH0a6zFNuG+e8= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9 h1:7mCg2xaRhnXNK5Ql7a4iZIjz3LTMgdgkOIQm9BLCMT4= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9/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= From a5bebbae7efe44b4d6d3f43a1602f3e9995e8813 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Tue, 24 Nov 2026 09:06:45 -0600 Subject: [PATCH 36/38] cleanup and pruning --- core/services/ocr3_1/plugins/queue/README.md | 10 +++++----- core/services/ocr3_1/plugins/queue/kvstate.go | 9 +++++++++ core/services/ocr3_1/plugins/queue/queue.go | 14 ++++++++------ core/services/ocr3_1/plugins/queue/queue_test.go | 12 ++++++------ 4 files changed, 28 insertions(+), 17 deletions(-) diff --git a/core/services/ocr3_1/plugins/queue/README.md b/core/services/ocr3_1/plugins/queue/README.md index f4621ea594d..3df8b798d25 100644 --- a/core/services/ocr3_1/plugins/queue/README.md +++ b/core/services/ocr3_1/plugins/queue/README.md @@ -77,10 +77,10 @@ sequenceDiagram Note over StateTransition: nothing new is added StateTransition->>consensus: Write(): every queued event, whatever the capacity else - alt fewer than F+1 votes for an event - StateTransition->>observed: Write(): the vote and its blob - else F+1 votes + 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 @@ -112,7 +112,7 @@ stateDiagram-v2 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: capacity (overall and for its workflow) + 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 @@ -125,7 +125,7 @@ Nothing retries a failed start: once an event is in consensus it leaves the queu | Key | Holds | | --- | --- | | `observed_events::index` | events with fewer than F+1 votes: who voted, and each voter's blob | -| `queued_events::index` | events with consensus, waiting for capacity, in priority order | +| `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 | diff --git a/core/services/ocr3_1/plugins/queue/kvstate.go b/core/services/ocr3_1/plugins/queue/kvstate.go index 41b4426a5d8..70c6bac2005 100644 --- a/core/services/ocr3_1/plugins/queue/kvstate.go +++ b/core/services/ocr3_1/plugins/queue/kvstate.go @@ -557,6 +557,7 @@ func (s *kvState) writeTo(w *stateWriter) error { return nil } +// pruneExpiredObservations deletes expired observations, but does not evict on capacity + 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 @@ -756,7 +758,7 @@ type observations struct { } func (res *observations) aggregate(ctx context.Context, f int, aos []ocrtypes.AttributedObservation) { - res.medianCapPerWF = make(map[string]uint32) + res.fPlus1thCapPerWF = make(map[string]uint32) res.newObservedEvents = make(map[string]*pb.ConsensusQueueObservedEvent) res.observedBlobs = make(voterBlobs) @@ -803,12 +805,12 @@ func (res *observations) aggregate(ctx context.Context, f int, aos []ocrtypes.At // 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.medianCap = slices.Sorted(slices.Values(capacities))[f] + 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.medianCapPerWF[wf] = slices.Sorted(slices.Values(caps))[f] + res.fPlus1thCapPerWF[wf] = slices.Sorted(slices.Values(caps))[f] } } diff --git a/core/services/ocr3_1/plugins/queue/queue_test.go b/core/services/ocr3_1/plugins/queue/queue_test.go index 70845c74949..9a9c97911ab 100644 --- a/core/services/ocr3_1/plugins/queue/queue_test.go +++ b/core/services/ocr3_1/plugins/queue/queue_test.go @@ -308,8 +308,8 @@ func TestObservationsAggregate(t *testing.T) { mkAO(2, base(7, map[string]uint32{testWF: 9})), }) require.NoError(t, res.err) - assert.Equal(t, uint32(7), res.medianCap, "F+1th lowest of 1,7,10") - assert.Equal(t, uint32(5), res.medianCapPerWF[testWF], "F+1th lowest of 1,5,9") + 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()) }) @@ -322,7 +322,7 @@ func TestObservationsAggregate(t *testing.T) { mkAO(2, base(6, nil)), // honest mkAO(3, base(1<<31, nil)), // byzantine high }) - assert.Equal(t, uint32(5), res.medianCap) + assert.Equal(t, uint32(5), res.fPlus1thCap) }) t.Run("garbage observation errors", func(t *testing.T) { @@ -1653,7 +1653,7 @@ func TestObservationsAggregate_Omissions(t *testing.T) { 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.medianCapPerWF[testWF], "F omissions count as zero, which sorted[F] tolerates") + 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) { @@ -1661,8 +1661,8 @@ func TestObservationsAggregate_Omissions(t *testing.T) { 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.medianCapPerWF, testWF) - assert.Zero(t, res.medianCapPerWF[testWF]) + 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) { From 5a0e98cde11b4f34d1fa91495f20f9eb22873609 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Tue, 24 Nov 2026 09:29:30 -0600 Subject: [PATCH 37/38] don't short circuit on broacast failure --- core/scripts/go.mod | 2 +- core/scripts/go.sum | 4 +- core/services/ocr3_1/plugins/queue/queue.go | 42 +++++++++---------- .../ocr3_1/plugins/queue/queue_test.go | 16 ++++--- deployment/go.mod | 2 +- deployment/go.sum | 4 +- go.mod | 2 +- go.sum | 4 +- integration-tests/go.mod | 2 +- integration-tests/go.sum | 4 +- integration-tests/load/go.mod | 2 +- integration-tests/load/go.sum | 4 +- system-tests/lib/go.mod | 2 +- system-tests/lib/go.sum | 4 +- system-tests/tests/go.mod | 2 +- system-tests/tests/go.sum | 4 +- 16 files changed, 52 insertions(+), 48 deletions(-) diff --git a/core/scripts/go.mod b/core/scripts/go.mod index 7072b5f2253..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.20261123175101-9ca98b2bd5e9 + 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 83c99560de9..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.20261123175101-9ca98b2bd5e9 h1:7mCg2xaRhnXNK5Ql7a4iZIjz3LTMgdgkOIQm9BLCMT4= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9/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/ocr3_1/plugins/queue/queue.go b/core/services/ocr3_1/plugins/queue/queue.go index 08cd8b35d40..5a97aac5295 100644 --- a/core/services/ocr3_1/plugins/queue/queue.go +++ b/core/services/ocr3_1/plugins/queue/queue.go @@ -398,7 +398,9 @@ func observeEvent( } // 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. +// 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 0 { assert.Contains(t, obs.WorkflowCapacities, testWF, "capacities cover the events kept") diff --git a/deployment/go.mod b/deployment/go.mod index f265f0328b1..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.20261123175101-9ca98b2bd5e9 + 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 ab5eea7f2c3..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.20261123175101-9ca98b2bd5e9 h1:7mCg2xaRhnXNK5Ql7a4iZIjz3LTMgdgkOIQm9BLCMT4= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9/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 8c8f242751c..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.20261123175101-9ca98b2bd5e9 + 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 90910ab4bd3..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.20261123175101-9ca98b2bd5e9 h1:7mCg2xaRhnXNK5Ql7a4iZIjz3LTMgdgkOIQm9BLCMT4= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9/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 dc769ca02cc..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.20261123175101-9ca98b2bd5e9 + 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 4db15b8d406..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.20261123175101-9ca98b2bd5e9 h1:7mCg2xaRhnXNK5Ql7a4iZIjz3LTMgdgkOIQm9BLCMT4= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9/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 d379dbf64b3..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.20261123175101-9ca98b2bd5e9 + 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 91f4cd2d3f1..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.20261123175101-9ca98b2bd5e9 h1:7mCg2xaRhnXNK5Ql7a4iZIjz3LTMgdgkOIQm9BLCMT4= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9/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 9132554519d..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.20261123175101-9ca98b2bd5e9 + 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 f1666da7737..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.20261123175101-9ca98b2bd5e9 h1:7mCg2xaRhnXNK5Ql7a4iZIjz3LTMgdgkOIQm9BLCMT4= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9/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 36e4467196c..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.20261123175101-9ca98b2bd5e9 + 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 2af6076fe64..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.20261123175101-9ca98b2bd5e9 h1:7mCg2xaRhnXNK5Ql7a4iZIjz3LTMgdgkOIQm9BLCMT4= -github.com/smartcontractkit/chainlink-common v0.11.2-0.20261123175101-9ca98b2bd5e9/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= From ad9d14672b653883d4e6a341e7bbbad3aca9d3cb Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Tue, 24 Nov 2026 09:57:04 -0600 Subject: [PATCH 38/38] test cleanup --- core/services/ocr2/validate/validate_test.go | 40 -------------------- 1 file changed, 40 deletions(-) diff --git a/core/services/ocr2/validate/validate_test.go b/core/services/ocr2/validate/validate_test.go index 1031247740b..fd3d7c57898 100644 --- a/core/services/ocr2/validate/validate_test.go +++ b/core/services/ocr2/validate/validate_test.go @@ -26,46 +26,6 @@ func TestValidateOracleSpec(t *testing.T) { overrides func(c *chainlink.Config, s *chainlink.Secrets) assertion func(t *testing.T, os job.Job, err error) }{ - { - name: "consensus queue spec without plugin config is rejected, not a panic", - toml: ` -type = "offchainreporting2" -schemaVersion = 1 -pluginType = "consensus-queue" -relay = "evm" -contractID = "0x613a38AC1659769640aaE063C651F48E0250454C" -transmitterID = "0x613a38AC1659769640aaE063C651F48E0250454C" -[relayConfig] -chainID = 1337 -`, - assertion: func(t *testing.T, _ job.Job, err error) { - require.Error(t, err) - assert.Contains(t, err.Error(), "MaxObservationBytes (0) must be positive") - }, - }, - { - name: "consensus queue spec with limits", - toml: ` -type = "offchainreporting2" -schemaVersion = 1 -pluginType = "consensus-queue" -relay = "evm" -contractID = "0x613a38AC1659769640aaE063C651F48E0250454C" -transmitterID = "0x613a38AC1659769640aaE063C651F48E0250454C" -[relayConfig] -chainID = 1337 -[pluginConfig.limits] -MaxObservationBytes = 524288 -MaxKeyValueModifiedKeys = 4 -MaxKeyValueModifiedKeysPlusValuesBytes = 10485760 -MaxBlobPayloadBytes = 5242880 -MaxPerOracleUnexpiredBlobCumulativePayloadBytes = 104857600 -MaxPerOracleUnexpiredBlobCount = 100 -`, - assertion: func(t *testing.T, _ job.Job, err error) { - require.NoError(t, err) - }, - }, { name: "minimal OCR2 oracle spec", toml: `