From 8b13c75fa265331dfb98687daadf2075449c6c5d Mon Sep 17 00:00:00 2001 From: Jackson Price <59149601+jprice8@users.noreply.github.com> Date: Mon, 26 Oct 2026 10:48:51 -0500 Subject: [PATCH] fix(redshift): stay queued for backend ownership until the deadline (#6634) * fix(redshift): stay queued for backend ownership until the deadline runWithBackendOwned waited for the fair backend lock 200 ms at a time, the length of the pump's idle read. A wait that ran out while a read was in progress left the queue, and the pump takes the lock back as soon as it releases it, so the request could miss every handoff until the 2 s deadline. Every Simple Query waits for ownership while the Spectrum interceptor inspects it. When the handoffs were missed, the query stalled for the full 2 s, and one over an external table then failed. External-table preparation on Parse and Bind failed with "Unable to prepare external query", a Simple Query S3 COPY or UNLOAD went to PostgreSQL unintercepted and failed there, and closing an abandoned Spectrum cursor kept its temp table until the session ended. The wait now spans the rest of the deadline in one attempt, as the Extended Query Execute paths already do, so the request keeps its place and takes the lock at the pump's next release. The idle check, the mid-frame backoff and the deadline itself are unchanged. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * refactor(redshift): drop the unreachable retry after a timed-out lock wait runWithBackendOwned now waits for the backend lock once, for the rest of the deadline. A timed tryLock returns false only after that whole budget has elapsed, so the deadline check that followed always held and its continue could not run. Return false straight away, with the same warning; behaviour is unchanged. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(redshift): hand the backend lock to the bridge through a constructor RedshiftBackendOwnershipTest replaced the bridge's private final backendLock by reflection, which later JDKs warn about. The public constructors now pass a new fair lock to a private constructor, and a package-private one for tests takes the lock with no services, so the test builds its bridge directly. Production bridges get the same fair lock as before. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(redshift): run the ownership control test on a short budget The control case in RedshiftBackendOwnershipTest, where the pump never releases the lock, sat out the real 2 s ownership deadline on every run. The test constructor now also takes the runWithBackendOwned budget: the control case uses 100 ms, and the handoff case keeps the production 2 s. Production bridges still get PUMP_PARK_WAIT_MS, now package-private so the test can name it. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> --------- Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> --- .../proxy/RedshiftInterceptingBridge.java | 48 +++++-- .../proxy/RedshiftBackendOwnershipTest.java | 133 ++++++++++++++++++ 2 files changed, 170 insertions(+), 11 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftBackendOwnershipTest.java diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftInterceptingBridge.java b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftInterceptingBridge.java index b22fbc5335..6174373b07 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftInterceptingBridge.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftInterceptingBridge.java @@ -56,7 +56,7 @@ public class RedshiftInterceptingBridge { private static final int PUMP_READ_TIMEOUT_MS = 200; private static final int CLIENT_READ_TIMEOUT_MS = 10_000; - private static final long PUMP_PARK_WAIT_MS = 2_000L; + static final long PUMP_PARK_WAIT_MS = 2_000L; /** Bounded read timeout while an exchange owns the backend, so a stalled backend cannot hang the session. */ private static final int EXCHANGE_READ_TIMEOUT_MS = 60_000; private static final long BUSY_BACKOFF_NANOS = 2_000_000L; @@ -82,7 +82,9 @@ public class RedshiftInterceptingBridge { private final Map spectrumCursors = new HashMap<>(); private final BackendResponseCoordinator coordinator = new BackendResponseCoordinator(session); - private final ReentrantLock backendLock = new ReentrantLock(true); + private final ReentrantLock backendLock; + /** Budget of {@link #runWithBackendOwned} only; the Extended Query paths keep {@link #PUMP_PARK_WAIT_MS}. */ + private final long ownershipWaitMillis; private volatile boolean pumpBetweenMessages = true; private volatile boolean pumpFinished = false; private boolean extendedSpectrumError; @@ -132,6 +134,26 @@ public class RedshiftInterceptingBridge { SpectrumInterceptor spectrumInterceptor, String clusterKey, String databaseName, String defaultIamRoleArn, RedshiftAuditLogPublisher auditLogPublisher, String databaseUser) { + this(client, backend, s3Service, iamService, clusterAccountId, iamRoleArns, spectrumInterceptor, + clusterKey, databaseName, defaultIamRoleArn, auditLogPublisher, databaseUser, new ReentrantLock(true), + PUMP_PARK_WAIT_MS); + } + + /** + * For tests: a bridge with no services, whose fair backend lock and {@link #runWithBackendOwned} + * budget the caller supplies. + */ + RedshiftInterceptingBridge(Socket client, Socket backend, ReentrantLock backendLock, long ownershipWaitMillis) { + this(client, backend, null, null, null, List.of(), null, null, null, null, null, null, backendLock, + ownershipWaitMillis); + } + + private RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService, + String clusterAccountId, List iamRoleArns, + SpectrumInterceptor spectrumInterceptor, String clusterKey, String databaseName, + String defaultIamRoleArn, RedshiftAuditLogPublisher auditLogPublisher, + String databaseUser, ReentrantLock backendLock, + long ownershipWaitMillis) { this.client = client; this.backend = backend; this.s3Service = s3Service; @@ -145,6 +167,8 @@ public class RedshiftInterceptingBridge { this.auditLogPublisher = auditLogPublisher; this.databaseUser = databaseUser; this.relationalBackend = new PostgresExtendedBackendSession(backend); + this.backendLock = backendLock; + this.ownershipWaitMillis = ownershipWaitMillis; } private SpectrumSession spectrumSession() { @@ -774,11 +798,12 @@ public class RedshiftInterceptingBridge { /** * Take exclusive ownership of an idle backend at a wire-message boundary, run {@code exchange}, - * then release it. Returns {@code false} if the backend could not be caught idle within - * {@link #PUMP_PARK_WAIT_MS}; the caller must then forward the original {@code 'Q'} unmodified. + * then release it. Returns {@code false} if the backend could not be caught idle within the + * ownership budget ({@link #PUMP_PARK_WAIT_MS} outside tests); the caller must then forward the + * original {@code 'Q'} unmodified. */ boolean runWithBackendOwned(BackendExchange exchange) throws IOException { - long deadlineNanos = System.nanoTime() + PUMP_PARK_WAIT_MS * 1_000_000L; + long deadlineNanos = System.nanoTime() + ownershipWaitMillis * 1_000_000L; while (true) { if (pumpFinished) { return false; @@ -797,17 +822,18 @@ public class RedshiftInterceptingBridge { } boolean locked; try { - locked = backendLock.tryLock(PUMP_READ_TIMEOUT_MS, TimeUnit.MILLISECONDS); + // One queued wait for the rest of the budget: a fair-lock waiter that times out and retries + // can miss every handoff to an idle pump, which takes the lock back as soon as it releases it. + long remainingNanos = Math.max(0L, deadlineNanos - System.nanoTime()); + locked = backendLock.tryLock(remainingNanos, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("interrupted while acquiring the backend lock", e); } if (!locked) { - if (System.nanoTime() >= deadlineNanos) { - LOG.warn("could not take the backend stream in time; forwarding the COPY unintercepted"); - return false; - } - continue; + // A timed tryLock returns false only once the whole remaining budget has elapsed. + LOG.warn("could not take the backend stream in time; forwarding the COPY unintercepted"); + return false; } boolean backendBusy; try { diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftBackendOwnershipTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftBackendOwnershipTest.java new file mode 100644 index 0000000000..333b07736c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftBackendOwnershipTest.java @@ -0,0 +1,133 @@ +package io.github.hectorvent.floci.services.redshift.proxy; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import java.io.IOException; +import java.net.Socket; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.ReentrantLock; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class RedshiftBackendOwnershipTest { + + // Taking ownership only sets the backend socket's read timeout, so unconnected sockets will do. + private final Socket client = new Socket(); + private final Socket backend = new Socket(); + + @AfterEach + void closeSockets() throws IOException { + client.close(); + backend.close(); + } + + /** + * The pump holds the backend lock for each idle read and takes it back as soon as it releases it. A + * waiter whose timed attempt runs out while a read is in progress resumes only after the pump has + * started its next read, so it must stay queued across that read to be handed the backend. + */ + @Test + @Timeout(10) + void retainsItsPlaceWhileAnIdlePumpFinishesReading() throws Exception { + DelayedWaiterLock lock = new DelayedWaiterLock(); + RedshiftInterceptingBridge bridge = new RedshiftInterceptingBridge(client, backend, lock, + RedshiftInterceptingBridge.PUMP_PARK_WAIT_MS); + AtomicBoolean stopped = new AtomicBoolean(); + AtomicReference pumpFailure = new AtomicReference<>(); + Thread pump = Thread.ofVirtual().start(() -> { + try { + while (!stopped.get()) { + lock.lockInterruptibly(); + try { + lock.readStarted.release(); + // Outlasts one 200 ms lock attempt (PUMP_READ_TIMEOUT_MS), well inside the 2 s deadline. + lock.endRead.tryAcquire(350, TimeUnit.MILLISECONDS); + } finally { + lock.unlock(); + } + } + } catch (InterruptedException expected) { + // The test stops the pump by interrupting it. + Thread.currentThread().interrupt(); + } catch (Throwable failure) { + pumpFailure.set(failure); + } + }); + try { + assertTrue(lock.readStarted.tryAcquire(1, TimeUnit.SECONDS)); + assertTrue(bridge.runWithBackendOwned(() -> true), + "an idle pump must yield the backend before the ownership deadline"); + assertNull(pumpFailure.get()); + } finally { + stopped.set(true); + pump.interrupt(); + pump.join(1000); + assertFalse(pump.isAlive()); + } + } + + @Test + @Timeout(10) + void doesNotRunAnExchangeWhenTheBackendRemainsOwned() throws Exception { + ReentrantLock lock = new ReentrantLock(true); + // A short budget is enough to show the call gives up; the handoff case keeps the production one. + RedshiftInterceptingBridge bridge = new RedshiftInterceptingBridge(client, backend, lock, 100); + CountDownLatch held = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + Thread pump = Thread.ofVirtual().start(() -> { + lock.lock(); + try { + held.countDown(); + release.await(); + } catch (InterruptedException expected) { + // Only an interrupt from outside the test could end the wait early; keep its status. + Thread.currentThread().interrupt(); + } finally { + lock.unlock(); + } + }); + try { + assertTrue(held.await(1, TimeUnit.SECONDS)); + AtomicBoolean exchanged = new AtomicBoolean(); + assertFalse(bridge.runWithBackendOwned(() -> { + exchanged.set(true); + return true; + })); + assertFalse(exchanged.get()); + } finally { + release.countDown(); + pump.join(1000); + assertFalse(pump.isAlive()); + } + } + + private static final class DelayedWaiterLock extends ReentrantLock { + private final Semaphore readStarted = new Semaphore(0); + private final Semaphore endRead = new Semaphore(0); + + private DelayedWaiterLock() { + super(true); + } + + @Override + public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { + boolean acquired = super.tryLock(timeout, unit); + if (!acquired) { + // The timed-out waiter resumes only after the pump has finished this read and started the next. + endRead.release(); + if (!readStarted.tryAcquire(1, TimeUnit.SECONDS)) { + throw new AssertionError("pump did not resume"); + } + } + return acquired; + } + } +}