Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/llo-transmit-queue-deadlock.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@chainlink/data-streams": patch
---

Fixed a Postgres deadlock (`40P01`) between `Delete` and `Prune` on `llo_mercury_transmit_queue`. `Prune` now selects candidate rows with `FOR UPDATE SKIP LOCKED`, so it no longer holds locks in an order that can conflict with `Delete`. A skipped row is left for the next prune cycle.
43 changes: 30 additions & 13 deletions llo/transmitter/dataengine/orm.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,14 @@ func (o *orm) Prune(ctx context.Context, serverURL string, maxSize, batchSize in
return 0, fmt.Errorf("llo orm: failed to get oldest seq_nr: %w", err)
}
// Prune the requests with seq_nr older than this, in batches to avoid long
// locking or queries
// locking or queries.
//
// SKIP LOCKED is essential here: Delete removes rows by transmission_hash
// while Prune walks them by seq_nr, so the two can hold locks on rows the
// other wants and deadlock (40P01). Prune is best-effort, so skipping a row
// that is currently being deleted is fine; it is cleaned up by the next
// cycle. Delete must not skip because its caller has already removed those
// transmissions from the in-memory queue.
for {
var res sql.Result
res, err = o.ds.ExecContext(ctx, `
Expand All @@ -215,6 +222,7 @@ USING (
AND seq_nr < $3
ORDER BY seq_nr ASC
LIMIT $4
FOR UPDATE SKIP LOCKED
) AS to_delete
WHERE q.transmission_hash = to_delete.transmission_hash;
`, o.donID, serverURL, oldest, batchSize)
Expand All @@ -232,22 +240,31 @@ WHERE q.transmission_hash = to_delete.transmission_hash;
rowsDeleted += rowsAffected
}

// This query to trim off the final few rows to reach exactly maxSize with
// This query to trim off the final few rows to reach exactly maxSize
// should now be fast and efficient because of the batch deletes that
// already completed above.
//
// Select candidate rows in an unlocked OFFSET subquery first, then apply
// FOR UPDATE SKIP LOCKED only to those excess rows. Putting FOR UPDATE in
// the same SELECT as OFFSET would lock all maxSize retained rows before
// skipping them, and SKIP LOCKED on a locked retained row would shift the
// OFFSET window and over-delete a kept row.
res, err := o.ds.ExecContext(ctx, `
WITH to_delete AS (
SELECT ctid
FROM (
SELECT ctid,
ROW_NUMBER() OVER (PARTITION BY don_id, server_url ORDER BY seq_nr DESC, inserted_at DESC) AS row_num
DELETE FROM llo_mercury_transmit_queue AS q
USING (
SELECT transmission_hash
FROM llo_mercury_transmit_queue
WHERE don_id = $1 AND server_url = $2
AND transmission_hash IN (
SELECT transmission_hash
FROM llo_mercury_transmit_queue
WHERE don_id = $1 AND server_url = $2
) sub
WHERE row_num > $3
)
DELETE FROM llo_mercury_transmit_queue
WHERE ctid IN (SELECT ctid FROM to_delete);
WHERE don_id = $1 AND server_url = $2
ORDER BY seq_nr DESC, inserted_at DESC
OFFSET $3
)
FOR UPDATE SKIP LOCKED
) AS to_delete
WHERE q.transmission_hash = to_delete.transmission_hash;
Comment on lines +253 to +267

@brunotm brunotm Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we need the partitioning predicate also on the middle query taking the lock. this will allow the qeury planner to estimate the scan instead of a sequential or hash join over the whole table,

Suggested change
DELETE FROM llo_mercury_transmit_queue AS q
USING (
SELECT transmission_hash
FROM llo_mercury_transmit_queue
WHERE transmission_hash IN (
SELECT transmission_hash
FROM llo_mercury_transmit_queue
WHERE don_id = $1 AND server_url = $2
) sub
WHERE row_num > $3
)
DELETE FROM llo_mercury_transmit_queue
WHERE ctid IN (SELECT ctid FROM to_delete);
WHERE don_id = $1 AND server_url = $2
ORDER BY seq_nr DESC, inserted_at DESC
OFFSET $3
)
FOR UPDATE SKIP LOCKED
) AS to_delete
WHERE q.transmission_hash = to_delete.transmission_hash;
DELETE FROM llo_mercury_transmit_queue AS q
USING (
SELECT transmission_hash
FROM llo_mercury_transmit_queue
WHERE don_id = $1 AND server_url = $2
AND transmission_hash IN (
SELECT transmission_hash
FROM llo_mercury_transmit_queue
WHERE don_id = $1 AND server_url = $2
ORDER BY seq_nr DESC, inserted_at DESC
OFFSET $3
)
FOR UPDATE SKIP LOCKED
) AS to_delete
WHERE q.transmission_hash = to_delete.transmission_hash;

`, o.donID, serverURL, maxSize)

if err != nil {
Expand Down
119 changes: 119 additions & 0 deletions llo/transmitter/dataengine/orm_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package dataengine

import (
"sync"
"testing"
"time"

Expand Down Expand Up @@ -145,3 +146,121 @@ func TestORM(t *testing.T) {
require.Len(t, result, 5)
})
}

// TestORM_PruneSkipsRowsLockedByDelete checks that Prune does not wait for rows that a concurrent Delete has
// locked. Delete removes rows by transmission_hash while Prune walks them by seq_nr, so without
// FOR UPDATE SKIP LOCKED the two delete paths can hold locks on rows the other wants and deadlock (40P01).
func TestORM_PruneSkipsRowsLockedByDelete(t *testing.T) {
ctx := t.Context()
sessions := testutils.NewIndependentSqlxSessions(t, 2)
lockDS, pruneDS := sessions[0], sessions[1]

const (
donID = uint32(1234)
n = 10
maxSize = 5
batchSize = 100
)
transmissions := makeSampleTransmissions(n, sURL)
require.NoError(t, NewORM(lockDS, donID).Insert(ctx, transmissions))

// Hold a lock on the oldest row (pruned by the batch loop) and on the newest row (retained in the top
// maxSize during the final OFFSET truncate), exactly like an in-flight Delete would.
tx, err := lockDS.BeginTxx(ctx, nil)
require.NoError(t, err)
t.Cleanup(func() { _ = tx.Rollback() })
var locked [][]byte
require.NoError(t, tx.SelectContext(ctx, &locked,
`SELECT transmission_hash FROM llo_mercury_transmit_queue
WHERE don_id = $1 AND server_url = $2 AND seq_nr IN (0, $3)
FOR UPDATE`, donID, sURL, n-1))
require.Len(t, locked, 2)

// Prune must not block on the locked rows, and a locked retained row (seq_nr = n-1) must not shift the
// OFFSET window in the final truncate to over-delete seq_nr = 5. If Prune blocks, the session's lock_timeout
// fires and it returns 55P03, so the failure is reported as an error rather than a hang; the deadline is
// only a safety net.
done := make(chan struct{})
var (
deleted int64
pruneErr error
)
go func() {
deleted, pruneErr = NewORM(pruneDS, donID).Prune(ctx, sURL, maxSize, batchSize)
close(done)
}()
select {
case <-done:
case <-time.After(60 * time.Second):
t.Fatal("Prune did not return; expected FOR UPDATE SKIP LOCKED to skip the locked row")
}
require.NoError(t, pruneErr, "Prune blocked on a row locked by Delete; expected FOR UPDATE SKIP LOCKED")
assert.Equal(t, int64(n-maxSize-1), deleted)

result, err := NewORM(pruneDS, donID).Get(ctx, sURL, 100, 0)
require.NoError(t, err)
require.Len(t, result, n-maxSize+1, "maxSize rows plus the one still locked")
var seqNrs []uint64
for _, tr := range result {
seqNrs = append(seqNrs, tr.SeqNr)
}
assert.ElementsMatch(t, []uint64{0, 5, 6, 7, 8, 9}, seqNrs, "only the locked row should be left below maxSize")
}

// TestORM_ConcurrentDeleteAndPrune hammers Delete and Prune at the same time and fails if either returns an
// error. It is a broader regression net around the SQL in Prune; the deadlock itself is reproduced
// deterministically in TestORM_PruneSkipsRowsLockedByDelete.
func TestORM_ConcurrentDeleteAndPrune(t *testing.T) {
ctx := t.Context()
sessions := testutils.NewIndependentSqlxSessions(t, 2)
deleteORM := NewORM(sessions[0], 4321)
pruneORM := NewORM(sessions[1], 4321)

const (
n = 1_000
iterations = 25
maxSize = n / 2
pruneBatch = 32
deleteSize = 100
)

transmissions := makeSampleTransmissions(n, sURL)
require.NoError(t, deleteORM.Insert(ctx, transmissions))
hashes := make([][32]byte, n)
for i, tr := range transmissions {
hashes[i] = tr.Hash()
}

errs := make(chan error, 2*iterations)
for i := range iterations {
// Restore anything the previous round pruned so both paths keep contending over real rows.
require.NoError(t, deleteORM.Insert(ctx, transmissions))

// Rotate the Delete batch so it overlaps different parts of Prune's seq_nr ordering.
start := (i * 37) % n
batch := make([][32]byte, deleteSize)
for j := range batch {
batch[j] = hashes[(start+j)%n]
}

var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
if err := deleteORM.Delete(ctx, batch); err != nil {
errs <- err
}
}()
go func() {
defer wg.Done()
if _, err := pruneORM.Prune(ctx, sURL, maxSize, pruneBatch); err != nil {
errs <- err
}
}()
wg.Wait()
}
close(errs)
for err := range errs {
require.NoError(t, err, "concurrent Delete/Prune must not deadlock")
}
}
49 changes: 39 additions & 10 deletions mercury/testutils/sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,23 +44,52 @@ const pristineDBName = "chainlink_test_pristine" // TODO update when splitting s
// NewIndependentSqlxDB return a new independent test database, which does not use txdb and therefore supports txs etc.
// Use this with caution, as it is much more costly than NewSqlxDB.
func NewIndependentSqlxDB(t testing.TB) *sqlx.DB {
SkipShortDB(t)
return NewIndependentSqlxDBs(t, 1)[0]
}

// NewIndependentSqlxDBs returns n handles to a single fresh test database, which does not use txdb and therefore
// supports real transactions and lock contention between connections. Use this with caution, as it is much more
// costly than NewSqlxDB.
func NewIndependentSqlxDBs(t testing.TB, n int) []*sqlx.DB {
return newIndependentSqlxDBs(t, n, pg.DBConfig{
IdleInTxSessionTimeout: time.Hour,
LockTimeout: 15 * time.Second,
MaxOpenConns: 100,
MaxIdleConns: 10,
})
}

// NewIndependentSqlxSessions returns n handles to a single fresh test database, each pinned to its own
// connection (pool size 1). Unlike the handles from NewIndependentSqlxDBs, session state such as SET or an
// open transaction does not leak between them, which makes it suitable for tests that hold locks on one
// session while another session contends for them.
//
// lock_timeout is set so that a regression that makes a query wait on a lock fails the test instead of hanging it.
func NewIndependentSqlxSessions(t testing.TB, n int) []*sqlx.DB {
return newIndependentSqlxDBs(t, n, pg.DBConfig{
IdleInTxSessionTimeout: time.Hour,
LockTimeout: 10 * time.Second,
MaxOpenConns: 1,
MaxIdleConns: 1,
})
}

func newIndependentSqlxDBs(t testing.TB, n int, cfg pg.DBConfig) []*sqlx.DB {
SkipShortDB(t)
ctx := tests.Context(t)

dbURL, err := url.Parse(sqltest.TestURL(t))
require.NoError(t, err)
dbName := "chainlink_test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
newDBURL := sqltest.CreateOrReplace(t, *dbURL, dbName, pristineDBName)

db, err := pg.DBConfig{
IdleInTxSessionTimeout: time.Hour,
LockTimeout: 15 * time.Second,
MaxOpenConns: 100,
MaxIdleConns: 10,
}.New(ctx, newDBURL.String(), pg.DriverPostgres)
require.NoError(t, err)
t.Cleanup(func() { assert.NoError(t, db.Close()) })
dbs := make([]*sqlx.DB, n)
for i := range dbs {
db, err := cfg.New(ctx, newDBURL.String(), pg.DriverPostgres)
require.NoError(t, err)
t.Cleanup(func() { assert.NoError(t, db.Close()) })
dbs[i] = db
}

return db
return dbs
}
Loading