From 93d54acf184fc71a7d372c3446e7147e216cfc13 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 19 Sep 2026 13:24:29 -0700 Subject: [PATCH 1/4] Scope the JDBI test decorators on Predicate Three PRs in the #32946 stack each carry their own copy of these decorators and now collide with the versions #33539 landed on main: CONFLICT (add/add) SqlQueryCounter.java #33344, #33355 CONFLICT (add/add) SqlFailureProbe.java #33362 Their copies are not gratuitous - they scope on Predicate rather than the BooleanSupplier that merged, and #33344 and #33355 already call the three-argument forRequests and deadlockOnce. This makes main's copy the one they call, so the dedup on rebase is a deletion rather than a rewrite. Predicate is also the better answer to the review on #33539 that forRequests was too broad. A fragment alone cannot tell the request under test apart from a concurrent one running the same SQL; the caller needs a look at each candidate statement. SqlFailureProbe.forRequests therefore returns, but requiring the caller's predicate rather than matching any in-flight request. SqlFailureProbe.deadlockOnce covers #33344's SqlQueryCounter.deadlockOnce so EntityRepositoryGoldenIT becomes a one-line swap. Injection stays in the probe rather than moving into the counter: a counter that also throws is two jobs in one class, and the probe's one-shot claim is already a compareAndSet. 16 unit tests, both guards verified to fail without the code that satisfies them - dropping the predicate gate gives "a matching statement the predicate rejects must not be counted", and replacing the CAS with a check-then-act gives "both threads were past the guard at once ... expected: <1> but was: <2>". Co-Authored-By: Claude Opus 5 (1M context) --- .../openmetadata/it/util/SqlFailureProbe.java | 66 +++++++++++++++---- .../it/util/SqlFailureProbeTest.java | 35 ++++++++-- .../openmetadata/it/util/SqlQueryCounter.java | 39 +++++++---- .../it/util/SqlQueryCounterTest.java | 48 +++++++++++--- 4 files changed, 148 insertions(+), 40 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbe.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbe.java index f3c87888da07..c52875fac261 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbe.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbe.java @@ -3,12 +3,13 @@ import java.sql.SQLException; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.BooleanSupplier; +import java.util.function.Predicate; import java.util.function.Supplier; import org.jdbi.v3.core.Jdbi; import org.jdbi.v3.core.statement.SqlLogger; import org.jdbi.v3.core.statement.SqlStatements; import org.jdbi.v3.core.statement.StatementContext; +import org.openmetadata.service.monitoring.RequestLatencyContext; /** * Fails a real SQL operation after execution, once, without affecting background jobs. @@ -16,16 +17,13 @@ *

The failure is thrown from {@code logAfterExecution}, so the statement really did run before * the caller sees the error — which is what makes it usable for atomicity tests: the rollback has * something to undo. - * - *

Scoped to the installing thread. The probe sits on the application-wide Jdbi, so without a - * scope it would fire on whichever background job happened to run a matching statement first. */ public final class SqlFailureProbe implements SqlLogger, AutoCloseable { private final Jdbi jdbi; private final SqlLogger delegate; private final String fragment; private final Supplier failure; - private final BooleanSupplier inScope; + private final Predicate inScope; /** * Exactly-once is a contract, not an optimisation: a probe that fires twice fails an operation the @@ -35,16 +33,51 @@ public final class SqlFailureProbe implements SqlLogger, AutoCloseable { */ private final AtomicBoolean injected = new AtomicBoolean(); + /** Fails the first matching statement issued on the calling thread. */ public SqlFailureProbe( final Jdbi jdbi, final String fragment, final Supplier failure) { this(jdbi, fragment, failure, callingThread()); } + /** + * Fails the first matching statement issued while serving an HTTP request, for tests that drive + * the server over REST and so cannot use the calling thread as the scope. + * + *

The caller supplies {@code statement} to identify the request under test. {@link + * RequestLatencyContext} carries no test identity, so scoping on "some request is in flight" + * alone would let a concurrent request consume the injection and leave the target request + * succeeding — pass a predicate that inspects the statement's SQL, bindings or attributes. + */ + public static SqlFailureProbe forRequests( + final Jdbi jdbi, + final String fragment, + final Supplier failure, + final Predicate statement) { + return new SqlFailureProbe( + jdbi, + fragment, + failure, + context -> RequestLatencyContext.getContext() != null && statement.test(context)); + } + + /** + * Injects a deadlock (SQLSTATE 40001 / MySQL 1213) after the first matching statement, the shape + * {@code DeadlockRetry} is expected to replay. + */ + public static SqlFailureProbe deadlockOnce(final Jdbi jdbi, final String fragment) { + return new SqlFailureProbe( + jdbi, + fragment, + () -> + new RuntimeException( + "Injected deadlock after SQL write", new SQLException("Deadlock", "40001", 1213))); + } + SqlFailureProbe( final Jdbi jdbi, final String fragment, final Supplier failure, - final BooleanSupplier inScope) { + final Predicate inScope) { this.jdbi = jdbi; this.delegate = jdbi.getConfig(SqlStatements.class).getSqlLogger(); this.fragment = fragment.toLowerCase(Locale.ROOT); @@ -63,15 +96,23 @@ public boolean injected() { * #logAfterExecution} so the match, the scope and the exactly-once claim can be exercised without * a database. */ - boolean claimInjection(final String renderedSql) { - return inScope.getAsBoolean() + boolean claimInjection(final StatementContext context, final String renderedSql) { + return inScope.test(context) && renderedSql.toLowerCase(Locale.ROOT).contains(fragment) && injected.compareAndSet(false, true); } - private static BooleanSupplier callingThread() { + /** + * The failure this probe would raise for a statement, or {@code null} when it declines to claim + * it. Lets a test assert on the configured failure without a database to trigger it. + */ + RuntimeException failureFor(final StatementContext context, final String renderedSql) { + return claimInjection(context, renderedSql) ? failure.get() : null; + } + + private static Predicate callingThread() { final Thread owner = Thread.currentThread(); - return () -> Thread.currentThread() == owner; + return ignored -> Thread.currentThread() == owner; } @Override @@ -82,8 +123,9 @@ public void logBeforeExecution(final StatementContext context) { @Override public void logAfterExecution(final StatementContext context) { delegate.logAfterExecution(context); - if (claimInjection(context.getRenderedSql())) { - throw failure.get(); + final RuntimeException injectedFailure = failureFor(context, context.getRenderedSql()); + if (injectedFailure != null) { + throw injectedFailure; } } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbeTest.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbeTest.java index a4535b6cbdb4..d0be5b19f22f 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbeTest.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbeTest.java @@ -2,9 +2,13 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.sql.SQLException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.TimeUnit; @@ -34,11 +38,11 @@ void claimsTheInjectionOnceForAMatchingStatement() { try (var probe = probe(jdbi, "insert into chart_entity")) { assertFalse(probe.injected()); - assertTrue(probe.claimInjection("INSERT INTO chart_entity (id, json) VALUES (?, ?)")); + assertTrue(probe.claimInjection(null, "INSERT INTO chart_entity (id, json) VALUES (?, ?)")); assertTrue(probe.injected()); assertFalse( - probe.claimInjection("insert into chart_entity (id, json) values (?, ?)"), + probe.claimInjection(null, "insert into chart_entity (id, json) values (?, ?)"), "a spent probe must let the retry through, or the replay can never succeed"); } } @@ -47,10 +51,10 @@ void claimsTheInjectionOnceForAMatchingStatement() { void doesNotSpendItselfOnAStatementThatDoesNotMatch() { Jdbi jdbi = unconnectedJdbi(); try (var probe = probe(jdbi, "insert into chart_entity")) { - assertFalse(probe.claimInjection("insert into table_entity (id) values (?)")); + assertFalse(probe.claimInjection(null, "insert into table_entity (id) values (?)")); assertFalse(probe.injected()); - assertTrue(probe.claimInjection("insert into chart_entity (id) values (?)")); + assertTrue(probe.claimInjection(null, "insert into chart_entity (id) values (?)")); } } @@ -62,7 +66,7 @@ void ignoresStatementsFromOtherThreads() throws Exception { Thread background = new Thread( () -> { - if (probe.claimInjection("insert into chart_entity (id) values (?)")) { + if (probe.claimInjection(null, "insert into chart_entity (id) values (?)")) { claimed.incrementAndGet(); } }); @@ -91,7 +95,7 @@ void exactlyOneOfTwoThreadsInsideTheWindowClaimsTheInjection() throws Exception jdbi, "insert into chart_entity", () -> new IllegalStateException("injected"), - () -> { + ignored -> { try { bothInsideTheWindow.await(30, TimeUnit.SECONDS); } catch (Exception e) { @@ -104,7 +108,7 @@ void exactlyOneOfTwoThreadsInsideTheWindowClaimsTheInjection() throws Exception new Thread( () -> { try { - if (probe.claimInjection("insert into chart_entity (id) values (?)")) { + if (probe.claimInjection(null, "insert into chart_entity (id) values (?)")) { claims.incrementAndGet(); } } finally { @@ -136,4 +140,21 @@ void restoresTheApplicationSqlLoggerOnClose() { assertSame(original, jdbi.getConfig(SqlStatements.class).getSqlLogger()); } + + @Test + void deadlockOnceRaisesTheShapeDeadlockRetryReplays() { + Jdbi jdbi = unconnectedJdbi(); + try (var probe = SqlFailureProbe.deadlockOnce(jdbi, "update chart_entity")) { + RuntimeException raised = probe.failureFor(null, "update chart_entity set json = ?"); + + assertNotNull(raised, "the probe must claim a matching statement"); + SQLException cause = assertInstanceOf(SQLException.class, raised.getCause()); + assertEquals("40001", cause.getSQLState(), "DeadlockRetry keys off SQLSTATE 40001"); + assertEquals(1213, cause.getErrorCode(), "and off MySQL error code 1213"); + + assertNull( + probe.failureFor(null, "update chart_entity set json = ?"), + "a spent probe must let the replay through"); + } + } } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlQueryCounter.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlQueryCounter.java index d5af52da32a6..fe6f201e6f2a 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlQueryCounter.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlQueryCounter.java @@ -3,7 +3,7 @@ import java.sql.SQLException; import java.util.Locale; import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.BooleanSupplier; +import java.util.function.Predicate; import org.jdbi.v3.core.Jdbi; import org.jdbi.v3.core.statement.SqlLogger; import org.jdbi.v3.core.statement.SqlStatements; @@ -15,9 +15,10 @@ public final class SqlQueryCounter implements SqlLogger, AutoCloseable { private final Jdbi jdbi; private final SqlLogger delegate; private final String fragment; - private final BooleanSupplier inScope; + private final Predicate inScope; private final AtomicInteger count = new AtomicInteger(); + /** Counts statements issued on the calling thread, so background jobs cannot contribute. */ public SqlQueryCounter(Jdbi jdbi, String fragment) { this(jdbi, fragment, callingThread()); } @@ -26,16 +27,28 @@ public SqlQueryCounter(Jdbi jdbi, String fragment) { * Counts statements issued while serving an HTTP request, for tests that drive the server over * REST and so cannot use the calling thread as the scope. * - *

This matches any in-flight request, not the one under test — the probe is installed - * on the application-wide Jdbi and {@link RequestLatencyContext} carries no test identity. Use it - * only from an {@code @Isolated} test, and pick a fragment specific enough that a background app - * cannot contribute to the count. + *

This matches any in-flight request. {@link RequestLatencyContext} carries no test + * identity, so if another request can run a statement matching {@code fragment} concurrently, use + * {@link #forRequests(Jdbi, String, Predicate)} and discriminate on the statement itself. */ public static SqlQueryCounter forRequests(final Jdbi jdbi, final String fragment) { - return new SqlQueryCounter(jdbi, fragment, () -> RequestLatencyContext.getContext() != null); + return forRequests(jdbi, fragment, ignored -> true); } - SqlQueryCounter(Jdbi jdbi, String fragment, BooleanSupplier inScope) { + /** + * As {@link #forRequests(Jdbi, String)}, but the caller narrows the scope further by inspecting + * the statement — its rendered SQL, bindings or attributes — so a concurrent request cannot be + * counted as if it were the one under test. + */ + public static SqlQueryCounter forRequests( + final Jdbi jdbi, final String fragment, final Predicate statement) { + return new SqlQueryCounter( + jdbi, + fragment, + context -> RequestLatencyContext.getContext() != null && statement.test(context)); + } + + SqlQueryCounter(Jdbi jdbi, String fragment, Predicate inScope) { this.jdbi = jdbi; this.inScope = inScope; this.delegate = jdbi.getConfig(SqlStatements.class).getSqlLogger(); @@ -51,22 +64,22 @@ public int count() { * Counts a statement if it is in scope and matches. Separated from {@link #logBeforeExecution} so * the match and the scope can be exercised without a database. */ - boolean record(final String renderedSql) { - if (inScope.getAsBoolean() && renderedSql.toLowerCase(Locale.ROOT).contains(fragment)) { + boolean record(final StatementContext context, final String renderedSql) { + if (inScope.test(context) && renderedSql.toLowerCase(Locale.ROOT).contains(fragment)) { count.incrementAndGet(); return true; } return false; } - private static BooleanSupplier callingThread() { + private static Predicate callingThread() { final Thread owner = Thread.currentThread(); - return () -> Thread.currentThread() == owner; + return ignored -> Thread.currentThread() == owner; } @Override public void logBeforeExecution(StatementContext context) { - record(context.getRenderedSql()); + record(context, context.getRenderedSql()); delegate.logBeforeExecution(context); } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlQueryCounterTest.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlQueryCounterTest.java index 7e465847eb88..5e05448b2528 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlQueryCounterTest.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlQueryCounterTest.java @@ -7,6 +7,8 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import org.jdbi.v3.core.Jdbi; import org.jdbi.v3.core.statement.SqlLogger; import org.jdbi.v3.core.statement.SqlStatements; @@ -30,9 +32,9 @@ private static Jdbi unconnectedJdbi() { void countsOnlyStatementsContainingTheFragment() { Jdbi jdbi = unconnectedJdbi(); try (var counter = new SqlQueryCounter(jdbi, "entity_relationship")) { - assertTrue(counter.record("SELECT * FROM entity_relationship WHERE fromId = ?")); - assertTrue(counter.record("delete from entity_relationship")); - assertFalse(counter.record("select * from table_entity")); + assertTrue(counter.record(null, "SELECT * FROM entity_relationship WHERE fromId = ?")); + assertTrue(counter.record(null, "delete from entity_relationship")); + assertFalse(counter.record(null, "select * from table_entity")); assertEquals(2, counter.count()); } @@ -42,7 +44,7 @@ void countsOnlyStatementsContainingTheFragment() { void matchesTheFragmentWithoutRegardToCase() { Jdbi jdbi = unconnectedJdbi(); try (var counter = new SqlQueryCounter(jdbi, "FROM Entity_Relationship")) { - assertTrue(counter.record("select 1 from entity_relationship")); + assertTrue(counter.record(null, "select 1 from entity_relationship")); assertEquals(1, counter.count()); } } @@ -51,7 +53,8 @@ void matchesTheFragmentWithoutRegardToCase() { void ignoresStatementsFromOtherThreads() throws Exception { Jdbi jdbi = unconnectedJdbi(); try (var counter = new SqlQueryCounter(jdbi, "entity_relationship")) { - Thread background = new Thread(() -> counter.record("select * from entity_relationship")); + Thread background = + new Thread(() -> counter.record(null, "select * from entity_relationship")); background.start(); background.join(); @@ -60,7 +63,7 @@ void ignoresStatementsFromOtherThreads() throws Exception { counter.count(), "a background job running the same statement must not pollute the count"); - counter.record("select * from entity_relationship"); + counter.record(null, "select * from entity_relationship"); assertEquals(1, counter.count()); } } @@ -73,14 +76,14 @@ void countsEveryConcurrentStatementWhenTheScopeAdmitsThem() throws Exception { CountDownLatch start = new CountDownLatch(1); CountDownLatch done = new CountDownLatch(threads); - try (var counter = new SqlQueryCounter(jdbi, "entity_relationship", () -> true)) { + try (var counter = new SqlQueryCounter(jdbi, "entity_relationship", ignored -> true)) { for (int i = 0; i < threads; i++) { new Thread( () -> { try { start.await(); for (int n = 0; n < perThread; n++) { - counter.record("select * from entity_relationship"); + counter.record(null, "select * from entity_relationship"); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); @@ -123,4 +126,33 @@ void nestedCountersUnwindInOrder() { assertSame(original, jdbi.getConfig(SqlStatements.class).getSqlLogger()); } + + @Test + void theScopePredicateIsConsultedPerStatement() { + // The reason the scope is a Predicate rather than a plain boolean: a fragment + // alone cannot tell the request under test apart from a concurrent one running the same SQL, so + // the caller has to get a look at each candidate statement. + Jdbi jdbi = unconnectedJdbi(); + AtomicInteger consulted = new AtomicInteger(); + AtomicBoolean admit = new AtomicBoolean(true); + + try (var counter = + new SqlQueryCounter( + jdbi, + "entity_relationship", + context -> { + consulted.incrementAndGet(); + return admit.get(); + })) { + assertTrue(counter.record(null, "select * from entity_relationship")); + + admit.set(false); + assertFalse( + counter.record(null, "select * from entity_relationship"), + "a matching statement the predicate rejects must not be counted"); + + assertEquals(1, counter.count()); + assertEquals(2, consulted.get(), "every matching candidate is offered to the predicate"); + } + } } From abfcd5a37ab8a7001286590da9c7931f675b9418 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 19 Sep 2026 13:42:10 -0700 Subject: [PATCH 2/4] Cover the request-scoped overloads, which nothing exercised Review feedback, and correct: forRequests was called by nothing but itself. The unit tests injected predicates through the package-private constructor and SqlTestDecoratorsIT only used the calling-thread ones, so the composed scope - "a request is in flight AND the caller's predicate accepts" - was the one line in these classes with no coverage. It is also the line where a regression is silent: get it wrong and every REST-driven statement is rejected, or every one is accepted, and a test supplying its own predicate would never notice. RequestLatencyContext.startRequest and clearContext are public statics, so the composition is testable without a server. Four tests, two per class: a matching statement outside any request is not counted or claimed, the same statement inside one is, and a caller predicate that rejects still wins while a request is in flight. Each half is independently guarded. Dropping the request check fails with "no request in flight, so there is nothing to attribute the statement to"; dropping the caller predicate fails with "a request is in flight but the caller's predicate rejects this statement". Verified both ways. 20 unit tests total. Co-Authored-By: Claude Opus 5 (1M context) --- .../it/util/SqlFailureProbeTest.java | 47 +++++++++++++++++++ .../it/util/SqlQueryCounterTest.java | 45 ++++++++++++++++++ 2 files changed, 92 insertions(+) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbeTest.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbeTest.java index d0be5b19f22f..e2d1f267a011 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbeTest.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbeTest.java @@ -17,6 +17,7 @@ import org.jdbi.v3.core.statement.SqlLogger; import org.jdbi.v3.core.statement.SqlStatements; import org.junit.jupiter.api.Test; +import org.openmetadata.service.monitoring.RequestLatencyContext; /** Exactly-once is the probe's whole contract; these pin it, including under concurrency. */ class SqlFailureProbeTest { @@ -157,4 +158,50 @@ void deadlockOnceRaisesTheShapeDeadlockRetryReplays() { "a spent probe must let the replay through"); } } + + @Test + void forRequestsClaimsNothingOutsideARequest() { + Jdbi jdbi = unconnectedJdbi(); + try (var probe = + SqlFailureProbe.forRequests( + jdbi, + "insert into chart_entity", + () -> new IllegalStateException("injected"), + ignored -> true)) { + assertFalse( + probe.claimInjection(null, "insert into chart_entity (id) values (?)"), + "no request in flight, so the probe must not spend itself"); + assertFalse(probe.injected()); + + RequestLatencyContext.startRequest("/v1/test", "POST"); + try { + assertTrue(probe.claimInjection(null, "insert into chart_entity (id) values (?)")); + } finally { + RequestLatencyContext.clearContext(); + } + assertTrue(probe.injected()); + } + } + + @Test + void forRequestsStillHonoursTheCallerPredicate() { + Jdbi jdbi = unconnectedJdbi(); + try (var probe = + SqlFailureProbe.forRequests( + jdbi, + "insert into chart_entity", + () -> new IllegalStateException("injected"), + ignored -> false)) { + RequestLatencyContext.startRequest("/v1/test", "POST"); + try { + assertFalse( + probe.claimInjection(null, "insert into chart_entity (id) values (?)"), + "a request is in flight but the caller's predicate rejects this statement — the point" + + " of the overload is that a concurrent request cannot consume the injection"); + } finally { + RequestLatencyContext.clearContext(); + } + assertFalse(probe.injected()); + } + } } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlQueryCounterTest.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlQueryCounterTest.java index 5e05448b2528..b11e3631ff08 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlQueryCounterTest.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlQueryCounterTest.java @@ -13,6 +13,7 @@ import org.jdbi.v3.core.statement.SqlLogger; import org.jdbi.v3.core.statement.SqlStatements; import org.junit.jupiter.api.Test; +import org.openmetadata.service.monitoring.RequestLatencyContext; /** * The counter is a measuring instrument: if it miscounts, every SQL-count assertion built on it is @@ -155,4 +156,48 @@ void theScopePredicateIsConsultedPerStatement() { assertEquals(2, consulted.get(), "every matching candidate is offered to the predicate"); } } + + @Test + void forRequestsCountsNothingOutsideARequest() { + // The composed scope is `a request is in flight AND the caller's predicate accepts`. Tested + // through forRequests rather than by injecting a predicate, because the composition itself is + // the part that can regress: get it wrong and every REST-driven statement is rejected, or + // every one is accepted, and no test that supplies its own predicate would notice. + Jdbi jdbi = unconnectedJdbi(); + try (var counter = SqlQueryCounter.forRequests(jdbi, "entity_relationship")) { + assertFalse( + counter.record(null, "select * from entity_relationship"), + "no request in flight, so there is nothing to attribute the statement to"); + assertEquals(0, counter.count()); + + RequestLatencyContext.startRequest("/v1/test", "GET"); + try { + assertTrue(counter.record(null, "select * from entity_relationship")); + } finally { + RequestLatencyContext.clearContext(); + } + assertEquals(1, counter.count()); + + assertFalse( + counter.record(null, "select * from entity_relationship"), + "the request ended, so later statements fall back out of scope"); + assertEquals(1, counter.count()); + } + } + + @Test + void forRequestsStillHonoursTheCallerPredicate() { + Jdbi jdbi = unconnectedJdbi(); + try (var counter = SqlQueryCounter.forRequests(jdbi, "entity_relationship", ignored -> false)) { + RequestLatencyContext.startRequest("/v1/test", "GET"); + try { + assertFalse( + counter.record(null, "select * from entity_relationship"), + "a request is in flight but the caller's predicate rejects this statement"); + } finally { + RequestLatencyContext.clearContext(); + } + assertEquals(0, counter.count()); + } + } } From 47cf0a81b7f9663e50bf3d124a915f1ee043c272 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 22 Sep 2026 07:21:16 -0700 Subject: [PATCH 3/4] Replace deadlockOnce with a scope-free deadlock() supplier Review follow-up from @manerow, and the trap is real. deadlockOnce built its probe through the calling-thread constructor, while the #33344 factory it was meant to replace is request-scoped. Its only call site, EntityRepositoryGoldenIT, drives a PATCH over REST, so the statement runs on a Jetty worker: a calling-thread probe never fires, and the replay test goes green without ever exercising the replay. Silent false pass, in the one place whose job is to prove a deadlock is retried. A convenience that has to guess a scope will keep guessing wrong, so there is no longer one. deadlock() returns the failure shape DeadlockRetry replays and composes with either scope, which makes the mistake impossible to make by accident: new SqlFailureProbe(jdbi, fragment, deadlock()) // this thread SqlFailureProbe.forRequests(jdbi, fragment, deadlock(), mine::match) // a request Two claims in this PR were also wrong and are corrected in the description. The #33344 call site counts as well as injects - assertEquals(2, writes.count()) - and no factory here does both, so the swap is not one line; it nests a counter around a probe. And SqlQueryCounter.afterFirst is still not provided, so #33344 cannot delete its copy outright either. A new test pins the nesting: the probe sits outermost while both are open, closing it hands the logger back to the counter rather than the application, and the chain unwinds to the original. 21 unit tests. Co-Authored-By: Claude Opus 5 (1M context) --- .../openmetadata/it/util/SqlFailureProbe.java | 32 +++++++++++++------ .../it/util/SqlFailureProbeTest.java | 31 ++++++++++++++++-- 2 files changed, 52 insertions(+), 11 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbe.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbe.java index c52875fac261..991b8c291c10 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbe.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbe.java @@ -61,16 +61,30 @@ public static SqlFailureProbe forRequests( } /** - * Injects a deadlock (SQLSTATE 40001 / MySQL 1213) after the first matching statement, the shape - * {@code DeadlockRetry} is expected to replay. + * The failure shape {@code DeadlockRetry} replays — SQLSTATE 40001, vendor code 1213 — for use as + * the {@code failure} argument of any constructor here. + * + *

Deliberately a supplier rather than a pre-built probe. A {@code deadlockOnce(jdbi, fragment)} + * convenience would have to pick a scope, and picking the wrong one fails silently: a + * calling-thread probe never fires for a statement a REST call runs on a Jetty worker, so the test + * passes without ever exercising the replay. Composing the failure with an explicit scope makes + * that mistake impossible to make by accident: + * + *

{@code
+   * // statement issued on this thread
+   * new SqlFailureProbe(jdbi, "update chart_entity", deadlock())
+   *
+   * // statement issued while serving a request the caller identifies
+   * SqlFailureProbe.forRequests(jdbi, "update chart_entity", deadlock(), mine::matches)
+   * }
+ * + *

To both count statements and inject, nest a {@link SqlQueryCounter} around the probe — each + * decorator delegates to the logger it replaced, so the two compose. */ - public static SqlFailureProbe deadlockOnce(final Jdbi jdbi, final String fragment) { - return new SqlFailureProbe( - jdbi, - fragment, - () -> - new RuntimeException( - "Injected deadlock after SQL write", new SQLException("Deadlock", "40001", 1213))); + public static Supplier deadlock() { + return () -> + new RuntimeException( + "Injected deadlock after SQL write", new SQLException("Deadlock", "40001", 1213)); } SqlFailureProbe( diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbeTest.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbeTest.java index e2d1f267a011..1eea16c343ac 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbeTest.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbeTest.java @@ -143,9 +143,9 @@ void restoresTheApplicationSqlLoggerOnClose() { } @Test - void deadlockOnceRaisesTheShapeDeadlockRetryReplays() { + void deadlockRaisesTheShapeDeadlockRetryReplays() { Jdbi jdbi = unconnectedJdbi(); - try (var probe = SqlFailureProbe.deadlockOnce(jdbi, "update chart_entity")) { + try (var probe = new SqlFailureProbe(jdbi, "update chart_entity", SqlFailureProbe.deadlock())) { RuntimeException raised = probe.failureFor(null, "update chart_entity set json = ?"); assertNotNull(raised, "the probe must claim a matching statement"); @@ -204,4 +204,31 @@ void forRequestsStillHonoursTheCallerPredicate() { assertFalse(probe.injected()); } } + + @Test + void aCounterAndAProbeNestOnTheSameJdbi() { + // The migration path for a call site that both counts and injects, now that no single factory + // does both: each decorator delegates to the logger it replaced, so they stack and unwind in + // order. Asserting the chain rather than a count, because driving both ends needs a real + // StatementContext, which is final and cannot be constructed here. + Jdbi jdbi = unconnectedJdbi(); + SqlLogger original = jdbi.getConfig(SqlStatements.class).getSqlLogger(); + + try (var counter = new SqlQueryCounter(jdbi, "update chart_entity")) { + assertSame(counter, jdbi.getConfig(SqlStatements.class).getSqlLogger()); + try (var probe = + new SqlFailureProbe(jdbi, "update chart_entity", SqlFailureProbe.deadlock())) { + assertSame( + probe, + jdbi.getConfig(SqlStatements.class).getSqlLogger(), + "the probe sits outermost while both are open"); + } + assertSame( + counter, + jdbi.getConfig(SqlStatements.class).getSqlLogger(), + "closing the probe hands the logger back to the counter, not to the application"); + } + + assertSame(original, jdbi.getConfig(SqlStatements.class).getSqlLogger()); + } } From 5daa369ef3e197b5f6575f1a91daa3dc86507605 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 22 Sep 2026 07:45:45 -0700 Subject: [PATCH 4/4] Move the composition test to the IT, where it can assert behaviour Review feedback, and correct: assertSame on the SqlLogger chain is wiring, not behaviour, and passes even if delegation stops invoking the inner decorator - the one failure it needed to catch. I had justified it by saying a real StatementContext could not be built here. That was wrong twice over. StatementContext is not final; it has a private constructor that reflection can reach. But the signature is not stable: this module resolves jdbi3-core 3.37.1, whose constructor takes (ConfigRegistry, ExtensionMethod), while 3.47.0 takes a third Type argument. A unit test built on that would break on a minor dependency bump. So the test moves to SqlTestDecoratorsIT, where real statements produce real contexts and no reflection is needed. It now asserts what one statement does to both decorators: the outer probe fires, the inner counter still sees the same statement, and once the probe is spent the counter keeps counting through it. The unit-level wiring assertion is deleted rather than kept alongside. 20 unit tests; the composition case runs in the IT lane. Co-Authored-By: Claude Opus 5 (1M context) --- .../it/tests/SqlTestDecoratorsIT.java | 22 +++++++++++++++ .../it/util/SqlFailureProbeTest.java | 27 ------------------- 2 files changed, 22 insertions(+), 27 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SqlTestDecoratorsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SqlTestDecoratorsIT.java index 1ba96a8c3feb..b36415d33332 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SqlTestDecoratorsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SqlTestDecoratorsIT.java @@ -93,6 +93,28 @@ void probeIgnoresStatementsThatDoNotMatch() { } } + @Test + void aCounterAndAProbeComposeOnTheSameJdbi() { + // The migration for a call site that both counts and injects, now that no single factory does + // both. Asserted on what one real statement does to both decorators rather than on the logger + // chain: a chain assertion passes even if delegation stops invoking the inner decorator, which + // is precisely the failure this needs to catch. + final Jdbi jdbi = Entity.getJdbi(); + try (var counter = new SqlQueryCounter(jdbi, PROBE_FRAGMENT); + var probe = + new SqlFailureProbe( + jdbi, PROBE_FRAGMENT, () -> new IllegalStateException("injected"))) { + + final var thrown = assertThrows(IllegalStateException.class, () -> runProbeQuery(jdbi)); + assertEquals("injected", thrown.getMessage(), "the outer probe fired"); + assertEquals(1, counter.count(), "and the inner counter still saw the same statement"); + + // The probe is spent; the counter keeps counting through it. + assertEquals(1, runProbeQuery(jdbi)); + assertEquals(2, counter.count()); + } + } + @Test void transactionCounterSeparatesCommitsFromRollbacks() { final Jdbi jdbi = Entity.getJdbi(); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbeTest.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbeTest.java index 1eea16c343ac..dfae1454a3e1 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbeTest.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SqlFailureProbeTest.java @@ -204,31 +204,4 @@ void forRequestsStillHonoursTheCallerPredicate() { assertFalse(probe.injected()); } } - - @Test - void aCounterAndAProbeNestOnTheSameJdbi() { - // The migration path for a call site that both counts and injects, now that no single factory - // does both: each decorator delegates to the logger it replaced, so they stack and unwind in - // order. Asserting the chain rather than a count, because driving both ends needs a real - // StatementContext, which is final and cannot be constructed here. - Jdbi jdbi = unconnectedJdbi(); - SqlLogger original = jdbi.getConfig(SqlStatements.class).getSqlLogger(); - - try (var counter = new SqlQueryCounter(jdbi, "update chart_entity")) { - assertSame(counter, jdbi.getConfig(SqlStatements.class).getSqlLogger()); - try (var probe = - new SqlFailureProbe(jdbi, "update chart_entity", SqlFailureProbe.deadlock())) { - assertSame( - probe, - jdbi.getConfig(SqlStatements.class).getSqlLogger(), - "the probe sits outermost while both are open"); - } - assertSame( - counter, - jdbi.getConfig(SqlStatements.class).getSqlLogger(), - "closing the probe hands the logger back to the counter, not to the application"); - } - - assertSame(original, jdbi.getConfig(SqlStatements.class).getSqlLogger()); - } }