diff --git a/changelog/2026-11-23_indexer_message_replay_requeue.md b/changelog/2026-11-23_indexer_message_replay_requeue.md new file mode 100644 index 000000000..48cf8a84c --- /dev/null +++ b/changelog/2026-11-23_indexer_message_replay_requeue.md @@ -0,0 +1,47 @@ +# Indexer message replay puts messages back in the worker queue + +## Executive Summary + +- `indexer-replay messages` now sets each message that is not `SUCCESS` back to `PROCESSING` with a new deadline of now + `VerificationVisibilityWindow`. The live workers then fetch the missing verifications, retry with backoff and set the final status. +- Before this change, the replay fetched the verifications itself and did not change the status. A message with the status `TIMEOUT` stayed `TIMEOUT`, and the workers did not retry it. +- This change affects `indexer/pkg/replay`, `indexer/cmd/replay` and `indexer/pkg/storage`. +- It adds a method to `replay.Storage` and a required engine option for message replays. + +## AI Adapter Index + +| Symbol | Kind | Search | Location | Section | +|---|---|---|---|---| +| `replay.Storage.RequeueMessages` | signature-changed | `replay\.Storage\b\|\.RequeueMessages\(` | `indexer/pkg/replay/engine.go` | [#replay-storage-has-requeuemessages](#replay-storage-has-requeuemessages) | +| `replay.Engine` message replay | behavior-changed | `runMessageReplay\|indexer-replay messages` | `indexer/pkg/replay/message_replay.go` | [#message-replay-requeues](#message-replay-requeues) | +| `replay.WithRetryWindow` | added | `WithRetryWindow\(` | `indexer/pkg/replay/engine.go:48` | [#replay-storage-has-requeuemessages](#replay-storage-has-requeuemessages) | +| `storage.PostgresStorage.RequeueMessages` | added | `\.RequeueMessages\(` | `indexer/pkg/storage/work_state.go` | [#message-replay-requeues](#message-replay-requeues) | + +## Breaking Changes + +### Replay Storage has RequeueMessages + +- **What changed:** `replay.Storage` adds `RequeueMessages(ctx, ids []protocol.Bytes32, window time.Duration) ([]protocol.Bytes32, error)`. A message replay needs `replay.WithRetryWindow(d)`. Without it, a message replay returns `retry window not configured`. +- **Who is affected:** Custom `replay.Storage` implementations and code that builds a `replay.Engine` for message replays. `indexer/cmd/replay` passes `WithRetryWindow(VerificationVisibilityWindow)`. + +## Migration Guide + +1. Add `RequeueMessages` to custom `replay.Storage` implementations. +2. Add `replay.WithRetryWindow(time.Duration(cfg.Scheduler.VerificationVisibilityWindow) * time.Second)` to `replay.NewEngine`. + +## New Features / Additions + +### Message replay requeues + +- `RequeueMessages` changes each given row that is not `SUCCESS`: + - It sets `status = 'PROCESSING'`, clears `lastErr` and sets `retry_deadline = NOW() + window`. + - A `PROCESSING` row keeps its lease and its `attempt_count`. Only its deadline changes. + - A final row (`TIMEOUT`) gets `attempt_count + 1` and a NULL `next_attempt_at`, so it is due now. The new count stops an old claim from settling the reopened row. +- It returns the IDs that it changed and wakes the local pool. A message that is `SUCCESS` or not found is logged and skipped. +- Without `--force`, the replay only requeues. The workers fetch only the missing verifications. +- With `--force`, the replay first fetches the verifications from all configured verifiers and overwrites the stored ones, then requeues. +- `work_state_explain_test.go` adds the plan of the requeue query. It uses the primary key. + +## Compatibility & Requirements + +- **Requires:** the worker claim change (`2026-11-23_indexer_workers_claim_messages.md`). +- **Discovery replay:** no change. It writes `PROCESSING` rows, and the workers claim them. diff --git a/indexer/cmd/replay/main.go b/indexer/cmd/replay/main.go index 9afe3d483..8d239f07b 100644 --- a/indexer/cmd/replay/main.go +++ b/indexer/cmd/replay/main.go @@ -368,7 +368,8 @@ func mustBuildEngine(ctx context.Context, needsDiscoveryReader bool) (*replay.En } } - engine := replay.NewEngine(replayStore, indexerStorage, verifierRegistry, aggFactory, lggr) + engine := replay.NewEngine(replayStore, indexerStorage, verifierRegistry, aggFactory, lggr, + replay.WithRetryWindow(time.Duration(cfg.Scheduler.VerificationVisibilityWindow)*time.Second)) cleanup := func() { for _, c := range verifierCleanups { diff --git a/indexer/pkg/common/storage.go b/indexer/pkg/common/storage.go index 9dbe079ea..73ba13fc2 100644 --- a/indexer/pkg/common/storage.go +++ b/indexer/pkg/common/storage.go @@ -96,7 +96,7 @@ type DiscoveryLock interface { // ErrClaimLost means another worker claimed the message again, or the message is no longer PROCESSING. var ErrClaimLost = errors.New("worker claim lost") -// WorkClaim is one leased message. Attempt is the claim token: ClaimWork increments it. +// WorkClaim is one leased message. Attempt is the claim token: ClaimWork and a replay of a final message increment it. // SettleWork changes the row only if attempt_count is still Attempt, so a stale worker gets ErrClaimLost. type WorkClaim struct { MessageID protocol.Bytes32 diff --git a/indexer/pkg/replay/README.md b/indexer/pkg/replay/README.md index cf13d6f2c..bdef38fb7 100644 --- a/indexer/pkg/replay/README.md +++ b/indexer/pkg/replay/README.md @@ -33,15 +33,21 @@ The `--since` flag takes an aggregator sequence number (unsigned integer). All m Without `--force` the replay backfills only — existing messages and CCV records are left untouched (`ON CONFLICT DO NOTHING`). With `--force`, existing records are overwritten (`ON CONFLICT DO UPDATE`). +A new message is written as `PROCESSING`. The live indexer workers claim it and fetch the missing CCV records. + ### Message Replay -Fetches CCV records from all configured verifiers for a specific set of message IDs. Does not re-run discovery. +Puts a specific set of message IDs back in the `PROCESSING` status for the live indexer workers. Does not re-run discovery. Use it to reprocess messages that timed out. ``` indexer-replay messages --ids "0xabc123,0xdef456" indexer-replay messages --ids "0xabc123,0xdef456" --force ``` +Each message that is not `SUCCESS` gets the status `PROCESSING` and a new deadline of now + `VerificationVisibilityWindow`. The live indexer workers then fetch the missing CCV records, retry with backoff until the deadline, and set the final status. A message that is already `SUCCESS` is left unchanged. A message that a worker processes at that time keeps its current attempt, and only its deadline changes. + +With `--force` the replay first fetches the CCV records from all configured verifiers and overwrites the stored records, then requeues the message as above. + ### Job Management ``` @@ -108,10 +114,10 @@ With `restartPolicy: OnFailure` the pod is automatically restarted after a crash ┌─────────────────────────────────┐ ┌──────────────────────────────────┐ │ Live Indexer Process │ │ Replay CLI Process │ │ │ │ │ -│ Discovery ──► Worker Pool │ │ CLI ──► Engine │ -│ │ │ │ ├── DiscoveryReplayer │ +│ Discovery ──► messages table │ │ CLI ──► Engine │ +│ │ (Postgres) │ │ ├── DiscoveryReplayer │ │ ▼ │ │ └── MessageReplayer │ -│ Scheduler │ │ │ +│ Worker Pool │ │ │ └────────┬────────────────────────┘ └───────┬──────────────────────────┘ │ │ │ ┌────────────────────┐ │ diff --git a/indexer/pkg/replay/engine.go b/indexer/pkg/replay/engine.go index 608614a34..d0d8a849c 100644 --- a/indexer/pkg/replay/engine.go +++ b/indexer/pkg/replay/engine.go @@ -23,6 +23,8 @@ type Storage interface { UpsertMessages(ctx context.Context, messages []common.MessageWithMetadata, force bool) error // GetMessage retrieves a message (including CCV addresses) from the messages table by ID. GetMessage(ctx context.Context, messageID protocol.Bytes32) (common.MessageWithMetadata, error) + // RequeueMessages sets messages that are not SUCCESS back to PROCESSING with a new deadline of now + window. + RequeueMessages(ctx context.Context, messageIDs []protocol.Bytes32, window time.Duration) ([]protocol.Bytes32, error) } // AggregatorReaderFactory creates a new aggregator reader for replay. @@ -37,10 +39,16 @@ type Engine struct { aggregatorReaderFactory AggregatorReaderFactory lggr logger.Logger batchThrottleDelay time.Duration + retryWindow time.Duration } type EngineOption func(*Engine) +// WithRetryWindow sets the new visibility window that a message replay gives to each message. +func WithRetryWindow(d time.Duration) EngineOption { + return func(e *Engine) { e.retryWindow = d } +} + func WithBatchThrottleDelay(d time.Duration) EngineOption { return func(e *Engine) { e.batchThrottleDelay = d } } diff --git a/indexer/pkg/replay/engine_test.go b/indexer/pkg/replay/engine_test.go index 8f7cdfbd9..3a0fd6e71 100644 --- a/indexer/pkg/replay/engine_test.go +++ b/indexer/pkg/replay/engine_test.go @@ -25,6 +25,7 @@ type mockReplayStorage struct { upsertMsgErr error upsertCCVErr error forceUsed bool + requeued []protocol.Bytes32 } func newMockReplayStorage() *mockReplayStorage { @@ -64,6 +65,13 @@ func (m *mockReplayStorage) GetMessage(ctx context.Context, messageID protocol.B return common.MessageWithMetadata{}, fmt.Errorf("message not found") } +func (m *mockReplayStorage) RequeueMessages(_ context.Context, ids []protocol.Bytes32, _ time.Duration) ([]protocol.Bytes32, error) { + m.mu.Lock() + defer m.mu.Unlock() + m.requeued = append(m.requeued, ids...) + return ids, nil +} + func (m *mockReplayStorage) capturedMessages() []common.MessageWithMetadata { m.mu.Lock() defer m.mu.Unlock() @@ -429,7 +437,8 @@ func TestRunMessageReplay_EmptyMessageIDs(t *testing.T) { assert.Contains(t, err.Error(), "at least one message ID") } -func TestRunMessageReplay_NilRegistry(t *testing.T) { +// Force replay calls the verifiers itself, so it needs the registry. +func TestRunMessageReplay_ForceNeedsRegistry(t *testing.T) { lggr := logger.Test(t) engine := &Engine{ @@ -437,10 +446,11 @@ func TestRunMessageReplay_NilRegistry(t *testing.T) { } job := &Job{ - ID: "test-nil-reg", - Type: TypeMessages, - Status: StatusRunning, - MessageIDs: []string{"0x1234"}, + ID: "test-nil-reg", + Type: TypeMessages, + Status: StatusRunning, + MessageIDs: []string{"0x1234"}, + ForceOverwrite: true, } err := engine.runMessageReplay(context.Background(), job) diff --git a/indexer/pkg/replay/message_replay.go b/indexer/pkg/replay/message_replay.go index efca9161b..fbf648ada 100644 --- a/indexer/pkg/replay/message_replay.go +++ b/indexer/pkg/replay/message_replay.go @@ -14,9 +14,12 @@ func (e *Engine) runMessageReplay(ctx context.Context, job *Job) error { if len(job.MessageIDs) == 0 { return fmt.Errorf("message replay requires at least one message ID") } - if e.registry == nil { + if job.ForceOverwrite && e.registry == nil { return fmt.Errorf("verifier registry not configured") } + if e.retryWindow <= 0 { + return fmt.Errorf("retry window not configured") + } startIdx := int(job.ProgressCursor) if startIdx > 0 { @@ -40,12 +43,24 @@ func (e *Engine) runMessageReplay(ctx context.Context, job *Job) error { e.lggr.Infow("Replaying message", "jobID", job.ID, "messageID", msgIDHex, "index", i, "total", len(job.MessageIDs)) - if err := e.gatherAllVerifications(ctx, job, msgID); err != nil { - e.lggr.Warnw("Error gathering verifications for message", - "jobID", job.ID, - "messageID", msgIDHex, - "error", err, - ) + // Force overwrites the stored verifications; the worker only fetches missing ones. + if job.ForceOverwrite { + if err := e.gatherAllVerifications(ctx, job, msgID); err != nil { + e.lggr.Warnw("Error gathering verifications for message", + "jobID", job.ID, + "messageID", msgIDHex, + "error", err, + ) + } + } + + // The worker fetches missing verifications, retries, and sets the final status. + requeued, err := e.storage.RequeueMessages(ctx, []protocol.Bytes32{msgID}, e.retryWindow) + if err != nil { + return fmt.Errorf("failed to requeue message %s: %w", msgIDHex, err) + } + if len(requeued) == 0 { + e.lggr.Infow("Message not requeued: already successful or not found", "jobID", job.ID, "messageID", msgIDHex) } if err := e.checkpointMessage(ctx, job, i+1); err != nil { diff --git a/indexer/pkg/storage/testdata/explain_work_state_requeue.txt b/indexer/pkg/storage/testdata/explain_work_state_requeue.txt new file mode 100644 index 000000000..630e65100 --- /dev/null +++ b/indexer/pkg/storage/testdata/explain_work_state_requeue.txt @@ -0,0 +1,14 @@ +=== EXPLAIN ANALYZE: requeue === +Update on indexer.messages (cost=0.42..41.04 rows=1 width=90) (actual time=0.028..0.060 rows=4 loops=1) + Output: message_id + Buffers: shared hit=76 + -> Index Scan using messages_pkey on indexer.messages (cost=0.42..41.04 rows=1 width=90) (actual time=0.013..0.025 rows=4 loops=1) + Output: 'PROCESSING'::text, ''::text, CASE WHEN (status = 'PROCESSING'::text) THEN attempt_count ELSE (attempt_count + 1) END, CASE WHEN (status = 'PROCESSING'::text) THEN next_attempt_at ELSE NULL::timestamp with time zone END, (now() + '08:00:00'::interval), ctid + Index Cond: (messages.message_id = ANY ('{new-1,retry-1,leased-1,timeout-1,success-1}'::text[])) + Filter: (messages.status <> 'SUCCESS'::text) + Rows Removed by Filter: 1 + Buffers: shared hit=24 +Planning: + Buffers: shared hit=4 +Planning Time: 0.060 ms +Execution Time: 0.070 ms diff --git a/indexer/pkg/storage/work_state.go b/indexer/pkg/storage/work_state.go index 8443b151b..03122fa46 100644 --- a/indexer/pkg/storage/work_state.go +++ b/indexer/pkg/storage/work_state.go @@ -7,6 +7,8 @@ import ( "fmt" "time" + "github.com/lib/pq" + "github.com/smartcontractkit/chainlink-ccv/indexer/pkg/common" "github.com/smartcontractkit/chainlink-ccv/protocol" ) @@ -48,6 +50,14 @@ const ( LIMIT $4 FOR UPDATE SKIP LOCKED))` countProcessingSQL = `SELECT COUNT(*) FROM indexer.messages WHERE status = $1` + requeueMessagesSQL = ` + UPDATE indexer.messages + SET next_attempt_at = CASE WHEN status = $1 THEN next_attempt_at ELSE NULL END, + attempt_count = CASE WHEN status = $1 THEN attempt_count ELSE attempt_count + 1 END, + status = $1, lastErr = '', + retry_deadline = NOW() + make_interval(secs => $2) + WHERE message_id = ANY($3) AND status <> $4 + RETURNING message_id` ) // ClaimWork implements common.IndexerStorage. @@ -118,3 +128,33 @@ func (d *PostgresStorage) CountProcessingMessages(ctx context.Context) (int64, e err := d.ds.GetContext(ctx, &n, countProcessingSQL, common.MessageProcessingString) return n, err } + +// RequeueMessages sets each given message that is not SUCCESS back to PROCESSING with a new deadline of NOW() + window. +// A PROCESSING message keeps its lease and claim token. A final message gets a new token, so an old claim cannot settle it. +func (d *PostgresStorage) RequeueMessages(ctx context.Context, messageIDs []protocol.Bytes32, window time.Duration) ([]protocol.Bytes32, error) { + if len(messageIDs) == 0 { + return nil, nil + } + ids := make([]string, len(messageIDs)) + for i, id := range messageIDs { + ids[i] = id.String() + } + var out []string + err := d.ds.SelectContext(ctx, &out, requeueMessagesSQL, + common.MessageProcessingString, window.Seconds(), pq.Array(ids), common.MessageSuccessfulString) + if err != nil { + return nil, fmt.Errorf("failed to requeue messages: %w", err) + } + requeued := make([]protocol.Bytes32, 0, len(out)) + for _, id := range out { + b, err := protocol.NewBytes32FromString(id) + if err != nil { + return nil, err + } + requeued = append(requeued, b) + } + if len(requeued) > 0 && d.onMessagesPersisted != nil { + d.onMessagesPersisted() + } + return requeued, nil +} diff --git a/indexer/pkg/storage/work_state_explain_test.go b/indexer/pkg/storage/work_state_explain_test.go index fb6d10378..45334d83c 100644 --- a/indexer/pkg/storage/work_state_explain_test.go +++ b/indexer/pkg/storage/work_state_explain_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/jmoiron/sqlx" + "github.com/lib/pq" "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink-ccv/indexer/pkg/common" @@ -15,7 +16,8 @@ import ( ) const ( - explainLeaseSecs = 90.0 + explainLeaseSecs = 90.0 + explainRequeueWindowSecs = 28800.0 // the devenv VerificationVisibilityWindow ) // seedWorkStateExplainData loads indexer.messages with a mix of final, due, leased and expired rows. @@ -65,6 +67,7 @@ func TestExplainWorkStateQueryPlans(t *testing.T) { require.NoError(t, RunMigrationsContext(t.Context(), db)) seedWorkStateExplainData(t, db) + ids := []string{"new-1", "retry-1", "leased-1", "timeout-1", "success-1"} processing := common.MessageProcessingString explainWorkState(t, db, "claim", claimWorkSQL, processing, explainLeaseSecs, 50) @@ -75,6 +78,8 @@ func TestExplainWorkStateQueryPlans(t *testing.T) { explainWorkState(t, db, "expire", expireWorkSQL, common.MessageTimeout.String(), "retry deadline passed", processing, 1000) explainWorkState(t, db, "count_processing", countProcessingSQL, processing) + explainWorkState(t, db, "requeue", requeueMessagesSQL, + processing, explainRequeueWindowSecs, pq.Array(ids), common.MessageSuccessfulString) explainWorkState(t, db, "backfill_retry_deadline", retryDeadlineBackfillSQL(t)) } diff --git a/indexer/pkg/storage/work_state_test.go b/indexer/pkg/storage/work_state_test.go index dba3d0b2b..f5960548c 100644 --- a/indexer/pkg/storage/work_state_test.go +++ b/indexer/pkg/storage/work_state_test.go @@ -221,6 +221,64 @@ func TestUpsertMessages_DefaultRetryDeadline(t *testing.T) { require.WithinDuration(t, before.Add(24*time.Hour), *d, 5*time.Second) } +// Requeue gives a timed-out message a new deadline, so an old message is claimed again; SUCCESS is not changed. +func TestRequeueMessages_GivesNewWindow(t *testing.T) { + s := newWorkStateStorage(t) + timedOut, done := testMessage(7), testMessage(8) + timedOut.Metadata.Status = common.MessageTimeout + done.Metadata.Status = common.MessageSuccessful + ids := insertMessages(t, s, timedOut, done) + past := time.Now().Add(-time.Minute) + setDeadline(t, s, ids[0], &past) + + requeued, err := s.RequeueMessages(t.Context(), ids, testWindow) + require.NoError(t, err) + require.Equal(t, []protocol.Bytes32{ids[0]}, requeued) + require.Equal(t, common.MessageProcessing, statusOf(t, s, ids[0])) + require.Equal(t, common.MessageSuccessful, statusOf(t, s, ids[1])) + + claims, err := s.ClaimWork(t.Context(), 10, time.Minute) + require.NoError(t, err) + require.Equal(t, []common.WorkClaim{{MessageID: ids[0], Attempt: 2}}, claims, "reopening a final message gives a new token") + + // A requeue during an attempt keeps the lease and the claim token. + _, err = s.RequeueMessages(t.Context(), ids[:1], testWindow) + require.NoError(t, err) + claims, err = s.ClaimWork(t.Context(), 10, time.Minute) + require.NoError(t, err) + require.Empty(t, claims) + _, err = s.SettleWork(t.Context(), common.WorkSettlement{MessageID: ids[0], Attempt: 2, Status: common.MessageSuccessful}) + require.NoError(t, err) +} + +// A worker whose claim expired cannot settle the message after a replay reopens it. +func TestRequeueMessages_InvalidatesExpiredClaim(t *testing.T) { + s := newWorkStateStorage(t) + ids := insertMessages(t, s, testMessage(10)) + claims, err := s.ClaimWork(t.Context(), 1, time.Millisecond) + require.NoError(t, err) + require.Equal(t, 1, claims[0].Attempt) + time.Sleep(10 * time.Millisecond) + + // The lease and the deadline end, so the message times out. + past := time.Now().Add(-time.Minute) + setDeadline(t, s, ids[0], &past) + n, err := s.ExpireWork(t.Context(), 10) + require.NoError(t, err) + require.EqualValues(t, 1, n) + _, err = s.RequeueMessages(t.Context(), ids, testWindow) + require.NoError(t, err) + + // The old worker resumes before the next claim. + _, err = s.SettleWork(t.Context(), common.WorkSettlement{MessageID: ids[0], Attempt: 1, Status: common.MessageTimeout}) + require.ErrorIs(t, err, common.ErrClaimLost) + require.Equal(t, common.MessageProcessing, statusOf(t, s, ids[0])) + + claims, err = s.ClaimWork(t.Context(), 1, time.Minute) + require.NoError(t, err) + require.Equal(t, []common.WorkClaim{{MessageID: ids[0], Attempt: 3}}, claims) +} + // The discovery traceparent is stored with the message and returned with each claim. func TestClaimWork_ReturnsTraceParent(t *testing.T) { s := newWorkStateStorage(t)