Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,27 @@
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.
*
* <p>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.
*
* <p>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<RuntimeException> failure;
private final BooleanSupplier inScope;
private final Predicate<StatementContext> inScope;

/**
* Exactly-once is a contract, not an optimisation: a probe that fires twice fails an operation the
Expand All @@ -35,16 +33,65 @@ 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<RuntimeException> 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.
*
* <p>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<RuntimeException> failure,
final Predicate<StatementContext> statement) {
return new SqlFailureProbe(
jdbi,
fragment,
failure,
context -> RequestLatencyContext.getContext() != null && statement.test(context));
}
Comment thread
harshach marked this conversation as resolved.
Resolved

/**
* The failure shape {@code DeadlockRetry} replays — SQLSTATE 40001, vendor code 1213 — for use as
* the {@code failure} argument of any constructor here.
*
* <p>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:
*
* <pre>{@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)
* }</pre>
*
* <p>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 Supplier<RuntimeException> deadlock() {
return () ->
new RuntimeException(
"Injected deadlock after SQL write", new SQLException("Deadlock", "40001", 1213));
}

SqlFailureProbe(
final Jdbi jdbi,
final String fragment,
final Supplier<RuntimeException> failure,
final BooleanSupplier inScope) {
final Predicate<StatementContext> inScope) {
this.jdbi = jdbi;
this.delegate = jdbi.getConfig(SqlStatements.class).getSqlLogger();
this.fragment = fragment.toLowerCase(Locale.ROOT);
Expand All @@ -63,15 +110,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<StatementContext> callingThread() {
final Thread owner = Thread.currentThread();
return () -> Thread.currentThread() == owner;
return ignored -> Thread.currentThread() == owner;
}

@Override
Expand All @@ -82,8 +137,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;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -13,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 {
Expand All @@ -34,11 +39,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");
}
}
Expand All @@ -47,10 +52,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 (?)"));
}
}

Expand All @@ -62,7 +67,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();
}
});
Expand Down Expand Up @@ -91,7 +96,7 @@ void exactlyOneOfTwoThreadsInsideTheWindowClaimsTheInjection() throws Exception
jdbi,
"insert into chart_entity",
() -> new IllegalStateException("injected"),
() -> {
ignored -> {
try {
bothInsideTheWindow.await(30, TimeUnit.SECONDS);
} catch (Exception e) {
Expand All @@ -104,7 +109,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 {
Expand Down Expand Up @@ -136,4 +141,67 @@ void restoresTheApplicationSqlLoggerOnClose() {

assertSame(original, jdbi.getConfig(SqlStatements.class).getSqlLogger());
}

@Test
void deadlockRaisesTheShapeDeadlockRetryReplays() {
Jdbi jdbi = unconnectedJdbi();
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");
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");
}
}

@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());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<StatementContext> 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());
}
Expand All @@ -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.
*
* <p>This matches <em>any</em> 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.
* <p>This matches <em>any</em> 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<StatementContext> statement) {
return new SqlQueryCounter(
jdbi,
fragment,
context -> RequestLatencyContext.getContext() != null && statement.test(context));
}

SqlQueryCounter(Jdbi jdbi, String fragment, Predicate<StatementContext> inScope) {
this.jdbi = jdbi;
this.inScope = inScope;
this.delegate = jdbi.getConfig(SqlStatements.class).getSqlLogger();
Expand All @@ -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<StatementContext> 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);
}

Expand Down
Loading
Loading