From 9cc4f07339c48ec2fa4c77d2e0ef0704b63524ea Mon Sep 17 00:00:00 2001 From: Adam Hamrick Date: Fri, 30 Oct 2026 12:44:28 -0400 Subject: [PATCH 1/3] fix(llo): avoid transmit queue deadlock in Prune Prune deletes the oldest transmissions by seq_nr while Delete removes them by transmission_hash. Run concurrently, the two paths can hold locks on rows the other wants and Postgres reports 40P01. Select Prune's batch and final-truncate candidates with FOR UPDATE SKIP LOCKED. Prune is best-effort, so skipping a row that is being deleted right now is fine; it is reaped on the next cycle. Delete keeps blocking because its caller has already removed those transmissions from the in-memory queue. The final truncate no longer uses a window function, because FOR UPDATE cannot be combined with one. The partition there was constant (don_id and server_url are fixed), so OFFSET is equivalent. --- .changeset/llo-transmit-queue-deadlock.md | 5 + llo/transmitter/dataengine/orm.go | 33 ++++--- llo/transmitter/dataengine/orm_test.go | 115 ++++++++++++++++++++++ mercury/testutils/sql.go | 66 ++++++++++--- 4 files changed, 194 insertions(+), 25 deletions(-) create mode 100644 .changeset/llo-transmit-queue-deadlock.md diff --git a/.changeset/llo-transmit-queue-deadlock.md b/.changeset/llo-transmit-queue-deadlock.md new file mode 100644 index 00000000..110f59c5 --- /dev/null +++ b/.changeset/llo-transmit-queue-deadlock.md @@ -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. diff --git a/llo/transmitter/dataengine/orm.go b/llo/transmitter/dataengine/orm.go index 53e842f9..d3096690 100644 --- a/llo/transmitter/dataengine/orm.go +++ b/llo/transmitter/dataengine/orm.go @@ -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, ` @@ -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) @@ -235,19 +243,20 @@ WHERE q.transmission_hash = to_delete.transmission_hash; // This query to trim off the final few rows to reach exactly maxSize with // should now be fast and efficient because of the batch deletes that // already completed above. + // + // The window function version of this query cannot take FOR UPDATE, so it + // is expressed as an OFFSET instead; the partition in the original query + // was constant because don_id and server_url are fixed here. 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 - 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 ctid IN ( + SELECT ctid + 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 +); `, o.donID, serverURL, maxSize) if err != nil { diff --git a/llo/transmitter/dataengine/orm_test.go b/llo/transmitter/dataengine/orm_test.go index b0d5b2a4..e810e0db 100644 --- a/llo/transmitter/dataengine/orm_test.go +++ b/llo/transmitter/dataengine/orm_test.go @@ -1,6 +1,7 @@ package dataengine import ( + "sync" "testing" "time" @@ -145,3 +146,117 @@ 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, exactly like an in-flight Delete would. + tx, err := lockDS.BeginTxx(ctx, nil) + require.NoError(t, err) + t.Cleanup(func() { _ = tx.Rollback() }) + require.NoError(t, tx.GetContext(ctx, new([]byte), + `SELECT transmission_hash FROM llo_mercury_transmit_queue + WHERE don_id = $1 AND server_url = $2 AND seq_nr = 0 + FOR UPDATE`, donID, sURL)) + + // Prune must not block on the locked row. It deletes everything it can and leaves that row to the Delete + // that is already removing it. If it 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") + } +} diff --git a/mercury/testutils/sql.go b/mercury/testutils/sql.go index 8bb6a326..450574f4 100644 --- a/mercury/testutils/sql.go +++ b/mercury/testutils/sql.go @@ -44,23 +44,63 @@ 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 { + ctx := tests.Context(t) + newDBURL := newIndependentDBURL(t) + + dbs := make([]*sqlx.DB, n) + for i := range dbs { + 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[i] = db + } + + return dbs +} +// 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 { ctx := tests.Context(t) + newDBURL := newIndependentDBURL(t) + + sessions := make([]*sqlx.DB, n) + for i := range sessions { + db, err := pg.DBConfig{ + IdleInTxSessionTimeout: time.Hour, + LockTimeout: 10 * time.Second, + MaxOpenConns: 1, + MaxIdleConns: 1, + }.New(ctx, newDBURL.String(), pg.DriverPostgres) + require.NoError(t, err) + t.Cleanup(func() { assert.NoError(t, db.Close()) }) + sessions[i] = db + } + + return sessions +} + +func newIndependentDBURL(t testing.TB) url.URL { + SkipShortDB(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()) }) - - return db + return sqltest.CreateOrReplace(t, *dbURL, dbName, pristineDBName) } From fc46435baa8d05f7816d3dc2b2d5fbd88ae18b7c Mon Sep 17 00:00:00 2001 From: Adam Hamrick Date: Fri, 30 Oct 2026 13:10:08 -0400 Subject: [PATCH 2/3] fix(llo): lock only excess rows in Prune final truncate; dedupe testutils DB creation --- llo/transmitter/dataengine/orm.go | 29 +++++++----- llo/transmitter/dataengine/orm_test.go | 20 +++++---- mercury/testutils/sql.go | 61 +++++++++++--------------- 3 files changed, 55 insertions(+), 55 deletions(-) diff --git a/llo/transmitter/dataengine/orm.go b/llo/transmitter/dataengine/orm.go index d3096690..0052a9eb 100644 --- a/llo/transmitter/dataengine/orm.go +++ b/llo/transmitter/dataengine/orm.go @@ -240,23 +240,30 @@ 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. // - // The window function version of this query cannot take FOR UPDATE, so it - // is expressed as an OFFSET instead; the partition in the original query - // was constant because don_id and server_url are fixed here. + // 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, ` -DELETE FROM llo_mercury_transmit_queue -WHERE ctid IN ( - SELECT ctid +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 - ORDER BY seq_nr DESC, inserted_at DESC - OFFSET $3 + WHERE 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 { diff --git a/llo/transmitter/dataengine/orm_test.go b/llo/transmitter/dataengine/orm_test.go index e810e0db..e1e70ce7 100644 --- a/llo/transmitter/dataengine/orm_test.go +++ b/llo/transmitter/dataengine/orm_test.go @@ -164,18 +164,22 @@ func TestORM_PruneSkipsRowsLockedByDelete(t *testing.T) { transmissions := makeSampleTransmissions(n, sURL) require.NoError(t, NewORM(lockDS, donID).Insert(ctx, transmissions)) - // Hold a lock on the oldest row, exactly like an in-flight Delete would. + // 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() }) - require.NoError(t, tx.GetContext(ctx, new([]byte), + 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 = 0 - FOR UPDATE`, donID, sURL)) - - // Prune must not block on the locked row. It deletes everything it can and leaves that row to the Delete - // that is already removing it. If it 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. + 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 diff --git a/mercury/testutils/sql.go b/mercury/testutils/sql.go index 450574f4..d98c1a27 100644 --- a/mercury/testutils/sql.go +++ b/mercury/testutils/sql.go @@ -51,23 +51,12 @@ func NewIndependentSqlxDB(t testing.TB) *sqlx.DB { // 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 { - ctx := tests.Context(t) - newDBURL := newIndependentDBURL(t) - - dbs := make([]*sqlx.DB, n) - for i := range dbs { - 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[i] = db - } - - return dbs + 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 @@ -77,30 +66,30 @@ func NewIndependentSqlxDBs(t testing.TB, n int) []*sqlx.DB { // // 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 { - ctx := tests.Context(t) - newDBURL := newIndependentDBURL(t) - - sessions := make([]*sqlx.DB, n) - for i := range sessions { - db, err := pg.DBConfig{ - IdleInTxSessionTimeout: time.Hour, - LockTimeout: 10 * time.Second, - MaxOpenConns: 1, - MaxIdleConns: 1, - }.New(ctx, newDBURL.String(), pg.DriverPostgres) - require.NoError(t, err) - t.Cleanup(func() { assert.NoError(t, db.Close()) }) - sessions[i] = db - } - - return sessions + return newIndependentSqlxDBs(t, n, pg.DBConfig{ + IdleInTxSessionTimeout: time.Hour, + LockTimeout: 10 * time.Second, + MaxOpenConns: 1, + MaxIdleConns: 1, + }) } -func newIndependentDBURL(t testing.TB) url.URL { +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(), "-", "") - return sqltest.CreateOrReplace(t, *dbURL, dbName, pristineDBName) + newDBURL := sqltest.CreateOrReplace(t, *dbURL, dbName, pristineDBName) + + 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 dbs } From 8b1ca6394cb84686ce744a205ed1270b3e417d17 Mon Sep 17 00:00:00 2001 From: Adam Hamrick Date: Tue, 3 Nov 2026 10:16:05 -0500 Subject: [PATCH 3/3] fix(llo): scope middle truncate lock query by don_id and server_url --- llo/transmitter/dataengine/orm.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/llo/transmitter/dataengine/orm.go b/llo/transmitter/dataengine/orm.go index 0052a9eb..0e461f21 100644 --- a/llo/transmitter/dataengine/orm.go +++ b/llo/transmitter/dataengine/orm.go @@ -254,7 +254,8 @@ DELETE FROM llo_mercury_transmit_queue AS q USING ( SELECT transmission_hash FROM llo_mercury_transmit_queue - WHERE transmission_hash IN ( + 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