Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions changelog/2026-11-23_indexer_message_replay_requeue.md
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 2 additions & 1 deletion indexer/cmd/replay/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion indexer/pkg/common/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 10 additions & 4 deletions indexer/pkg/replay/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

```
Expand Down Expand Up @@ -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 │ │ │
└────────┬────────────────────────┘ └───────┬──────────────────────────┘
│ │
│ ┌────────────────────┐ │
Expand Down
8 changes: 8 additions & 0 deletions indexer/pkg/replay/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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 }
}
Expand Down
20 changes: 15 additions & 5 deletions indexer/pkg/replay/engine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ type mockReplayStorage struct {
upsertMsgErr error
upsertCCVErr error
forceUsed bool
requeued []protocol.Bytes32
}

func newMockReplayStorage() *mockReplayStorage {
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -429,18 +437,20 @@ 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{
lggr: lggr,
}

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)
Expand Down
29 changes: 22 additions & 7 deletions indexer/pkg/replay/message_replay.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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 {
Expand Down
14 changes: 14 additions & 0 deletions indexer/pkg/storage/testdata/explain_work_state_requeue.txt

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

40 changes: 40 additions & 0 deletions indexer/pkg/storage/work_state.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
}
7 changes: 6 additions & 1 deletion indexer/pkg/storage/work_state_explain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,16 @@ import (
"testing"

"github.com/jmoiron/sqlx"
"github.com/lib/pq"
"github.com/stretchr/testify/require"

"github.com/smartcontractkit/chainlink-ccv/indexer/pkg/common"
"github.com/smartcontractkit/chainlink-ccv/indexer/testutil"
)

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.
Expand Down Expand Up @@ -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)
Expand All @@ -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))
}

Expand Down
58 changes: 58 additions & 0 deletions indexer/pkg/storage/work_state_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading