A late result from an earlier attempt can overwrite the attempt that's running

未關閉
#1,599 0 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

維護者通常 1 天內回覆

還沒有人認領這個 Issue。

評估

難度
3/5
預估耗時
1-2 天
新手友好度
45/100
Issue 類型
缺陷
描述清晰度
基本清楚
活躍度
活躍
技術堆疊
go, postgresql
領域
backend, databases

研究方向

The stale update is in JobSetStateIfRunningMany and JobCompleteTx, which the reporter says check job ID and state but not the execution that produced the result. Start with the three tests in the reproduction (TestLostReplyRetryOverwritesNextAttempt, TestJobCompleteTxAfterRescue, TestLateResultAfterRescue) and confirm they fail on master against a disposable Postgres. Done means all three pass without overlapping attempts and the existing tests still pass; the proposed attempted_at guard is one option, and #1289 is the related discussion.

由索引模型根據 Issue 內容生成。

描述

JobSetStateIfRunningMany can apply attempt 1's result while attempt 2 is running. It checks the job ID and state, but not which execution produced the result. That can start a third attempt alongside the second, or mark a running job completed.

#1289 already discusses guarding stale completions, including JobCompleteTx. This report has a runnable reproduction on released versions and a lost-reply case that doesn't need rescue or shutdown:

  1. Postgres applies attempt 1's error, but its reply is lost. The completer retries after attempt 2 starts, making the job available again.
  2. After rescue starts attempt 2, attempt 1 calls JobCompleteTx, which completes the job without error.
  3. After rescue, attempt 1 returns an error instead, making the job available while attempt 2 runs.

All three fail on v0.51.2 and master edc210f8, using Go 1.27.3, Postgres 18.6 and riverpgxv5.

Matching each result's attempted_at makes all three pass in a patch I've tested, which adds AND (NOT job_input.attempted_at_do_match OR river_job.attempted_at = job_input.attempted_at) to JobSetStateIfRunningMany. I can open it as a PR. Unlike the attempt number, it distinguishes executions after a snooze. This could be the separate attempt-guard change suggested in #1289.

repro_test.go and output (creates and drops databases)

Needs Postgres and a role that can create databases. Each test creates and drops river_repro_<random> on the server in DATABASE_URL. The lost-reply test uses a TCP relay and requires plaintext connections (sslmode=disable). Run only against a disposable test server. The file takes about 100 seconds.

Save the program as repro_test.go, then run:

go mod init repro
go get github.com/riverqueue/[email protected] github.com/riverqueue/river/riverdriver/[email protected]
go mod tidy
DATABASE_URL='postgres://user@localhost:5432/postgres?sslmode=disable' go test -v -count=1

Use @master instead of @v0.51.2 to test master.

package repro

import (
	"bytes"
	"context"
	"crypto/rand"
	"encoding/hex"
	"errors"
	"net"
	"os"
	"strconv"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/riverqueue/river"
	"github.com/riverqueue/river/riverdriver/riverpgxv5"
	"github.com/riverqueue/river/rivermigrate"
	"github.com/riverqueue/river/rivertype"
)

type retryNow struct{}

func (retryNow) NextRetry(*rivertype.JobRow) time.Time { return time.Now() }

type reproArgs struct{}

func (reproArgs) Kind() string { return "repro" }

// Attempt 1 fails. Postgres applies the completer's update, but the reply is
// lost, so the completer retries the same update about a second later. By
// then attempt 2 is running, and the retry makes the job available again.
func TestLostReplyRetryOverwritesNextAttempt(t *testing.T) {
	ctx := context.Background()
	cfg := newDatabase(t)
	rl := newRelay(t, cfg.Host, cfg.Port)
	pool := newPool(t, cfg, rl.addr())

	var mu sync.Mutex
	running := 0
	overlaps := 0
	workers := river.NewWorkers()
	river.AddWorker(workers, river.WorkFunc(func(ctx context.Context, job *river.Job[reproArgs]) error {
		if job.Attempt == 1 {
			return errors.New("attempt 1 fails")
		}
		mu.Lock()
		if running > 0 {
			overlaps++
			t.Logf("attempt %d started while another attempt was running", job.Attempt)
		}
		running++
		mu.Unlock()
		defer func() { mu.Lock(); running--; mu.Unlock() }()
		select {
		case <-time.After(5 * time.Second):
		case <-ctx.Done():
		}
		return nil
	}))
	client, err := river.NewClient(riverpgxv5.New(pool), &river.Config{
		FetchCooldown:     10 * time.Millisecond,
		FetchPollInterval: 50 * time.Millisecond,
		Queues:            map[string]river.QueueConfig{river.QueueDefault: {MaxWorkers: 4}},
		RetryPolicy:       retryNow{},
		Workers:           workers,
	})
	if err != nil {
		t.Fatal(err)
	}
	if err := client.Start(ctx); err != nil {
		t.Fatal(err)
	}
	res, err := client.Insert(ctx, reproArgs{}, nil)
	if err != nil {
		t.Fatal(err)
	}
	time.Sleep(12 * time.Second)
	stopCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
	defer cancel()
	if err := client.Stop(stopCtx); err != nil {
		t.Fatal(err)
	}

	job, err := client.JobGet(ctx, res.Job.ID)
	if err != nil {
		t.Fatal(err)
	}
	errs := make([]string, len(job.Errors))
	for i, e := range job.Errors {
		errs[i] = e.Error
	}
	t.Logf("lost replies: %d; final state %s, attempt %d, errors %q", rl.lost.Load(), job.State, job.Attempt, errs)
	if rl.lost.Load() != 1 {
		t.Fatal("the relay did not lose the completer's reply")
	}
	if overlaps > 0 {
		t.Error("two attempts ran at once: the retried update from attempt 1 made the job available while attempt 2 ran")
	}
}

// Attempt 1 outlives RescueStuckJobsAfter, and the rescuer makes the job
// available again, so attempt 2 starts. Attempt 1 then calls JobCompleteTx.
func TestJobCompleteTxAfterRescue(t *testing.T) {
	ctx := context.Background()
	cfg := newDatabase(t)
	pool := newPool(t, cfg, "")

	attempt2Started := make(chan struct{})
	release2 := make(chan struct{})
	var attempt1Err error
	attempt1Done := make(chan struct{})
	workers := river.NewWorkers()
	river.AddWorker(workers, river.WorkFunc(func(ctx context.Context, job *river.Job[reproArgs]) error {
		if job.Attempt == 2 {
			close(attempt2Started)
			<-release2
			return nil
		}
		// Attempt 1 finishes its work after its timeout, so it commits with a
		// context that isn't cancelled.
		defer close(attempt1Done)
		<-attempt2Started
		attempt1Err = pgx.BeginFunc(context.WithoutCancel(ctx), pool, func(tx pgx.Tx) error {
			_, err := river.JobCompleteTx[*riverpgxv5.Driver](context.WithoutCancel(ctx), tx, job)
			return err
		})
		return attempt1Err
	}))
	client, err := river.NewClient(riverpgxv5.New(pool), &river.Config{
		FetchCooldown:        10 * time.Millisecond,
		FetchPollInterval:    50 * time.Millisecond,
		JobTimeout:           5 * time.Second,
		Queues:               map[string]river.QueueConfig{river.QueueDefault: {MaxWorkers: 4}},
		RescueStuckJobsAfter: 5 * time.Second,
		RetryPolicy:          retryNow{},
		Workers:              workers,
	})
	if err != nil {
		t.Fatal(err)
	}
	if err := client.Start(ctx); err != nil {
		t.Fatal(err)
	}
	res, err := client.Insert(ctx, reproArgs{}, nil)
	if err != nil {
		t.Fatal(err)
	}
	select {
	case <-attempt1Done:
	case <-time.After(90 * time.Second):
		t.Fatal("the rescuer did not start attempt 2 within 90 seconds")
	}
	job, err := client.JobGet(ctx, res.Job.ID)
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("attempt 1's JobCompleteTx returned %v; the job is now %s at attempt %d, while attempt 2 is still running", attempt1Err, job.State, job.Attempt)
	close(release2)
	stopCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
	defer cancel()
	if err := client.Stop(stopCtx); err != nil {
		t.Fatal(err)
	}
	if attempt1Err == nil {
		t.Error("JobCompleteTx from attempt 1 completed the job while attempt 2 was running")
	}
}

// Attempt 1 ignores its context and outlives RescueStuckJobsAfter, so the
// rescuer makes the job available again and attempt 2 starts. Attempt 1 then
// returns an error. No network fault is involved.
func TestLateResultAfterRescue(t *testing.T) {
	ctx := context.Background()
	cfg := newDatabase(t)
	pool := newPool(t, cfg, "")

	var mu sync.Mutex
	attempt2Running := false
	overlaps := 0
	attempt2Started := make(chan struct{})
	attempt1Done := make(chan struct{})
	workers := river.NewWorkers()
	river.AddWorker(workers, river.WorkFunc(func(ctx context.Context, job *river.Job[reproArgs]) error {
		switch job.Attempt {
		case 1:
			defer close(attempt1Done)
			<-attempt2Started
			return errors.New("attempt 1 fails late")
		case 2:
			mu.Lock()
			attempt2Running = true
			mu.Unlock()
			close(attempt2Started)
			time.Sleep(10 * time.Second)
			mu.Lock()
			attempt2Running = false
			mu.Unlock()
			return nil
		default:
			mu.Lock()
			if attempt2Running {
				overlaps++
				t.Logf("attempt %d started while attempt 2 was running", job.Attempt)
			}
			mu.Unlock()
			return nil
		}
	}))
	client, err := river.NewClient(riverpgxv5.New(pool), &river.Config{
		FetchCooldown:        10 * time.Millisecond,
		FetchPollInterval:    50 * time.Millisecond,
		JobTimeout:           5 * time.Second,
		Queues:               map[string]river.QueueConfig{river.QueueDefault: {MaxWorkers: 4}},
		RescueStuckJobsAfter: 5 * time.Second,
		RetryPolicy:          retryNow{},
		Workers:              workers,
	})
	if err != nil {
		t.Fatal(err)
	}
	if err := client.Start(ctx); err != nil {
		t.Fatal(err)
	}
	res, err := client.Insert(ctx, reproArgs{}, nil)
	if err != nil {
		t.Fatal(err)
	}
	select {
	case <-attempt1Done:
	case <-time.After(90 * time.Second):
		t.Fatal("the rescuer did not start attempt 2 within 90 seconds")
	}
	time.Sleep(12 * time.Second) // attempt 2 finishes
	stopCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
	defer cancel()
	if err := client.Stop(stopCtx); err != nil {
		t.Fatal(err)
	}

	job, err := client.JobGet(ctx, res.Job.ID)
	if err != nil {
		t.Fatal(err)
	}
	errs := make([]string, len(job.Errors))
	for i, e := range job.Errors {
		errs[i] = e.Error
	}
	t.Logf("final state %s, attempt %d, errors %q", job.State, job.Attempt, errs)
	mu.Lock()
	defer mu.Unlock()
	if overlaps > 0 {
		t.Error("attempt 1's late error made the job available while attempt 2 ran")
	}
}

// newDatabase creates a database with River's schema and drops it when the
// test ends. It needs DATABASE_URL, for a role that may create databases.
func newDatabase(t *testing.T) *pgx.ConnConfig {
	t.Helper()
	ctx := context.Background()
	admin, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
	if err != nil {
		t.Fatal(err)
	}
	b := make([]byte, 4)
	_, _ = rand.Read(b)
	name := "river_repro_" + hex.EncodeToString(b)
	if _, err := admin.Exec(ctx, "CREATE DATABASE "+name); err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() {
		_, _ = admin.Exec(context.Background(), "DROP DATABASE "+name+" WITH (FORCE)")
		_ = admin.Close(context.Background())
	})
	cfg, err := pgx.ParseConfig(os.Getenv("DATABASE_URL"))
	if err != nil {
		t.Fatal(err)
	}
	cfg.Database = name
	pool := newPool(t, cfg, "")
	migrator, err := rivermigrate.New(riverpgxv5.New(pool), nil)
	if err != nil {
		t.Fatal(err)
	}
	if _, err := migrator.Migrate(ctx, rivermigrate.DirectionUp, nil); err != nil {
		t.Fatal(err)
	}
	pool.Close()
	return cfg
}

// newPool opens a pool to cfg's database, through addr if it isn't empty.
func newPool(t *testing.T, cfg *pgx.ConnConfig, addr string) *pgxpool.Pool {
	t.Helper()
	pcfg, err := pgxpool.ParseConfig("")
	if err != nil {
		t.Fatal(err)
	}
	pcfg.ConnConfig = cfg.Copy()
	if addr != "" {
		host, port, _ := net.SplitHostPort(addr)
		p, err := strconv.ParseUint(port, 10, 16)
		if err != nil {
			t.Fatal(err)
		}
		pcfg.ConnConfig.Host, pcfg.ConnConfig.Port, pcfg.ConnConfig.Fallbacks = host, uint16(p), nil
	}
	pool, err := pgxpool.NewWithConfig(context.Background(), pcfg)
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(pool.Close)
	return pool
}

// relay forwards TCP connections to Postgres. It loses Postgres's reply to
// the first execution of JobSetStateIfRunningMany, after Postgres has applied
// it, and closes that connection, as a network fault would.
type relay struct {
	ln     net.Listener
	target string
	lost   atomic.Int32
	armed  atomic.Bool // the first JobSetStateIfRunningMany was prepared
}

func newRelay(t *testing.T, host string, port uint16) *relay {
	t.Helper()
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	r := &relay{ln: ln, target: net.JoinHostPort(host, strconv.Itoa(int(port)))}
	go r.accept()
	t.Cleanup(func() { _ = ln.Close() })
	return r
}

func (r *relay) addr() string { return r.ln.Addr().String() }

func (r *relay) accept() {
	for {
		c, err := r.ln.Accept()
		if err != nil {
			return
		}
		s, err := net.Dial("tcp", r.target)
		if err != nil {
			_ = c.Close()
			continue
		}
		var loseNext atomic.Bool
		go r.fromClient(c, s, &loseNext)
		go r.fromServer(s, c, &loseNext)
	}
}

// fromClient watches for the statement. pgx prepares a statement in one round
// trip and executes it in the next, and only the prepare carries the SQL text,
// so the reply to lose is the one after the client's next message.
func (r *relay) fromClient(c, s net.Conn, loseNext *atomic.Bool) {
	defer s.Close()
	buf := make([]byte, 32<<10)
	prepared := false
	for {
		n, err := c.Read(buf)
		if n > 0 {
			if prepared && r.lost.Load() == 0 {
				loseNext.Store(true)
				prepared = false
			}
			if bytes.Contains(buf[:n], []byte("-- name: JobSetStateIfRunningMany")) && r.armed.CompareAndSwap(false, true) {
				prepared = true
			}
			if _, werr := s.Write(buf[:n]); werr != nil {
				return
			}
		}
		if err != nil {
			return
		}
	}
}

func (r *relay) fromServer(s, c net.Conn, loseNext *atomic.Bool) {
	defer c.Close()
	buf := make([]byte, 32<<10)
	for {
		n, err := s.Read(buf)
		if n > 0 {
			if loseNext.Load() {
				r.lost.Add(1)
				_ = s.Close()
				return
			}
			if _, werr := c.Write(buf[:n]); werr != nil {
				return
			}
		}
		if err != nil {
			return
		}
	}
}

Master edc210f8, with the structured log lines omitted:

=== RUN   TestLostReplyRetryOverwritesNextAttempt
    repro_test.go:53: attempt 3 started while another attempt was running
    repro_test.go:96: lost replies: 1; final state completed, attempt 3, errors ["attempt 1 fails" "attempt 1 fails"]
    repro_test.go:101: two attempts ran at once: the retried update from attempt 1 made the job available while attempt 2 ran
--- FAIL: TestLostReplyRetryOverwritesNextAttempt (14.86s)
=== RUN   TestJobCompleteTxAfterRescue
    repro_test.go:161: attempt 1's JobCompleteTx returned <nil>; the job is now completed at attempt 2, while attempt 2 is still running
    repro_test.go:169: JobCompleteTx from attempt 1 completed the job while attempt 2 was running
--- FAIL: TestJobCompleteTxAfterRescue (37.12s)
=== RUN   TestLateResultAfterRescue
    repro_test.go:207: attempt 3 started while attempt 2 was running
    repro_test.go:252: final state completed, attempt 3, errors ["Stuck job rescued by JobRescuer" "attempt 1 fails late"]
    repro_test.go:256: attempt 1's late error made the job available while attempt 2 ran
--- FAIL: TestLateResultAfterRescue (47.76s)
主要語言
Go
星號
6k
分支
210
平均合併
12 小時 2 分鐘
30 天內合併 PR
24

環境準備

這個專案沒有提供開發容器、Dockerfile 或貢獻指南,環境需要你自己搭建:先看它的 README,通用步驟見我們的新手貢獻指南。

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

riverqueue/river 的其他 Issue

查看 riverqueue/river 的全部 Issue

相似的 Issue

更多 Go Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。