From 2e12c11c0c01f3abd2d86f775b13172cd801d9aa Mon Sep 17 00:00:00 2001 From: Bryan Frimin Date: Thu, 19 Mar 2026 13:22:50 +0100 Subject: [PATCH] Fix flaky finding e2e tests: move advisory lock outside CTE The pg_advisory_xact_lock inside the WITH clause caused race conditions in READ COMMITTED mode. When a transaction blocked on the lock and resumed after acquiring it, it used a stale snapshot and computed the same reference ID as the previous transaction, violating the unique constraint. Moving the lock to a separate statement before the INSERT ensures the snapshot includes all previously committed data. Signed-off-by: Bryan Frimin --- pkg/coredata/finding.go | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/pkg/coredata/finding.go b/pkg/coredata/finding.go index 592989739..dc5d99bfc 100644 --- a/pkg/coredata/finding.go +++ b/pkg/coredata/finding.go @@ -243,9 +243,19 @@ func (f *Finding) Insert( conn pg.Conn, scope Scoper, ) error { + lockQuery := `SELECT pg_advisory_xact_lock(hashtext(@organization_id::text))` + + lockArgs := pgx.StrictNamedArgs{ + "organization_id": f.OrganizationID, + } + + if _, err := conn.Exec(ctx, lockQuery, lockArgs); err != nil { + return fmt.Errorf("cannot acquire advisory lock: %w", err) + } + q := ` WITH next_ref AS ( - SELECT pg_advisory_xact_lock(hashtext(@organization_id::text)), + SELECT COALESCE( MAX(CAST(SUBSTRING(reference_id FROM 5) AS INTEGER)), 0 @@ -306,7 +316,7 @@ RETURNING reference_id "identified_on": f.IdentifiedOn, "root_cause": f.RootCause, "corrective_action": f.CorrectiveAction, - "owner_id": f.OwnerID, + "owner_id": f.OwnerID, "due_date": f.DueDate, "status": f.Status, "priority": f.Priority,