From 82f6d19020f4c8552308b895a37bd4c7a5cdad05 Mon Sep 17 00:00:00 2001 From: Adam Hamrick Date: Wed, 11 Nov 2026 08:23:48 -0500 Subject: [PATCH 01/10] perf(tests): cut llo wall time llo tests: add WithRMax and use RMax=10 (5s epochs instead of 50s) in v31_blob_catchup and v31_restart_resumes, which waited out a full epoch. Those two tests drop from 66-82s to ~28s. cltest: use N=2^4 scrypt params for test keystores. The keyring is re-encrypted on every key add; scrypt was 14% of llo CPU. Co-Authored-By: Claude Sonnet 5.5 --- core/internal/cltest/cltest.go | 10 ++++++++-- .../ocr2/plugins/llo/integration_test.go | 17 +++++++++++++++-- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/core/internal/cltest/cltest.go b/core/internal/cltest/cltest.go index 6b85f2ed090..85a3d686857 100644 --- a/core/internal/cltest/cltest.go +++ b/core/internal/cltest/cltest.go @@ -385,7 +385,7 @@ func NewApplicationWithConfig(t testing.TB, cfg chainlink.GeneralConfig, flagsAn } } } - keyStore := keystore.NewInMemory(ds, commonkeystore.FastScryptParams, lggr.Infof) + keyStore := keystore.NewInMemory(ds, TestScryptParams, lggr.Infof) require.NoError(t, keyStore.Unlock(ctx, Password)) logPubKeys(t, keyStore) @@ -793,10 +793,16 @@ func (ta *TestApplication) NewAuthenticatingShell(prompter cmd.Prompter) *cmd.Sh return client } +// TestScryptParams is the cheapest scrypt cost (N=2^4) for test keystores. +// The keyring is re-encrypted on every key add, so FastScryptParams (N=2^14, +// ~16 MB per call) was a measurable share of CPU in suites that start many +// apps. Tests of encryption itself should use real params. +var TestScryptParams = commonkeystore.ScryptParams{N: 1 << 4, P: 1} + // NewKeyStore returns a new, unlocked keystore func NewKeyStore(t testing.TB, ds sqlutil.DataSource) keystore.Master { ctx := t.Context() - keystore := keystore.NewInMemory(ds, commonkeystore.FastScryptParams, logger.TestLogger(t).Infof) + keystore := keystore.NewInMemory(ds, TestScryptParams, logger.TestLogger(t).Infof) require.NoError(t, keystore.Unlock(ctx, Password)) logPubKeys(t, keystore) return keystore diff --git a/core/services/ocr2/plugins/llo/integration_test.go b/core/services/ocr2/plugins/llo/integration_test.go index 3312fe3205d..4f7a4b784b2 100644 --- a/core/services/ocr2/plugins/llo/integration_test.go +++ b/core/services/ocr2/plugins/llo/integration_test.go @@ -304,6 +304,15 @@ func WithV31() OCRConfigOption { } } +// WithRMax sets the number of rounds per epoch. An oracle that joins or restarts +// takes part from the next epoch, so a small RMax shortens its catch-up wait +// (epoch length is about RMax x DeltaRound). +func WithRMax(rMax uint64) OCRConfigOption { + return func(cfg *OCRConfig) { + cfg.RMax = rMax + } +} + type OCRConfigOption func(*OCRConfig) func generateConfig(t *testing.T, opts ...OCRConfigOption) (signers []types.OnchainPublicKey, transmitters []types.Account, f uint8, outOnchainConfig []byte, offchainConfigVersion uint64, offchainConfig []byte) { @@ -3569,6 +3578,10 @@ pluginVersion = "v31"`, serverURL, serverPubKey, donID, configStoreAddress, from // reporting, and an oracle whose job is deleted mid-run and re-created after // the DON has advanced many rounds without it. In both cases the remaining // 3 oracles (2F+1) keep the DON reporting throughout. +// shortEpochRMax gives ~5 s epochs at the default 500ms DeltaRound, so a +// late or restarted oracle does not wait out a 50 s epoch (RMax 100). +const shortEpochRMax = uint64(10) + func TestIntegration_LLO_v31_blob_catchup(t *testing.T) { t.Parallel() tcs := []struct { @@ -3710,7 +3723,7 @@ pluginVersion = "v31"`, serverURL, serverPubKey, donID, configStoreAddress, from setProductionConfig( t, donID, steve, backend, configurator, configuratorAddress, nodes, - WithOracles(oracles), WithOffchainConfig(offchainConfig), WithV31(), + WithOracles(oracles), WithOffchainConfig(offchainConfig), WithV31(), WithRMax(shortEpochRMax), ) // reportsFlowing drains transmitted reports for the channel under test until @@ -3881,7 +3894,7 @@ pluginVersion = "v31"`, serverURL, serverPubKey, donID, configStoreAddress, from setProductionConfig( t, donID, steve, backend, configurator, configuratorAddress, nodes, - WithOracles(oracles), WithOffchainConfig(offchainConfig), WithV31(), + WithOracles(oracles), WithOffchainConfig(offchainConfig), WithV31(), WithRMax(shortEpochRMax), ) reportsFlowing := func(d time.Duration) bool { From 5dd9d57898e4d1a2a659606877a14c944ea3217b Mon Sep 17 00:00:00 2001 From: Adam Hamrick Date: Wed, 11 Nov 2026 08:23:48 -0500 Subject: [PATCH 02/10] order packages --- core/internal/features/ocr2/features_ocr2_helper.go | 1 + core/internal/features/ocr2/features_ocr2_test.go | 1 + go.md | 2 +- tools/bin/go_core_tests | 6 +++++- 4 files changed, 8 insertions(+), 2 deletions(-) diff --git a/core/internal/features/ocr2/features_ocr2_helper.go b/core/internal/features/ocr2/features_ocr2_helper.go index 1fde8778990..75634daaeb7 100644 --- a/core/internal/features/ocr2/features_ocr2_helper.go +++ b/core/internal/features/ocr2/features_ocr2_helper.go @@ -276,6 +276,7 @@ name = "bootstrap" relay = "evm" schemaVersion = 1 contractID = "%s" +contractConfigTrackerPollInterval = "1s" [relayConfig] chainID = 1337 fromBlock = %d diff --git a/core/internal/features/ocr2/features_ocr2_test.go b/core/internal/features/ocr2/features_ocr2_test.go index 249d9cd8a2e..f546d3b567a 100644 --- a/core/internal/features/ocr2/features_ocr2_test.go +++ b/core/internal/features/ocr2/features_ocr2_test.go @@ -88,6 +88,7 @@ relay = "evm" schemaVersion = 1 forwardingAllowed = true contractID = "%s" +contractConfigTrackerPollInterval = "1s" [relayConfig] chainID = 1337 `, ocrContractAddress) diff --git a/go.md b/go.md index fff7fc8ef2a..ef3b4a3b8a7 100644 --- a/go.md +++ b/go.md @@ -671,7 +671,7 @@ flowchart LR click tdh2/go/tdh2 href "https://github.com/smartcontractkit/tdh2" testrig --> testrig/tools/test click testrig href "https://github.com/smartcontractkit/testrig" - testrig/tools/test + testrig/tools/test --> testrig click testrig/tools/test href "https://github.com/smartcontractkit/testrig" wsrpc click wsrpc href "https://github.com/smartcontractkit/wsrpc" diff --git a/tools/bin/go_core_tests b/tools/bin/go_core_tests index f2ad773f820..762e2c814a4 100755 --- a/tools/bin/go_core_tests +++ b/tools/bin/go_core_tests @@ -41,11 +41,15 @@ echo "" # For matching `go test` output - use --format='standard-quiet' and --hide-summary=skipped # For matching `go test -v` output - use only --format='standard-verbose' +# Slowest packages first. `go test` starts packages in command-line order, so listing these first stops the longest +# ones from starting late and setting the wall clock. Packages already listed are not run twice. +SLOW_PACKAGES="./core/services/ocr2/plugins/llo ./core/internal/features/ocr2 ./core/cmd" + gotestsum \ --format='standard-quiet' \ --hide-summary=skipped \ $RERUN_FLAGS \ - --packages='./...' \ + --packages="$SLOW_PACKAGES ./..." \ --jsonfile "$OUTPUT_FILE" \ --post-run-command "sh -c \"echo; echo 'Slowest tests'; echo '----------------------------------------------'; echo; gotestsum tool slowest --num 20 --jsonfile ${OUTPUT_FILE}\"" \ "$JUNIT_FLAG" \ From 35911e745ff678ecd43bdff46f7b0626e1445794 Mon Sep 17 00:00:00 2001 From: Adam Hamrick Date: Wed, 11 Nov 2026 08:23:48 -0500 Subject: [PATCH 03/10] faster tests --- core/cmd/shell_local_test.go | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/core/cmd/shell_local_test.go b/core/cmd/shell_local_test.go index 6488cd1c82d..e0ed32a4c38 100644 --- a/core/cmd/shell_local_test.go +++ b/core/cmd/shell_local_test.go @@ -5,6 +5,7 @@ import ( "errors" "flag" "math/big" + "net" "net/url" "os" "strconv" @@ -20,6 +21,7 @@ import ( "github.com/stretchr/testify/require" "github.com/urfave/cli" "go.uber.org/zap/zapcore" + "google.golang.org/grpc" commonkeystore "github.com/smartcontractkit/chainlink-common/keystore" "github.com/smartcontractkit/chainlink-common/pkg/beholder" @@ -599,6 +601,20 @@ func TestShell_BeforeNode(t *testing.T) { } } +// startFakeOTLPEndpoint starts a gRPC server with no OTLP services and returns its address. Exports get a +// non-retryable Unimplemented reply. With nothing listening, Beholder's final metrics flush on close retries +// "connection refused" for 10 s. +func startFakeOTLPEndpoint(t *testing.T) string { + t.Helper() + var lc net.ListenConfig + lis, err := lc.Listen(t.Context(), "tcp", "127.0.0.1:0") + require.NoError(t, err) + srv := grpc.NewServer() + go func() { _ = srv.Serve(lis) }() + t.Cleanup(srv.Stop) + return lis.Addr().String() +} + func TestShell_BeholderLifecycle(t *testing.T) { testutils.SkipShortDB(t) rawDBURL, ok := os.LookupEnv("CL_DATABASE_URL") @@ -654,7 +670,7 @@ func TestShell_BeholderLifecycle(t *testing.T) { shell, c := newShell(t, func(c *chainlink.Config, s *chainlink.Secrets) { trueVal := true c.Telemetry.Enabled = &trueVal - endpoint := "localhost:4317" + endpoint := startFakeOTLPEndpoint(t) c.Telemetry.Endpoint = &endpoint c.Telemetry.InsecureConnection = &trueVal }, nil) @@ -676,7 +692,7 @@ func TestShell_BeholderLifecycle(t *testing.T) { shell, c := newShell(t, func(c *chainlink.Config, s *chainlink.Secrets) { trueVal := true c.Telemetry.Enabled = &trueVal - endpoint := "localhost:4317" + endpoint := startFakeOTLPEndpoint(t) c.Telemetry.Endpoint = &endpoint c.Telemetry.InsecureConnection = &trueVal c.Telemetry.LogStreamingEnabled = &trueVal @@ -694,7 +710,7 @@ func TestShell_BeholderLifecycle(t *testing.T) { shell, c := newShell(t, func(c *chainlink.Config, s *chainlink.Secrets) { trueVal := true c.Telemetry.Enabled = &trueVal - endpoint := "localhost:4317" + endpoint := startFakeOTLPEndpoint(t) c.Telemetry.Endpoint = &endpoint c.Telemetry.InsecureConnection = &trueVal c.Telemetry.LogStreamingEnabled = &trueVal From c5235d305f104ce9aa3ef1fdd35c8ea9daec3536 Mon Sep 17 00:00:00 2001 From: Adam Hamrick Date: Wed, 11 Nov 2026 08:23:49 -0500 Subject: [PATCH 04/10] reduce sleeps --- .../remote/trigger_registration_load_test.go | 4 +++- core/internal/testutils/pgtest/txdb_test.go | 5 ++-- .../gateway/network/httpclient_test.go | 23 ++++++++++++------- .../chip_ingress_batch_client_test.go | 4 ++-- core/services/synchronization/helpers_test.go | 8 +++++++ 5 files changed, 31 insertions(+), 13 deletions(-) diff --git a/core/capabilities/remote/trigger_registration_load_test.go b/core/capabilities/remote/trigger_registration_load_test.go index 7a92c0e5b3f..d9f5be9bc62 100644 --- a/core/capabilities/remote/trigger_registration_load_test.go +++ b/core/capabilities/remote/trigger_registration_load_test.go @@ -350,7 +350,9 @@ func TestRegistrationCheckTrafficVolume(t *testing.T) { t.Parallel() synctest.Test(t, func(t *testing.T) { ctx := t.Context() - lggr := logger.Test(t) + // The publisher logs every registration at debug (~43 MB across all + // cases) and this test only asserts on dispatcher counts. + lggr := logger.Nop() dispatcher := newCountingDispatcher() capDonMembers := generatePeers(t, tc.capDonSize) diff --git a/core/internal/testutils/pgtest/txdb_test.go b/core/internal/testutils/pgtest/txdb_test.go index 34f8f68fdb6..af84fd3cc5d 100644 --- a/core/internal/testutils/pgtest/txdb_test.go +++ b/core/internal/testutils/pgtest/txdb_test.go @@ -56,8 +56,9 @@ func TestTxDBDriver(t *testing.T) { cancel() // BeginTx spawns separate goroutine that rollbacks the tx and tries to close underlying connection, unless // db driver says that connection is still active. - // This approach is not ideal, but there is no better way to wait for independent goroutine to complete - time.Sleep(time.Second * 10) + // This approach is not ideal, but there is no better way to wait for independent goroutine to complete. + // The goroutine runs as soon as the context is cancelled, so a second is ample. + time.Sleep(time.Second) ensureValuesPresent(t, db) }) } diff --git a/core/services/gateway/network/httpclient_test.go b/core/services/gateway/network/httpclient_test.go index c6620853e8a..04d46ea55ca 100644 --- a/core/services/gateway/network/httpclient_test.go +++ b/core/services/gateway/network/httpclient_test.go @@ -90,10 +90,12 @@ func TestHTTPClient_Send(t *testing.T) { name: "context canceled due to timeout passed in request", setupServer: func() *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - time.Sleep(10 * time.Second) - w.WriteHeader(http.StatusOK) - _, err2 := w.Write([]byte("success")) - assert.NoError(t, err2) + // Hold the response until the client gives up. A fixed sleep would + // make server.Close wait for the full duration. + select { + case <-r.Context().Done(): + case <-time.After(10 * time.Second): + } })) }, request: HTTPRequest{ @@ -110,10 +112,12 @@ func TestHTTPClient_Send(t *testing.T) { name: "context canceled due to default timeout", setupServer: func() *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - time.Sleep(10 * time.Second) - w.WriteHeader(http.StatusOK) - _, err2 := w.Write([]byte("success")) - assert.NoError(t, err2) + // Hold the response until the client gives up. A fixed sleep would + // make server.Close wait for the full duration. + select { + case <-r.Context().Done(): + case <-time.After(10 * time.Second): + } })) }, request: HTTPRequest{ @@ -122,6 +126,9 @@ func TestHTTPClient_Send(t *testing.T) { Headers: map[string]string{}, Body: nil, }, + configOption: func(hc *HTTPClientConfig) { + hc.DefaultTimeout = 200 * time.Millisecond + }, expectedError: context.DeadlineExceeded, }, { diff --git a/core/services/synchronization/chip_ingress_batch_client_test.go b/core/services/synchronization/chip_ingress_batch_client_test.go index 8aad74bef7c..8fce29e949b 100644 --- a/core/services/synchronization/chip_ingress_batch_client_test.go +++ b/core/services/synchronization/chip_ingress_batch_client_test.go @@ -313,7 +313,7 @@ func TestChipIngressBatchClient_HealthMonitoring(t *testing.T) { chipClient := chipingressmocks.NewClient(t) sendInterval := time.Nanosecond - chipIngressClient := synchronization.NewTestChipIngressBatchClient(t, chipClient, false, sendInterval) + chipIngressClient := synchronization.NewTestChipIngressBatchClientWithHealthInterval(t, chipClient, false, sendInterval, 50*time.Millisecond) // Mock Ping to succeed initially var pingCallCount atomic.Uint32 @@ -339,7 +339,7 @@ func TestChipIngressBatchClient_HealthMonitoring_PingFailure(t *testing.T) { chipClient := chipingressmocks.NewClient(t) sendInterval := time.Nanosecond - chipIngressClient := synchronization.NewTestChipIngressBatchClient(t, chipClient, false, sendInterval) + chipIngressClient := synchronization.NewTestChipIngressBatchClientWithHealthInterval(t, chipClient, false, sendInterval, 50*time.Millisecond) // Mock Ping to fail var pingCallCount atomic.Uint32 diff --git a/core/services/synchronization/helpers_test.go b/core/services/synchronization/helpers_test.go index 598ce4f31a9..5fa7f9d614d 100644 --- a/core/services/synchronization/helpers_test.go +++ b/core/services/synchronization/helpers_test.go @@ -30,3 +30,11 @@ func NewTestTelemetryIngressBatchClient(t *testing.T, url *url.URL, serverPubKey func NewTestChipIngressBatchClient(t *testing.T, chipClient chipingress.Client, logging bool, sendInterval time.Duration) ChipIngressService { return NewChipIngressBatchClient(chipClient, logging, logger.TestLogger(t), 100, 50, sendInterval, time.Second) } + +// NewTestChipIngressBatchClientWithHealthInterval is like NewTestChipIngressBatchClient but pings the +// connection every healthInterval instead of the 5s default. +func NewTestChipIngressBatchClientWithHealthInterval(t *testing.T, chipClient chipingress.Client, logging bool, sendInterval, healthInterval time.Duration) ChipIngressService { + c := NewTestChipIngressBatchClient(t, chipClient, logging, sendInterval) + c.(*chipIngressBatchClient).healthCheckInterval = healthInterval + return c +} From 4c875201192fbe59b7e60b5f011a3c872319300c Mon Sep 17 00:00:00 2001 From: Adam Hamrick Date: Wed, 11 Nov 2026 08:23:49 -0500 Subject: [PATCH 05/10] test: cut fixed waits in llo aggregation test, fix syncer v2 retry flake llo aggregation_fault_tolerance: the admits case now stops once both channels have reported instead of sitting out a fixed 15s window; the withholds case window is 10s (was 15s). syncer/v2 Test_StartReconciliation_RetriesWithBackoffV2: wait for >= 3 handler calls (2 failures + success) instead of exactly 1 event, which was only true for ~200ms and was missed under load. Co-Authored-By: Claude Sonnet 5.5 --- .../ocr2/plugins/llo/integration_test.go | 28 +++++++++++++------ .../syncer/v2/workflow_syncer_v2_test.go | 21 +++++++++----- 2 files changed, 33 insertions(+), 16 deletions(-) diff --git a/core/services/ocr2/plugins/llo/integration_test.go b/core/services/ocr2/plugins/llo/integration_test.go index 4f7a4b784b2..af7827a2aed 100644 --- a/core/services/ocr2/plugins/llo/integration_test.go +++ b/core/services/ocr2/plugins/llo/integration_test.go @@ -3550,6 +3550,20 @@ pluginVersion = "v31"`, serverURL, serverPubKey, donID, configStoreAddress, from return seen } + if expectPartialReports { + // Both channels must report. Stop as soon as both have been seen instead + // of sitting out a fixed window. + seen := make(map[uint32]bool) + require.Eventually(t, func() bool { + for ch := range collectChannels(2 * time.Second) { + seen[ch] = true + } + return seen[channelFull] && seen[channelPartial] + }, reportTimeout, 100*time.Millisecond, + "fully observed and under-observed channels should both report when the contribution floor is met") + return + } + // The fully observed channel must report regardless of the floor. This also // establishes that the DON has reached a reporting steady state before // judging the under-observed channel. @@ -3557,16 +3571,12 @@ pluginVersion = "v31"`, serverURL, serverPubKey, donID, configStoreAddress, from return collectChannels(2 * time.Second)[channelFull] }, reportTimeout, 100*time.Millisecond, "fully observed channel should produce reports") - // Now judge the under-observed channel over a window that spans many rounds. - seen := collectChannels(15 * time.Second) + // Now judge the under-observed channel over a window that spans many rounds + // (~20 at the 500ms round time and 1s min report interval). + seen := collectChannels(10 * time.Second) require.True(t, seen[channelFull], "fully observed channel should keep reporting") - if expectPartialReports { - require.True(t, seen[channelPartial], - "under-observed channel should report when the contribution floor is met") - } else { - require.False(t, seen[channelPartial], - "under-observed channel should not report when it cannot meet the contribution floor") - } + require.False(t, seen[channelPartial], + "under-observed channel should not report when it cannot meet the contribution floor") } // TestIntegration_LLO_v31_blob_catchup covers the v31 blob path for an oracle diff --git a/core/services/workflows/syncer/v2/workflow_syncer_v2_test.go b/core/services/workflows/syncer/v2/workflow_syncer_v2_test.go index e8b0d41be16..54d49bb158b 100644 --- a/core/services/workflows/syncer/v2/workflow_syncer_v2_test.go +++ b/core/services/workflows/syncer/v2/workflow_syncer_v2_test.go @@ -11,6 +11,7 @@ import ( "fmt" "math/big" "strconv" + "sync/atomic" "testing" "time" @@ -653,10 +654,11 @@ func Test_StartReconciliation_RetriesWithBackoffV2(t *testing.T) { workflow.ID = workflowID upsertWorkflowV2(t, backendTH, wfRegistryC, workflow) - var retryCount int + // The handler fails its first two calls, then succeeds. + var retryCount atomic.Int32 testEventHandler := newTestEvtHandler(func() error { - if retryCount <= 1 { - retryCount++ + if retryCount.Load() <= 1 { + retryCount.Add(1) return errors.New("error handling event") } return nil @@ -690,14 +692,19 @@ func Test_StartReconciliation_RetriesWithBackoffV2(t *testing.T) { servicetest.Run(t, worker) + // Every Handle call is recorded, including failed ones, and reconciliation + // keeps re-dispatching the event after it succeeds. Wait for the two failures + // plus the successful attempt; do not wait for an exact count, because a slow + // poll can miss the moment it is reached. require.Eventually(t, func() bool { - return len(testEventHandler.GetEvents()) == 1 + return len(testEventHandler.GetEvents()) >= 3 }, 30*time.Second, 100*time.Millisecond) - event := testEventHandler.GetEvents()[0] - assert.Equal(t, WorkflowActivated, event.Name) + for _, event := range testEventHandler.GetEvents() { + assert.Equal(t, WorkflowActivated, event.Name) + } - assert.Equal(t, 1, retryCount) + assert.Equal(t, int32(2), retryCount.Load()) } // Links owner account to Workflow Registry contract From ed31e0d338f2878dfb0d071a439378f5a03afbc9 Mon Sep 17 00:00:00 2001 From: Adam Hamrick Date: Wed, 11 Nov 2026 08:23:49 -0500 Subject: [PATCH 06/10] test: shorten two slow pg and ccip transmitter tests TestLockedDB_TwoInstances waits 3 renewal intervals instead of the full 10s lease. The ccip/ocrimpls transmitter tests mine and sample heads every 100ms instead of 1-2s (15s -> 1.8s per subtest). Co-Authored-By: Claude Sonnet 5.5 --- .../ccip/ocrimpls/contract_transmitter_test.go | 11 ++++++++--- core/services/pg/locked_db_test.go | 5 ++++- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/core/capabilities/ccip/ocrimpls/contract_transmitter_test.go b/core/capabilities/ccip/ocrimpls/contract_transmitter_test.go index ba811f7de67..e57fcfb2868 100644 --- a/core/capabilities/ccip/ocrimpls/contract_transmitter_test.go +++ b/core/capabilities/ccip/ocrimpls/contract_transmitter_test.go @@ -56,6 +56,11 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" ) +// blockTick is how often the tests mine a block while polling, and how often the +// head tracker samples heads. The tx confirmer needs several new blocks before it +// writes a receipt, so this sets how long those tests take. +const blockTick = 100 * time.Millisecond + func Test_ContractTransmitter_TransmitWithoutSignatures(t *testing.T) { t.Parallel() type testCase struct { @@ -159,7 +164,7 @@ func testTransmitter( receipt, err := uni.simClient.TransactionReceipt(ctx, common.BytesToHash(txHash)) require.NoError(c, err) txStatus = receipt.Status - }, testutils.WaitTimeout(t), 1*time.Second) + }, testutils.WaitTimeout(t), blockTick) // wait for receipt to be written to the db require.EventuallyWithT(t, func(c *assert.CollectT) { @@ -168,7 +173,7 @@ func testTransmitter( err := uni.db.GetContext(ctx, &count, `SELECT count(*) as cnt FROM evm.receipts LIMIT 1`) require.NoError(c, err) require.Equal(c, uint32(1), count) - }, testutils.WaitTimeout(t), 2*time.Second) + }, testutils.WaitTimeout(t), blockTick) require.Equal(t, uint64(1), txStatus, "tx status should be success") @@ -716,7 +721,7 @@ func (t *TestHeadTrackerConfig) MaxBufferSize() uint32 { // SamplingInterval implements config.HeadTracker. func (t *TestHeadTrackerConfig) SamplingInterval() time.Duration { - return 1 * time.Second + return blockTick } func (t *TestHeadTrackerConfig) PersistenceEnabled() bool { diff --git a/core/services/pg/locked_db_test.go b/core/services/pg/locked_db_test.go index fdcab61d5b5..a7ed074c728 100644 --- a/core/services/pg/locked_db_test.go +++ b/core/services/pg/locked_db_test.go @@ -89,7 +89,10 @@ func TestLockedDB_TwoInstances(t *testing.T) { // matters here. appID := config.AppID() appID[0] ^= 0xff - ctx, cancel := context.WithTimeout(t.Context(), config.Database().Lock().LeaseDuration()) + // The first instance renews its lease every second, so the second never gets + // it. A few renewal periods are enough to show that; waiting out the full + // lease duration only costs time. + ctx, cancel := context.WithTimeout(t.Context(), 3*config.Database().Lock().LeaseRefreshInterval()) defer cancel() ldb2 := pg.NewLockedDB(appID, config.Database(), config.Database().Lock(), lggr) err = ldb2.Open(ctx) From 1fc8bc94af01241e52d46b9cc626cce8586bba5c Mon Sep 17 00:00:00 2001 From: Adam Hamrick Date: Wed, 11 Nov 2026 08:23:50 -0500 Subject: [PATCH 07/10] test: batch row inserts in the slow pipeline and job ORM tests Test_PipelineORM_DeleteRunsOlderThan created a cron job per run and ran StoreRun for each of 2000 runs. One job now owns all runs and the rest are inserted in one InsertFinishedRuns call (15s -> 0.24s). Test_FindPipelineRunIDsByJobID inserted 4600 runs one at a time. A new helper inserts them in one ordered statement so ids still interleave across jobs (14.6s -> 0.3s). Co-Authored-By: Claude Sonnet 5.5 --- core/services/job/job_orm_test.go | 35 ++++++++++-- core/services/pipeline/orm_test.go | 90 ++++++++++++++++++++---------- 2 files changed, 92 insertions(+), 33 deletions(-) diff --git a/core/services/job/job_orm_test.go b/core/services/job/job_orm_test.go index c1109ca4aa4..1bde07e77b7 100644 --- a/core/services/job/job_orm_test.go +++ b/core/services/job/job_orm_test.go @@ -4,11 +4,13 @@ import ( "context" "database/sql" "fmt" + "slices" "testing" "time" "github.com/ethereum/go-ethereum/common" "github.com/google/uuid" + "github.com/jmoiron/sqlx" "github.com/lib/pq" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -1563,13 +1565,16 @@ func Test_FindPipelineRunIDsByJobID(t *testing.T) { jobs[j] = jb } + // Runs are spread across the jobs in turn so their ids interleave. + toInsert := make([]job.Job, 0, 2500) for i, j := 0, 0; i < 2500; i++ { - mustInsertPipelineRun(t, pipelineORM, jobs[j]) + toInsert = append(toInsert, jobs[j]) j++ if j == len(jobs)-1 { j = 0 } } + mustInsertPipelineRuns(t, db, toInsert) t.Run("with no pipeline runs", func(t *testing.T) { ctx := t.Context() @@ -1609,9 +1614,7 @@ func Test_FindPipelineRunIDsByJobID(t *testing.T) { assert.Equal(t, int64(67*(len(jobs)-1)), runIDs[12]-runIDs[79]) }) - for range 2100 { - mustInsertPipelineRun(t, pipelineORM, jb) - } + mustInsertPipelineRuns(t, db, slices.Repeat([]job.Job{jb}, 2100)) // There is a COUNT query which doesn't run unless the query for the most recent 1000 rows // returns empty. This can happen if the job id being requested hasn't run in a while, @@ -1878,6 +1881,30 @@ func Test_CountPipelineRunsByJobID(t *testing.T) { }) } +// mustInsertPipelineRuns inserts one running pipeline run per entry of jobs in a single +// statement, so ids follow the order of jobs. Use it instead of looping over +// mustInsertPipelineRun when a test needs thousands of rows. +func mustInsertPipelineRuns(t *testing.T, db *sqlx.DB, jobs []job.Job) { + t.Helper() + + now := time.Now() + runs := make([]pipeline.Run, len(jobs)) + for i, j := range jobs { + runs[i] = pipeline.Run{ + PipelineSpecID: j.PipelineSpecID, + PruningKey: j.ID, + State: pipeline.RunStatusRunning, + Outputs: jsonserializable.JSONSerializable{Valid: false}, + AllErrors: pipeline.RunErrors{}, + CreatedAt: now.Add(time.Duration(i) * time.Microsecond), + FinishedAt: null.Time{}, + } + } + _, err := db.NamedExecContext(t.Context(), `INSERT INTO pipeline_runs (pipeline_spec_id, pruning_key, meta, all_errors, fatal_errors, inputs, outputs, created_at, finished_at, state) + VALUES (:pipeline_spec_id, :pruning_key, :meta, :all_errors, :fatal_errors, :inputs, :outputs, :created_at, :finished_at, :state)`, runs) + require.NoError(t, err) +} + func mustInsertPipelineRun(t *testing.T, orm pipeline.ORM, j job.Job) pipeline.Run { t.Helper() ctx := t.Context() diff --git a/core/services/pipeline/orm_test.go b/core/services/pipeline/orm_test.go index da59a93162e..ed3aeb61c12 100644 --- a/core/services/pipeline/orm_test.go +++ b/core/services/pipeline/orm_test.go @@ -568,44 +568,76 @@ func Test_PipelineORM_DeleteRun(t *testing.T) { func Test_PipelineORM_DeleteRunsOlderThan(t *testing.T) { ctx := t.Context() - _, orm, jorm := setupHeavyORM(t) + db, orm, jorm := setupHeavyORM(t) - var runsIDs []int64 + const nRuns = 2000 // more than one delete batch - for i := 1; i <= 2000; i++ { - run := mustInsertAsyncRun(t, orm, jorm) + // One job owns every run. Creating a job per run dominated the test's time, + // and MaxSuccessfulRuns (123456) is far above nRuns, so nothing is pruned. + first := mustInsertAsyncRun(t, orm, jorm) - now := time.Now() + now := time.Now() + finishedAt := null.TimeFrom(now.Add(-1 * time.Second)) + outputs := jsonserializable.JSONSerializable{Val: 1, Valid: true} + allErrors := pipeline.RunErrors{null.StringFrom("SOMETHING")} - run.PipelineTaskRuns = []pipeline.TaskRun{ - // finished task - { - ID: uuid.New(), - PipelineRunID: run.ID, - Type: "median", - DotID: "answer2", - Output: jsonserializable.JSONSerializable{Val: 1, Valid: true}, - CreatedAt: now, - FinishedAt: null.TimeFrom(now.Add(-1 * time.Second)), + // finish the run created above through the normal path + first.PipelineTaskRuns = []pipeline.TaskRun{ + { + ID: uuid.New(), + PipelineRunID: first.ID, + Type: "median", + DotID: "answer2", + Output: outputs, + CreatedAt: now, + FinishedAt: finishedAt, + }, + } + first.State = pipeline.RunStatusCompleted + first.FinishedAt = finishedAt + first.Outputs = outputs + first.AllErrors = allErrors + restart, err := orm.StoreRun(ctx, first) + require.NoError(t, err) + // no new data, so we don't need a restart + assert.False(t, restart) + + // the rest are inserted already finished, in one batch + finished := make([]*pipeline.Run, 0, nRuns-1) + for range nRuns - 1 { + finished = append(finished, &pipeline.Run{ + PipelineSpecID: first.PipelineSpecID, + PruningKey: first.PruningKey, + State: pipeline.RunStatusCompleted, + Outputs: outputs, + AllErrors: allErrors, + CreatedAt: now, + FinishedAt: finishedAt, + PipelineTaskRuns: []pipeline.TaskRun{ + { + ID: uuid.New(), + Type: "median", + DotID: "answer2", + Output: outputs, + CreatedAt: now, + FinishedAt: finishedAt, + }, }, - } - run.State = pipeline.RunStatusCompleted - run.FinishedAt = null.TimeFrom(now.Add(-1 * time.Second)) - run.Outputs = jsonserializable.JSONSerializable{Val: 1, Valid: true} - run.AllErrors = pipeline.RunErrors{null.StringFrom("SOMETHING")} - - restart, err := orm.StoreRun(ctx, run) - require.NoError(t, err) - // no new data, so we don't need a restart - assert.False(t, restart) - - runsIDs = append(runsIDs, run.ID) + }) } + require.NoError(t, orm.InsertFinishedRuns(ctx, finished, false)) + + var runIDs []int64 + require.NoError(t, db.SelectContext(ctx, &runIDs, `SELECT id FROM pipeline_runs WHERE pruning_key = $1`, first.PruningKey)) + require.Len(t, runIDs, nRuns) - err := orm.DeleteRunsOlderThan(t.Context(), 1*time.Second) + err = orm.DeleteRunsOlderThan(ctx, 1*time.Second) require.NoError(t, err) - for _, runID := range runsIDs { + var remaining int + require.NoError(t, db.GetContext(ctx, &remaining, `SELECT count(*) FROM pipeline_runs WHERE pruning_key = $1`, first.PruningKey)) + assert.Zero(t, remaining) + for _, runID := range []int64{runIDs[0], runIDs[len(runIDs)-1]} { _, err := orm.FindRun(ctx, runID) require.Error(t, err, "not found") } From 99a632c5e527effae3324816c374b1f1604532ad Mon Sep 17 00:00:00 2001 From: Adam Hamrick Date: Wed, 11 Nov 2026 08:23:50 -0500 Subject: [PATCH 08/10] test: default heavy integration tests to Info logging llo nodes ran at Debug with P2P tracing and verbose pipeline/Mercury logging, plus an in-memory observer nothing read: ~190 MB of output per package run. They now log at Info; LLO_TEST_DEBUG=1 turns the old behaviour back on and the unused observer is gone. cltest.NewApplicationWithConfig built its default logger at Debug regardless of config. It now follows the config level; CL_TEST_DEBUG_LOGS=1 restores Debug. Measured: llo output 192 MB -> 45 MB, CPU -14%; features/ocr2 output 35 MB -> 3.1 MB, CPU -12%. Wall time per package is unchanged. Co-Authored-By: Claude Sonnet 5.5 --- core/internal/cltest/cltest.go | 15 +++++++- .../ocr2/plugins/llo/don_bench_test.go | 2 +- .../services/ocr2/plugins/llo/helpers_test.go | 38 +++++++++++++------ .../llo/history_backfill_integration_test.go | 2 +- .../ocr2/plugins/llo/integration_test.go | 26 ++++++------- 5 files changed, 55 insertions(+), 28 deletions(-) diff --git a/core/internal/cltest/cltest.go b/core/internal/cltest/cltest.go index 85a3d686857..77619fe5621 100644 --- a/core/internal/cltest/cltest.go +++ b/core/internal/cltest/cltest.go @@ -36,6 +36,7 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" + "go.uber.org/zap/zapcore" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting/types" "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types" @@ -252,6 +253,18 @@ func NewApplicationWithConfigAndKey(t testing.TB, c chainlink.GeneralConfig, fla } // NewApplicationWithConfig creates a New TestApplication with specified test config. +// appLogLevel is the level for the logger of an application that a test did not +// give one. It follows the config (Info unless the test sets [Log] Level), not +// Debug: the EVM services alone print thousands of debug lines per second, and each +// line costs encoding, a stack lookup and the test output lock. Set +// CL_TEST_DEBUG_LOGS=1 to get debug output back when chasing a failure. +func appLogLevel(cfg chainlink.GeneralConfig) zapcore.Level { + if os.Getenv("CL_TEST_DEBUG_LOGS") != "" { + return zapcore.DebugLevel + } + return cfg.Log().Level() +} + // This should only be used in full integration tests. For controller tests, see NewApplicationEVMDisabled. func NewApplicationWithConfig(t testing.TB, cfg chainlink.GeneralConfig, flagsAndDeps ...any) *TestApplication { t.Helper() @@ -268,7 +281,7 @@ func NewApplicationWithConfig(t testing.TB, cfg chainlink.GeneralConfig, flagsAn } } if lggr == nil { - lggr = logger.TestLogger(t) + lggr = logger.TestLogger(t, appLogLevel(cfg)) } var auditLogger audit.Logger diff --git a/core/services/ocr2/plugins/llo/don_bench_test.go b/core/services/ocr2/plugins/llo/don_bench_test.go index 6d9a399694c..33f0219427d 100644 --- a/core/services/ocr2/plugins/llo/don_bench_test.go +++ b/core/services/ocr2/plugins/llo/don_bench_test.go @@ -276,7 +276,7 @@ func runDONBench(t *testing.T, version lloconfig.PluginVersion, salt int64, donI bootstrapCSAKey := csakey.MustNewV2XXXTestingOnly(big.NewInt(salt - 1)) bootstrapNodePort := freeport.GetOne(t) - appBootstrap, bootstrapPeerID, _, bootstrapKb, _ := setupNode(t, bootstrapNodePort, fmt.Sprintf("bootstrap_llo_bench_%s", version), backend, bootstrapCSAKey, func(c *chainlink.Config) { + appBootstrap, bootstrapPeerID, _, bootstrapKb := setupNode(t, bootstrapNodePort, fmt.Sprintf("bootstrap_llo_bench_%s", version), backend, bootstrapCSAKey, func(c *chainlink.Config) { c.Log.Level = new(logLevel) onP2PHost(c) }) diff --git a/core/services/ocr2/plugins/llo/helpers_test.go b/core/services/ocr2/plugins/llo/helpers_test.go index 61f1a79b59b..71e14c5fe68 100644 --- a/core/services/ocr2/plugins/llo/helpers_test.go +++ b/core/services/ocr2/plugins/llo/helpers_test.go @@ -14,6 +14,7 @@ import ( "net/http" "net/http/httptest" "net/url" + "os" "reflect" "sync/atomic" "testing" @@ -24,7 +25,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/zap/zapcore" - "go.uber.org/zap/zaptest/observer" "google.golang.org/grpc" "google.golang.org/grpc/keepalive" @@ -52,6 +52,21 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/utils/testutils/heavyweight" ) +// The nodes in these tests print a lot: with debug logs, P2P tracing and verbose +// pipeline and Mercury logging on, one package run writes ~200 MB of JSON, and +// every line costs encoding, a stack lookup and the test output lock. That CPU +// competes with the rest of the suite, so they are off by default. Set +// LLO_TEST_DEBUG=1 when debugging a failure to turn all of them back on. +var ( + debugLogging = os.Getenv("LLO_TEST_DEBUG") != "" + testLogLevel = func() zapcore.Level { + if debugLogging { + return zapcore.DebugLevel + } + return zapcore.InfoLevel + }() +) + type mercuryServer struct { rpc.UnimplementedTransmitterServer csaSigner crypto.Signer @@ -120,7 +135,6 @@ type Node struct { App chainlink.Application ClientPubKey credentials.StaticSizedPublicKey KeyBundle ocr2key.KeyBundle - ObservedLogs *observer.ObservedLogs } func (node *Node) AddStreamJob(t *testing.T, spec string) (id int32) { @@ -160,9 +174,9 @@ func setupNode( csaKey csakey.KeyV2, f func(*chainlink.Config), deps ...any, -) (app chainlink.Application, peerID string, clientPubKey credentials.StaticSizedPublicKey, ocr2kb ocr2key.KeyBundle, observedLogs *observer.ObservedLogs) { - app, peerID, clientPubKey, ocr2kb, observedLogs, _ = setupRestartableNode(t, port, dbName, backend, csaKey, f, deps...) - return app, peerID, clientPubKey, ocr2kb, observedLogs +) (app chainlink.Application, peerID string, clientPubKey credentials.StaticSizedPublicKey, ocr2kb ocr2key.KeyBundle) { + app, peerID, clientPubKey, ocr2kb, _ = setupRestartableNode(t, port, dbName, backend, csaKey, f, deps...) + return app, peerID, clientPubKey, ocr2kb } // setupRestartableNode is setupNode plus a restart hook. restart stops the @@ -178,7 +192,7 @@ func setupRestartableNode( csaKey csakey.KeyV2, f func(*chainlink.Config), deps ...any, -) (app chainlink.Application, peerID string, clientPubKey credentials.StaticSizedPublicKey, ocr2kb ocr2key.KeyBundle, observedLogs *observer.ObservedLogs, restart func(t *testing.T, whileDown func()) chainlink.Application) { +) (app chainlink.Application, peerID string, clientPubKey credentials.StaticSizedPublicKey, ocr2kb ocr2key.KeyBundle, restart func(t *testing.T, whileDown func()) chainlink.Application) { k := big.NewInt(int64(port)) // keys unique to port p2pKey := p2pkey.MustNewV2XXXTestingOnly(k) rdr := keystest.NewRandReaderFromSeed(int64(port)) @@ -195,7 +209,7 @@ func setupRestartableNode( // [JobPipeline] c.JobPipeline.MaxSuccessfulRuns = new(uint64(0)) - c.JobPipeline.VerboseLogging = new(true) + c.JobPipeline.VerboseLogging = new(debugLogging) // [Feature] c.Feature.UICSAKeys = new(true) @@ -214,7 +228,7 @@ func setupRestartableNode( // [P2P] c.P2P.PeerID = new(p2pKey.PeerID()) - c.P2P.TraceLogging = new(true) + c.P2P.TraceLogging = new(debugLogging) // Required for OCR3.1 (llo/v31) networking (the "2" endpoint factory needs // the experimental ragep2p host). Backward-compatible with OCR3.0. c.P2P.EnableExperimentalRageP2P = new(true) @@ -227,10 +241,10 @@ func setupRestartableNode( c.P2P.V2.DeltaReconcile = commonconfig.MustNewDuration(5 * time.Second) // [Mercury] - c.Mercury.VerboseLogging = new(true) + c.Mercury.VerboseLogging = new(debugLogging) // [Log] - c.Log.Level = new(toml.LogLevel(zapcore.DebugLevel)) // generally speaking we want debug level for logs unless overridden + c.Log.Level = new(toml.LogLevel(testLogLevel)) // tests can override this // [CRE] c.CRE.UseLocalTimeProvider = new(true) @@ -249,7 +263,7 @@ func setupRestartableNode( } }) - lggr, observedLogs := logger.TestLoggerObserved(t, config.Log().Level()) + lggr := logger.TestLogger(t, config.Log().Level()) // newApp builds and starts an application over the config above. Start // registers its own cleanup, which tolerates an application this test // already stopped. @@ -275,7 +289,7 @@ func setupRestartableNode( return current } - return app, p2pKey.PeerID().Raw(), csaKey.StaticSizedPublicKey(), ocr2kb, observedLogs, restart + return app, p2pKey.PeerID().Raw(), csaKey.StaticSizedPublicKey(), ocr2kb, restart } // receiveWithTimeout receives from the packet channel with a timeout. diff --git a/core/services/ocr2/plugins/llo/history_backfill_integration_test.go b/core/services/ocr2/plugins/llo/history_backfill_integration_test.go index c0dc999bd4c..52bfd17e873 100644 --- a/core/services/ocr2/plugins/llo/history_backfill_integration_test.go +++ b/core/services/ocr2/plugins/llo/history_backfill_integration_test.go @@ -152,7 +152,7 @@ func testIntegrationLLOHistoryBackfill(t *testing.T, v31 bool) { bootstrapCSAKey := csakey.MustNewV2XXXTestingOnly(big.NewInt(salt - 1)) bootstrapNodePort := freeport.GetOne(t) - appBootstrap, bootstrapPeerID, _, bootstrapKb, _ := setupNode(t, bootstrapNodePort, "bootstrap_llo_backfill", backend, bootstrapCSAKey, nil) + appBootstrap, bootstrapPeerID, _, bootstrapKb := setupNode(t, bootstrapNodePort, "bootstrap_llo_backfill", backend, bootstrapCSAKey, nil) bootstrapNode := Node{App: appBootstrap, KeyBundle: bootstrapKb} packetCh := make(chan *packet, 100000) diff --git a/core/services/ocr2/plugins/llo/integration_test.go b/core/services/ocr2/plugins/llo/integration_test.go index af7827a2aed..7c38095de4f 100644 --- a/core/services/ocr2/plugins/llo/integration_test.go +++ b/core/services/ocr2/plugins/llo/integration_test.go @@ -571,7 +571,7 @@ func testIntegrationLLOEVMPremiumLegacy(t *testing.T, offchainConfig lloprotocol // Setup bootstrap bootstrapCSAKey := csakey.MustNewV2XXXTestingOnly(big.NewInt(salt - 1)) bootstrapNodePort := freeport.GetOne(t) - appBootstrap, bootstrapPeerID, _, bootstrapKb, _ := setupNode(t, bootstrapNodePort, "bootstrap_llo", backend, bootstrapCSAKey, nil) + appBootstrap, bootstrapPeerID, _, bootstrapKb := setupNode(t, bootstrapNodePort, "bootstrap_llo", backend, bootstrapCSAKey, nil) bootstrapNode := Node{App: appBootstrap, KeyBundle: bootstrapKb} t.Run("using legacy verifier configuration contract, produces reports in v0.3 format", func(t *testing.T) { @@ -811,7 +811,7 @@ func testIntegrationLLOMultiFormats(t *testing.T, offchainConfig lloprotocol.Off // Setup bootstrap bootstrapCSAKey := csakey.MustNewV2XXXTestingOnly(big.NewInt(salt - 1)) bootstrapNodePort := freeport.GetOne(t) - appBootstrap, bootstrapPeerID, _, bootstrapKb, _ := setupNode(t, bootstrapNodePort, "bootstrap_llo", backend, bootstrapCSAKey, nil) + appBootstrap, bootstrapPeerID, _, bootstrapKb := setupNode(t, bootstrapNodePort, "bootstrap_llo", backend, bootstrapCSAKey, nil) bootstrapNode := Node{App: appBootstrap, KeyBundle: bootstrapKb} t.Run("generates reports using multiple formats", func(t *testing.T) { @@ -1600,7 +1600,7 @@ func TestIntegration_LLO_stress_test_V1(t *testing.T) { // Setup bootstrap bootstrapCSAKey := csakey.MustNewV2XXXTestingOnly(big.NewInt(salt - 1)) bootstrapNodePort := freeport.GetOne(t) - appBootstrap, bootstrapPeerID, _, bootstrapKb, _ := setupNode(t, bootstrapNodePort, "bootstrap_llo", backend, bootstrapCSAKey, func(c *chainlink.Config) { + appBootstrap, bootstrapPeerID, _, bootstrapKb := setupNode(t, bootstrapNodePort, "bootstrap_llo", backend, bootstrapCSAKey, func(c *chainlink.Config) { c.Log.Level = new(logLevel) }) bootstrapNode := Node{App: appBootstrap, KeyBundle: bootstrapKb} @@ -1828,7 +1828,7 @@ func TestIntegration_LLO_transmit_errors(t *testing.T) { // Setup bootstrap bootstrapCSAKey := csakey.MustNewV2XXXTestingOnly(big.NewInt(salt - 1)) bootstrapNodePort := freeport.GetOne(t) - appBootstrap, bootstrapPeerID, _, bootstrapKb, _ := setupNode(t, bootstrapNodePort, "bootstrap_llo", backend, bootstrapCSAKey, func(c *chainlink.Config) { + appBootstrap, bootstrapPeerID, _, bootstrapKb := setupNode(t, bootstrapNodePort, "bootstrap_llo", backend, bootstrapCSAKey, func(c *chainlink.Config) { c.Log.Level = new(logLevel) }) bootstrapNode := Node{App: appBootstrap, KeyBundle: bootstrapKb} @@ -2067,7 +2067,7 @@ func testIntegrationLLOBlueGreenLifecycle(t *testing.T, offchainConfig lloprotoc // Setup bootstrap bootstrapCSAKey := csakey.MustNewV2XXXTestingOnly(big.NewInt(salt - 1)) bootstrapNodePort := freeport.GetOne(t) - appBootstrap, bootstrapPeerID, _, bootstrapKb, _ := setupNode(t, bootstrapNodePort, "bootstrap_llo", backend, bootstrapCSAKey, nil) + appBootstrap, bootstrapPeerID, _, bootstrapKb := setupNode(t, bootstrapNodePort, "bootstrap_llo", backend, bootstrapCSAKey, nil) bootstrapNode := Node{App: appBootstrap, KeyBundle: bootstrapKb} t.Run("Blue/Green lifecycle (using JSON report format)", func(t *testing.T) { @@ -2451,7 +2451,7 @@ func testIntegrationLLOChannelMerging(t *testing.T, v31 bool) { // Setup bootstrap bootstrapCSAKey := csakey.MustNewV2XXXTestingOnly(big.NewInt(salt - 1)) bootstrapNodePort := freeport.GetOne(t) - appBootstrap, bootstrapPeerID, _, bootstrapKb, _ := setupNode(t, bootstrapNodePort, "bootstrap_llo", backend, bootstrapCSAKey, nil) + appBootstrap, bootstrapPeerID, _, bootstrapKb := setupNode(t, bootstrapNodePort, "bootstrap_llo", backend, bootstrapCSAKey, nil) bootstrapNode := Node{App: appBootstrap, KeyBundle: bootstrapKb} t.Run("Channel merging lifecycle with owners and adders", func(t *testing.T) { @@ -2991,7 +2991,7 @@ func testIntegrationLLOTombstone(t *testing.T, v31 bool) { bootstrapCSAKey := csakey.MustNewV2XXXTestingOnly(big.NewInt(salt - 1)) bootstrapNodePort := freeport.GetOne(t) - appBootstrap, bootstrapPeerID, _, bootstrapKb, _ := setupNode(t, bootstrapNodePort, "bootstrap_llo_tombstone", backend, bootstrapCSAKey, nil) + appBootstrap, bootstrapPeerID, _, bootstrapKb := setupNode(t, bootstrapNodePort, "bootstrap_llo_tombstone", backend, bootstrapCSAKey, nil) bootstrapNode := Node{App: appBootstrap, KeyBundle: bootstrapKb} packetCh := make(chan *packet, 100000) @@ -3201,7 +3201,7 @@ func TestIntegration_LLO_bridgeConnManagerHappyPath(t *testing.T) { bootstrapCSAKey := csakey.MustNewV2XXXTestingOnly(big.NewInt(salt - 1)) bootstrapNodePort := freeport.GetOne(t) - appBootstrap, bootstrapPeerID, _, bootstrapKb, _ := setupNode(t, bootstrapNodePort, "bootstrap_llo_bridgeconnmanager", backend, bootstrapCSAKey, nil) + appBootstrap, bootstrapPeerID, _, bootstrapKb := setupNode(t, bootstrapNodePort, "bootstrap_llo_bridgeconnmanager", backend, bootstrapCSAKey, nil) bootstrapNode := Node{App: appBootstrap, KeyBundle: bootstrapKb} packetCh := make(chan *packet, 100000) @@ -3304,11 +3304,11 @@ func setupNodes(t *testing.T, nNodes int, backend evmtypes.Backend, clientCSAKey func setupNodesWithRestart(t *testing.T, nNodes int, backend evmtypes.Backend, clientCSAKeys []csakey.KeyV2, f func(*chainlink.Config), deps ...any) (oracles []confighelper.OracleIdentityExtra, nodes []Node, restarts []func(t *testing.T, whileDown func()) chainlink.Application) { ports := freeport.GetN(t, nNodes) for i := range nNodes { - app, peerID, transmitter, kb, observedLogs, restart := setupRestartableNode(t, ports[i], fmt.Sprintf("oracle_streams_%d", i), backend, clientCSAKeys[i], f, deps...) + app, peerID, transmitter, kb, restart := setupRestartableNode(t, ports[i], fmt.Sprintf("oracle_streams_%d", i), backend, clientCSAKeys[i], f, deps...) restarts = append(restarts, restart) nodes = append(nodes, Node{ - app, transmitter, kb, observedLogs, + app, transmitter, kb, }) offchainPublicKey, err := hex.DecodeString(strings.TrimPrefix(kb.OnChainPublicKey(), "0x")) require.NoError(t, err) @@ -3449,7 +3449,7 @@ func testIntegrationLLOAggregationFaultTolerance(t *testing.T, aft uint32, nPart bootstrapCSAKey := csakey.MustNewV2XXXTestingOnly(big.NewInt(salt - 1)) bootstrapNodePort := freeport.GetOne(t) - appBootstrap, bootstrapPeerID, _, bootstrapKb, _ := setupNode(t, bootstrapNodePort, "bootstrap_llo_aft", backend, bootstrapCSAKey, nil) + appBootstrap, bootstrapPeerID, _, bootstrapKb := setupNode(t, bootstrapNodePort, "bootstrap_llo_aft", backend, bootstrapCSAKey, nil) bootstrapNode := Node{App: appBootstrap, KeyBundle: bootstrapKb} packetCh := make(chan *packet, 100000) @@ -3642,7 +3642,7 @@ func testIntegrationLLOV31BlobCatchup(t *testing.T, rejoin bool, salt int64, don bootstrapCSAKey := csakey.MustNewV2XXXTestingOnly(big.NewInt(salt - 1)) bootstrapNodePort := freeport.GetOne(t) - appBootstrap, bootstrapPeerID, _, bootstrapKb, _ := setupNode(t, bootstrapNodePort, "bootstrap_llo_catchup", backend, bootstrapCSAKey, nil) + appBootstrap, bootstrapPeerID, _, bootstrapKb := setupNode(t, bootstrapNodePort, "bootstrap_llo_catchup", backend, bootstrapCSAKey, nil) bootstrapNode := Node{App: appBootstrap, KeyBundle: bootstrapKb} packetCh := make(chan *packet, 100000) @@ -3837,7 +3837,7 @@ func TestIntegration_LLO_v31_restart_resumes(t *testing.T) { bootstrapCSAKey := csakey.MustNewV2XXXTestingOnly(big.NewInt(salt - 1)) bootstrapNodePort := freeport.GetOne(t) - appBootstrap, bootstrapPeerID, _, bootstrapKb, _ := setupNode(t, bootstrapNodePort, "bootstrap_llo_restart", backend, bootstrapCSAKey, nil) + appBootstrap, bootstrapPeerID, _, bootstrapKb := setupNode(t, bootstrapNodePort, "bootstrap_llo_restart", backend, bootstrapCSAKey, nil) bootstrapNode := Node{App: appBootstrap, KeyBundle: bootstrapKb} packetCh := make(chan *packet, 100000) From 665e0369309d4e129c0d8d4f48eae8a3578d4ed2 Mon Sep 17 00:00:00 2001 From: Adam Hamrick Date: Wed, 11 Nov 2026 08:23:50 -0500 Subject: [PATCH 09/10] test: cut fixed waits in launcher, bridges and vrf tests; run slowest llo tests first ccip/launcher: registrysyncer.WithTickInterval(100ms) so the test does not wait out the 12 s sync tick (package 14.7 s -> 2.2 s). bridges: the async upsert test uses a 50 ms interval (package 6.6 s -> 1.4 s). vrf/v2: TestLogPollerFilterRegistered polls every 10 ms and checks for 2 s instead of 5 s (package 8.5 s -> 4.3 s). llo: move the aggregation_fault_tolerance and v31_blob_catchup wrappers above the other integration tests. Parallel tests are released in source order, so the two longest tests no longer wait ~26 s for a slot. Co-Authored-By: Claude Sonnet 5.5 --- core/bridges/cache_test.go | 22 ++- .../ccip/launcher/integration_test.go | 3 + .../ocr2/plugins/llo/integration_test.go | 137 +++++++++--------- .../vrf/v2/listener_v2_log_listener_test.go | 8 +- 4 files changed, 94 insertions(+), 76 deletions(-) diff --git a/core/bridges/cache_test.go b/core/bridges/cache_test.go index 6183a2b7bfe..8b18a116dd6 100644 --- a/core/bridges/cache_test.go +++ b/core/bridges/cache_test.go @@ -165,26 +165,32 @@ func TestBridgeCache_Response(t *testing.T) { t.Run("async upserts bridge response", func(t *testing.T) { t.Parallel() + // A short tick so the test does not wait out the 5 s default. + const upsertInterval = 50 * time.Millisecond mORM := new(mocks.ORM) lggr, _ := logger.NewLogger() - cache := bridges.NewCache(mORM, lggr, bridges.DefaultUpsertInterval) + cache := bridges.NewCache(mORM, lggr, upsertInterval) t.Cleanup(func() { require.NoError(t, cache.Close()) }) + chBulkUpsertCalled := make(chan struct{}, 1) + // Register the expectation before Start: the 50 ms tick can fire right away. + mORM.On("BulkUpsertBridgeResponse", mock.Anything, mock.Anything).Return(nil).Run(func(_ mock.Arguments) { + // Non-blocking: the short tick can upsert more than once. + select { + case chBulkUpsertCalled <- struct{}{}: + default: + } + }) + require.NoError(t, cache.Start(t.Context())) ctx := t.Context() dotID := "test" specID := int32(42) expected := []byte("test") - chBulkUpsertCalled := make(chan struct{}, 1) - - mORM.On("BulkUpsertBridgeResponse", mock.Anything, mock.Anything).Return(nil).Run(func(_ mock.Arguments) { - chBulkUpsertCalled <- struct{}{} - }) - require.NoError(t, cache.UpsertBridgeResponse(ctx, dotID, specID, expected)) response, err := cache.GetCachedResponse(ctx, dotID, specID, time.Second) @@ -192,7 +198,7 @@ func TestBridgeCache_Response(t *testing.T) { require.NoError(t, err) assert.Equal(t, expected, response) - timer := time.NewTimer(2 * bridges.DefaultUpsertInterval) + timer := time.NewTimer(2 * bridges.DefaultUpsertInterval) // generous bound; the upsert normally lands within ~50 ms select { case <-chBulkUpsertCalled: diff --git a/core/capabilities/ccip/launcher/integration_test.go b/core/capabilities/ccip/launcher/integration_test.go index 9dec6af68ae..2123c4d90f7 100644 --- a/core/capabilities/ccip/launcher/integration_test.go +++ b/core/capabilities/ccip/launcher/integration_test.go @@ -41,6 +41,9 @@ func TestIntegration_Launcher(t *testing.T) { uni, uni.CapReg.Address().String(), registrysyncer.NewORM(db, lggr), + // The DON is added to the registry after the initial sync, so without a + // short tick the test waits out the 12 s default. + registrysyncer.WithTickInterval(100*time.Millisecond), ) require.NoError(t, err) diff --git a/core/services/ocr2/plugins/llo/integration_test.go b/core/services/ocr2/plugins/llo/integration_test.go index 7c38095de4f..20a5e33574f 100644 --- a/core/services/ocr2/plugins/llo/integration_test.go +++ b/core/services/ocr2/plugins/llo/integration_test.go @@ -539,6 +539,78 @@ func offchainConfigCases() []offchainConfigCase { } } +// Order matters for wall time. `go test` releases parallel tests to run in source +// order, and the package runs at most GOMAXPROCS of them at once. The two longest +// tests (aggregation_fault_tolerance, v31_blob_catchup) used to sit last in this +// file, so they waited ~26 s for a slot and then ran 15-25 s, leaving the package +// tail with only a few tests running. Keep the longest tests first. This is a +// scheduling aid, not a speedup of the tests themselves. + +// TestIntegration_LLO_aggregation_fault_tolerance exercises the v31 contribution +// floor. aggregationFaultTolerance sets the fewest contributions an aggregate may +// be built from (2*aft+1), so a stream observed by too few oracles must not +// produce an aggregate and its channel must not report, while a stream observed +// by the whole DON keeps reporting. +// +// With nNodes=4 and F=1, aft=1 sets a floor of 3 contributions. A stream whose +// job exists on only 2 nodes is therefore withheld, and one whose job exists on +// 3 nodes reports. aft=0 is not exercised: v31 rejects it when F is non-zero. +func TestIntegration_LLO_aggregation_fault_tolerance(t *testing.T) { + t.Parallel() + tcs := []struct { + name string + // aft is the aggregationFaultTolerance set in the offchain config. + aft uint32 + // partialObservers is how many of the 4 oracles observe the partial + // stream. + partialObservers int + // partialReports is whether the channel of the partial stream is + // expected to produce reports. + partialReports bool + salt int64 + donID uint32 + }{ + {name: "floor of 3 withholds a stream with 2 observers", aft: 1, partialObservers: 2, partialReports: false, salt: 700, donID: uint32(555111)}, + {name: "floor of 3 admits a stream with 3 observers", aft: 1, partialObservers: 3, partialReports: true, salt: 750, donID: uint32(555222)}, + } + for _, tc := range tcs { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + testIntegrationLLOAggregationFaultTolerance(t, tc.aft, tc.partialObservers, tc.partialReports, tc.salt, tc.donID) + }) + } +} + +// TestIntegration_LLO_v31_blob_catchup covers the v31 blob path for an oracle +// that is not present for the earlier rounds. v31 disseminates stream values +// through blobs, so such an oracle can only contribute once it has fetched the +// blobs and state the running DON produced without it. +// +// Two ways in: an oracle whose LLO job is created after the DON is already +// reporting, and an oracle whose job is deleted mid-run and re-created after +// the DON has advanced many rounds without it. In both cases the remaining +// 3 oracles (2F+1) keep the DON reporting throughout. +func TestIntegration_LLO_v31_blob_catchup(t *testing.T) { + t.Parallel() + tcs := []struct { + name string + // rejoin starts the lagging oracle with an LLO job and deletes it + // mid-run, instead of never creating it until catch-up time. + rejoin bool + salt int64 + donID uint32 + }{ + {name: "oracle joining after the DON is reporting catches up", rejoin: false, salt: 800, donID: uint32(555333)}, + {name: "oracle rejoining after its job is deleted catches up", rejoin: true, salt: 850, donID: uint32(555444)}, + } + for _, tc := range tcs { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + testIntegrationLLOV31BlobCatchup(t, tc.rejoin, tc.salt, tc.donID) + }) + } +} + func TestIntegration_LLO_evm_premium_legacy(t *testing.T) { t.Parallel() for _, oc := range offchainConfigCases() { @@ -3382,41 +3454,6 @@ func newSingleABIEncoder(typ string, multiplier *sqlutil.Big) (enc lloevm.ABIEnc return enc } -// TestIntegration_LLO_aggregation_fault_tolerance exercises the v31 contribution -// floor. aggregationFaultTolerance sets the fewest contributions an aggregate may -// be built from (2*aft+1), so a stream observed by too few oracles must not -// produce an aggregate and its channel must not report, while a stream observed -// by the whole DON keeps reporting. -// -// With nNodes=4 and F=1, aft=1 sets a floor of 3 contributions. A stream whose -// job exists on only 2 nodes is therefore withheld, and one whose job exists on -// 3 nodes reports. aft=0 is not exercised: v31 rejects it when F is non-zero. -func TestIntegration_LLO_aggregation_fault_tolerance(t *testing.T) { - t.Parallel() - tcs := []struct { - name string - // aft is the aggregationFaultTolerance set in the offchain config. - aft uint32 - // partialObservers is how many of the 4 oracles observe the partial - // stream. - partialObservers int - // partialReports is whether the channel of the partial stream is - // expected to produce reports. - partialReports bool - salt int64 - donID uint32 - }{ - {name: "floor of 3 withholds a stream with 2 observers", aft: 1, partialObservers: 2, partialReports: false, salt: 700, donID: uint32(555111)}, - {name: "floor of 3 admits a stream with 3 observers", aft: 1, partialObservers: 3, partialReports: true, salt: 750, donID: uint32(555222)}, - } - for _, tc := range tcs { - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - testIntegrationLLOAggregationFaultTolerance(t, tc.aft, tc.partialObservers, tc.partialReports, tc.salt, tc.donID) - }) - } -} - func testIntegrationLLOAggregationFaultTolerance(t *testing.T, aft uint32, nPartialObservers int, expectPartialReports bool, salt int64, donID uint32) { const ( // streamIDFull has a stream job on every oracle. @@ -3579,40 +3616,10 @@ pluginVersion = "v31"`, serverURL, serverPubKey, donID, configStoreAddress, from "under-observed channel should not report when it cannot meet the contribution floor") } -// TestIntegration_LLO_v31_blob_catchup covers the v31 blob path for an oracle -// that is not present for the earlier rounds. v31 disseminates stream values -// through blobs, so such an oracle can only contribute once it has fetched the -// blobs and state the running DON produced without it. -// -// Two ways in: an oracle whose LLO job is created after the DON is already -// reporting, and an oracle whose job is deleted mid-run and re-created after -// the DON has advanced many rounds without it. In both cases the remaining -// 3 oracles (2F+1) keep the DON reporting throughout. // shortEpochRMax gives ~5 s epochs at the default 500ms DeltaRound, so a // late or restarted oracle does not wait out a 50 s epoch (RMax 100). const shortEpochRMax = uint64(10) -func TestIntegration_LLO_v31_blob_catchup(t *testing.T) { - t.Parallel() - tcs := []struct { - name string - // rejoin starts the lagging oracle with an LLO job and deletes it - // mid-run, instead of never creating it until catch-up time. - rejoin bool - salt int64 - donID uint32 - }{ - {name: "oracle joining after the DON is reporting catches up", rejoin: false, salt: 800, donID: uint32(555333)}, - {name: "oracle rejoining after its job is deleted catches up", rejoin: true, salt: 850, donID: uint32(555444)}, - } - for _, tc := range tcs { - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - testIntegrationLLOV31BlobCatchup(t, tc.rejoin, tc.salt, tc.donID) - }) - } -} - func testIntegrationLLOV31BlobCatchup(t *testing.T, rejoin bool, salt int64, donID uint32) { const ( streamID = uint32(790) diff --git a/core/services/vrf/v2/listener_v2_log_listener_test.go b/core/services/vrf/v2/listener_v2_log_listener_test.go index 823cc297b04..87976a9d7cf 100644 --- a/core/services/vrf/v2/listener_v2_log_listener_test.go +++ b/core/services/vrf/v2/listener_v2_log_listener_test.go @@ -238,12 +238,14 @@ func TestLogPollerFilterRegistered(t *testing.T) { filterName := th.Listener.getLogPollerFilterName() require.Eventually(t, func() bool { return th.Listener.chain.LogPoller().HasFilter(filterName) - }, testutils.WaitTimeout(t), time.Second) + }, testutils.WaitTimeout(t), 10*time.Millisecond) - // Once registered, expect the filter to stay registered. + // Once registered, expect the filter to stay registered. The listener + // re-checks on a 1 s interval (runLogListener above), so 2 s spans + // at least one re-check. gomega.NewWithT(t).Consistently(func() bool { return th.Listener.chain.LogPoller().HasFilter(filterName) - }, 5*time.Second, 1*time.Second).Should(gomega.BeTrue()) + }, 2*time.Second, 100*time.Millisecond).Should(gomega.BeTrue()) }() // Assert channel is closed. From a6da7c3a548c1cafb94d2f7d02be2cc26cc7e0e8 Mon Sep 17 00:00:00 2001 From: Adam Hamrick Date: Wed, 11 Nov 2026 12:57:58 -0500 Subject: [PATCH 10/10] fix backup flake --- core/services/periodicbackup/backup_test.go | 14 +++++++------- core/services/pipeline/task.bridge_test.go | 7 ++++++- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/core/services/periodicbackup/backup_test.go b/core/services/periodicbackup/backup_test.go index 758cb0f451b..be968c1f87c 100644 --- a/core/services/periodicbackup/backup_test.go +++ b/core/services/periodicbackup/backup_test.go @@ -33,7 +33,7 @@ func must(t testing.TB, s string) *url.URL { func TestPeriodicBackup_RunBackup(t *testing.T) { t.Parallel() backupConfig := newTestConfig(time.Minute, nil, "", config.DatabaseBackupModeFull) - periodicBackup := mustNewDatabaseBackup(t, *must(t, string(env.DatabaseURL.Get())), os.TempDir(), backupConfig) + periodicBackup := mustNewDatabaseBackup(t, *must(t, string(env.DatabaseURL.Get())), t.TempDir(), backupConfig) assert.False(t, periodicBackup.frequencyIsTooSmall()) result, err := periodicBackup.runBackup("0.9.9") @@ -53,7 +53,7 @@ func TestPeriodicBackup_RunBackup(t *testing.T) { func TestPeriodicBackup_RunBackupInLiteMode(t *testing.T) { t.Parallel() backupConfig := newTestConfig(time.Minute, nil, "", config.DatabaseBackupModeLite) - periodicBackup := mustNewDatabaseBackup(t, *must(t, string(env.DatabaseURL.Get())), os.TempDir(), backupConfig) + periodicBackup := mustNewDatabaseBackup(t, *must(t, string(env.DatabaseURL.Get())), t.TempDir(), backupConfig) assert.False(t, periodicBackup.frequencyIsTooSmall()) result, err := periodicBackup.runBackup("0.9.9") @@ -73,7 +73,7 @@ func TestPeriodicBackup_RunBackupInLiteMode(t *testing.T) { func TestPeriodicBackup_RunBackupWithoutVersion(t *testing.T) { t.Parallel() backupConfig := newTestConfig(time.Minute, nil, "", config.DatabaseBackupModeFull) - periodicBackup := mustNewDatabaseBackup(t, *must(t, string(env.DatabaseURL.Get())), os.TempDir(), backupConfig) + periodicBackup := mustNewDatabaseBackup(t, *must(t, string(env.DatabaseURL.Get())), t.TempDir(), backupConfig) assert.False(t, periodicBackup.frequencyIsTooSmall()) result, err := periodicBackup.runBackup(static.Unset) @@ -93,7 +93,7 @@ func TestPeriodicBackup_RunBackupViaAltUrlAndMaskPassword(t *testing.T) { t.Parallel() altURL, _ := url.Parse("postgresql://invalid:some-pass@invalid") // betterleaks:allow backupConfig := newTestConfig(time.Minute, altURL, "", config.DatabaseBackupModeFull) - periodicBackup := mustNewDatabaseBackup(t, *must(t, string(env.DatabaseURL.Get())), os.TempDir(), backupConfig) + periodicBackup := mustNewDatabaseBackup(t, *must(t, string(env.DatabaseURL.Get())), t.TempDir(), backupConfig) assert.False(t, periodicBackup.frequencyIsTooSmall()) partialResult, err := periodicBackup.runBackup("") @@ -104,15 +104,15 @@ func TestPeriodicBackup_RunBackupViaAltUrlAndMaskPassword(t *testing.T) { func TestPeriodicBackup_FrequencyTooSmall(t *testing.T) { t.Parallel() backupConfig := newTestConfig(time.Second, nil, "", config.DatabaseBackupModeFull) - periodicBackup := mustNewDatabaseBackup(t, *must(t, string(env.DatabaseURL.Get())), os.TempDir(), backupConfig) + periodicBackup := mustNewDatabaseBackup(t, *must(t, string(env.DatabaseURL.Get())), t.TempDir(), backupConfig) assert.True(t, periodicBackup.frequencyIsTooSmall()) } func TestPeriodicBackup_AlternativeOutputDir(t *testing.T) { t.Parallel() - backupDir := filepath.Join(os.TempDir(), "alternative") + backupDir := filepath.Join(t.TempDir(), "alternative") backupConfig := newTestConfig(time.Second, nil, backupDir, config.DatabaseBackupModeFull) - periodicBackup := mustNewDatabaseBackup(t, *must(t, string(env.DatabaseURL.Get())), os.TempDir(), backupConfig) + periodicBackup := mustNewDatabaseBackup(t, *must(t, string(env.DatabaseURL.Get())), t.TempDir(), backupConfig) result, err := periodicBackup.runBackup("0.9.9") require.NoError(t, err, "error not nil for backup") diff --git a/core/services/pipeline/task.bridge_test.go b/core/services/pipeline/task.bridge_test.go index cabb3cc6dae..b5ed4d9f319 100644 --- a/core/services/pipeline/task.bridge_test.go +++ b/core/services/pipeline/task.bridge_test.go @@ -1475,7 +1475,12 @@ func TestBridgeTask_AdapterTimeout(t *testing.T) { }) t.Run("short", func(t *testing.T) { - ctx, cancel := context.WithTimeout(t.Context(), time.Millisecond) + // The deadline must outlast the bridge lookup, which runs against the DB + // and shares the ctx's overtime window. With a 1ms deadline that window is + // only 100ms for two DB queries, which a loaded machine can miss. Here the + // request times out against the 1s handler, then the cache read gets the + // whole overtime window to itself. + ctx, cancel := context.WithTimeout(t.Context(), 250*time.Millisecond) t.Cleanup(cancel) result, runInfo := task.Run(ctx, logger.TestLogger(t), vars, nil)