From 8216c2b3825abafda7a1e7fc2241dcfa70528c6b Mon Sep 17 00:00:00 2001 From: Andre Kurait Date: Tue, 24 Nov 2026 20:02:22 -0600 Subject: [PATCH] fix(redshift): preserve frontend state after an error Sync (#9401) A query pipelined after Sync but before the previous ReadyForQuery could lose its prepared statement and portal during error recovery. The next frontend cycle now starts once Sync is registered or already queued, while its pending response stays the backend ownership barrier. A failed backend cycle is tracked apart from frontend discard mode, so a failed owned COPY transaction still rolls back at Sync, and the SQL needed for user-change audit events is kept. --- .../proxy/BackendResponseCoordinator.java | 19 ++++- .../proxy/RedshiftInterceptingBridge.java | 2 +- ...ackendResponseCoordinatorRecoveryTest.java | 76 +++++++++++++++++++ .../proxy/RedshiftCopyTransactionTest.java | 66 ++++++++++++++++ .../proxy/RedshiftInterceptingBridgeTest.java | 50 ++++++++++++ 5 files changed, 210 insertions(+), 3 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/redshift/proxy/BackendResponseCoordinatorRecoveryTest.java diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/BackendResponseCoordinator.java b/src/main/java/io/floci/aws/services/redshift/proxy/BackendResponseCoordinator.java index ae25130706..45c5b4c50b 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/BackendResponseCoordinator.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/BackendResponseCoordinator.java @@ -18,6 +18,7 @@ final class BackendResponseCoordinator { private final Map resolvedGates = new HashMap<>(); private long nextSequence = 1; private boolean discardingUntilSync; + private boolean extendedCycleFailed; private boolean closed; private char lastReadyStatus = 'I'; @@ -42,6 +43,9 @@ final class BackendResponseCoordinator { } } else { pending.addLast(new PendingOperation(ticket, mutation, response)); + if (operation == Operation.SYNC) { + discardingUntilSync = false; + } } changed.signalAll(); return ticket; @@ -157,7 +161,6 @@ final class BackendResponseCoordinator { pending.removeFirst(); reject(head); resolveSkippedGate(head); - discardingUntilSync = true; discardQueuedOperationsBeforeSync(); } changed.signalAll(); @@ -169,6 +172,7 @@ final class BackendResponseCoordinator { confirm(head); if (operation == Operation.SYNC) { discardingUntilSync = false; + extendedCycleFailed = false; } changed.signalAll(); } @@ -193,7 +197,6 @@ final class BackendResponseCoordinator { pending.remove(owned); confirm(owned); if (failed) { - discardingUntilSync = true; discardQueuedOperationsBeforeSync(); } changed.signalAll(); @@ -222,6 +225,15 @@ final class BackendResponseCoordinator { } } + boolean extendedCycleFailed() { + lock.lock(); + try { + return extendedCycleFailed; + } finally { + lock.unlock(); + } + } + char lastReadyStatus() { lock.lock(); try { @@ -256,11 +268,14 @@ final class BackendResponseCoordinator { } private void discardQueuedOperationsBeforeSync() { + extendedCycleFailed = true; while (!pending.isEmpty() && pending.peekFirst().ticket().operation() != Operation.SYNC) { PendingOperation skipped = pending.removeFirst(); reject(skipped); resolveSkippedGate(skipped); } + // Sync starts the next frontend cycle; its queued response still prevents early backend ownership. + discardingUntilSync = pending.isEmpty(); } private void resolveSkippedGate(PendingOperation operation) { diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridge.java b/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridge.java index eea4dc10b0..7b131213ea 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridge.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridge.java @@ -881,7 +881,7 @@ public class RedshiftInterceptingBridge { } try { backend.setSoTimeout(EXCHANGE_READ_TIMEOUT_MS); - boolean failed = coordinator.isDiscardingUntilSync(); + boolean failed = coordinator.extendedCycleFailed(); try { copyBackend.finish(failed); } catch (S3TransferException e) { diff --git a/src/test/java/io/floci/aws/services/redshift/proxy/BackendResponseCoordinatorRecoveryTest.java b/src/test/java/io/floci/aws/services/redshift/proxy/BackendResponseCoordinatorRecoveryTest.java new file mode 100644 index 0000000000..c665ce447e --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/proxy/BackendResponseCoordinatorRecoveryTest.java @@ -0,0 +1,76 @@ +package io.floci.aws.services.redshift.proxy; + +import io.floci.aws.testing.ThreadStates; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class BackendResponseCoordinatorRecoveryTest { + + @ParameterizedTest + @CsvSource({"false,false", "false,true", "true,false", "true,true"}) + @Timeout(5) + void syncPreservesTheNextCycleWhileItsReadyForQueryIsPending(boolean owned, boolean syncBeforeError) + throws Exception { + ExtendedQuerySession session = new ExtendedQuerySession(); + BackendResponseCoordinator coordinator = new BackendResponseCoordinator(session); + BackendResponseCoordinator.Ticket failed = coordinator.register( + BackendResponseCoordinator.Operation.EXECUTE, null); + if (syncBeforeError) { + coordinator.register(BackendResponseCoordinator.Operation.SYNC, null); + } + if (owned) { + coordinator.completeOwnedExecute(failed, true); + } else { + coordinator.onBackendFrame('E', new byte[0]); + } + if (!syncBeforeError) { + BackendResponseCoordinator.Ticket skipped = coordinator.register( + BackendResponseCoordinator.Operation.EXECUTE, null); + assertEquals(BackendResponseCoordinator.GateResult.SKIPPED_AFTER_ERROR, + coordinator.awaitTurn(skipped)); + coordinator.register(BackendResponseCoordinator.Operation.SYNC, null); + } + + CopyStatementParser.S3Statement nextCopy = CopyStatementParser.parse("COPY t FROM 's3://b/next'"); + coordinator.register(BackendResponseCoordinator.Operation.PARSE, session.stageParse("s", nextCopy)); + coordinator.register(BackendResponseCoordinator.Operation.BIND, session.stageBind("p", "s")); + BackendResponseCoordinator.Ticket next = coordinator.register( + BackendResponseCoordinator.Operation.EXECUTE, null); + + assertSame(nextCopy, session.portal("p").orElseThrow(), + "A Sync already sent to the backend starts a new frontend query cycle"); + assertFalse(coordinator.isDiscardingUntilSync()); + assertTrue(coordinator.extendedCycleFailed(), "Frontend Sync must retain the backend failure"); + assertFalse(coordinator.awaitIdle(1, TimeUnit.MILLISECONDS)); + FutureTask turn = + new FutureTask<>(() -> coordinator.awaitExtendedExecuteTurn(next)); + Thread waiter = Thread.ofVirtual().start(turn); + try { + assertEquals(Thread.State.WAITING, ThreadStates.awaitParkedOrDone(waiter), + "The new Execute must still wait for the previous Sync response"); + coordinator.onBackendFrame('Z', new byte[]{'I'}); + assertFalse(coordinator.extendedCycleFailed(), "ReadyForQuery ends the failed backend cycle"); + assertSame(nextCopy, session.portal("p").orElseThrow()); + coordinator.onBackendFrame('1', new byte[0]); + coordinator.onBackendFrame('2', new byte[0]); + assertEquals(BackendResponseCoordinator.GateResult.READY, turn.get(1, TimeUnit.SECONDS)); + coordinator.completeOwnedExecute(next, false); + coordinator.register(BackendResponseCoordinator.Operation.SYNC, null); + coordinator.onBackendFrame('Z', new byte[]{'I'}); + assertTrue(coordinator.awaitIdle(1, TimeUnit.SECONDS)); + } finally { + coordinator.close(); + waiter.interrupt(); + waiter.join(1000); + } + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/proxy/RedshiftCopyTransactionTest.java b/src/test/java/io/floci/aws/services/redshift/proxy/RedshiftCopyTransactionTest.java index 0125f89cda..cd36a3199c 100644 --- a/src/test/java/io/floci/aws/services/redshift/proxy/RedshiftCopyTransactionTest.java +++ b/src/test/java/io/floci/aws/services/redshift/proxy/RedshiftCopyTransactionTest.java @@ -2,6 +2,9 @@ package io.floci.aws.services.redshift.proxy; import io.floci.aws.core.common.PostgresWire; import io.floci.aws.services.iam.IamService; +import io.floci.aws.services.redshift.spectrum.SpectrumInterceptor; +import io.floci.aws.services.redshift.spectrum.SpectrumReadException; +import io.floci.aws.services.redshift.spectrum.SpectrumSession; import io.floci.aws.services.s3.S3Service; import io.floci.aws.services.s3.model.S3Object; import io.floci.aws.testing.ParallelLocks; @@ -9,6 +12,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.parallel.ResourceAccessMode; import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import java.io.ByteArrayOutputStream; import java.io.FilterInputStream; @@ -20,6 +25,7 @@ import java.net.ServerSocket; import java.net.Socket; import java.net.SocketTimeoutException; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; @@ -27,10 +33,13 @@ import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import static io.floci.aws.testing.InlineMocks.inlineMock; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -196,6 +205,63 @@ class RedshiftCopyTransactionTest { }); } + @ParameterizedTest + @CsvSource({"false,false", "false,true", "true,false", "true,true"}) + void failedCopyCycleRollsBackWhenSyncWasQueuedOrSentAfterError(boolean queuedSync, boolean localFailure) + throws Exception { + withBridgeSockets((client, bridgeClient, bridgeBackend, backend) -> { + S3Service s3 = mock(S3Service.class); + when(s3.objectExists("bucket", "data")).thenReturn(true); + when(s3.getObject("bucket", "data")).thenReturn(new S3Object("bucket", "data", + "1\n".getBytes(StandardCharsets.UTF_8), "text/plain")); + List commands = new ArrayList<>(); + CompletableFuture server = CompletableFuture.runAsync(() -> { + try { + new FakeCopyBackend(backend).serveUntilSync(false, commands::add); + } catch (Exception exception) { + throw new AssertionError(exception); + } + }); + SpectrumInterceptor spectrum = inlineMock(SpectrumInterceptor.class); + SpectrumInterceptor.Plan.Query plan = new SpectrumInterceptor.Plan.Query(null, null, null, "refused"); + when(spectrum.plan(eq("SELECT * FROM external_refused"), any(SpectrumSession.class))).thenReturn(plan); + when(spectrum.execute(eq(plan), eq("000000000000"), eq("dev"), eq(bridgeBackend))) + .thenThrow(new SpectrumReadException("42501", "Local Spectrum permission refusal")); + Thread.ofVirtual().start(new RedshiftInterceptingBridge(bridgeClient, bridgeBackend, s3, + mock(IamService.class), "000000000000", List.of(), spectrum, "000000000000:cluster", "dev")::run); + ByteArrayOutputStream pipeline = new ByteArrayOutputStream(); + statement(pipeline, "copy", "COPY events FROM 's3://bucket/data' MAXERROR 2"); + statement(pipeline, "failure", localFailure ? "SELECT * FROM external_refused" : "SELECT 1 / 0"); + if (queuedSync) { + PostgresWire.write(pipeline, 'S'); + } + client.getOutputStream().write(pipeline.toByteArray()); + client.getOutputStream().flush(); + PostgresWireDecoder decoder = new PostgresWireDecoder(client.getInputStream()); + boolean sawError = false; + while (true) { + PostgresWireDecoder.FrontendMessage response = decoder.nextMessage(); + assertNotNull(response); + if (response.type() == 'E') { + sawError = true; + if (!queuedSync) { + PostgresWire.write(client.getOutputStream(), 'S'); + client.getOutputStream().flush(); + } + } else if (response.type() == 'Z') { + assertEquals('I', response.body()[0]); + break; + } + } + server.get(5, TimeUnit.SECONDS); + assertTrue(sawError); + assertTrue(commands.contains("BEGIN"), "COPY must own the transaction"); + assertEquals(List.of("BEGIN", "ROLLBACK"), commands.stream() + .filter(sql -> sql.equals("BEGIN") || sql.equals("ROLLBACK") || sql.equals("COMMIT")) + .toList(), "A failed owned COPY cycle must roll back, including local Spectrum errors"); + }); + } + private void runCycle(List before, List after, boolean fragmentNotice) throws Exception { withBridgeSockets((client, bridgeClient, bridgeBackend, backend) -> { S3Service s3 = mock(S3Service.class); diff --git a/src/test/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridgeTest.java b/src/test/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridgeTest.java index b1ad14e2c9..141635fa9a 100644 --- a/src/test/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridgeTest.java +++ b/src/test/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridgeTest.java @@ -440,6 +440,56 @@ class RedshiftInterceptingBridgeTest { } } + @Test + @Timeout(10) + void queryAfterErrorSyncBeforeReadyPreservesSqlForAudit() throws Exception { + RedshiftAuditLogPublisher audit = mock(RedshiftAuditLogPublisher.class); + startBridge(null, audit); + testClientEnd.setSoTimeout(3000); + testBackendEnd.setSoTimeout(3000); + PostgresWireDecoder backendDecoder = new PostgresWireDecoder(testBackendEnd.getInputStream()); + PostgresWireDecoder clientDecoder = new PostgresWireDecoder(testClientEnd.getInputStream()); + + sendUnnamedExtendedQuery("INVALID"); + for (char expected : new char[]{'P', 'B', 'D', 'E', 'S'}) { + assertEquals(expected, backendDecoder.nextMessage().type()); + } + writeBackendFrame('E', "SERROR\0C42601\0Msyntax error\0\0".getBytes(StandardCharsets.US_ASCII)); + assertEquals('E', clientDecoder.nextMessage().type()); + + // Hold the prior ReadyForQuery so the next cycle always reaches the proxy during recovery. + sendUnnamedExtendedQuery("CREATE USER after_error"); + PostgresWireDecoder.FrontendMessage nextParse = backendDecoder.nextMessage(); + assertEquals('P', nextParse.type()); + assertTrue(backendDecoder.decodeParse(nextParse).sql().contains("after_error")); + for (char expected : new char[]{'B', 'D', 'E', 'S'}) { + assertEquals(expected, backendDecoder.nextMessage().type()); + } + writeBackendFrame('Z', new byte[]{'I'}); + writeBackendFrame('1', new byte[0]); + writeBackendFrame('2', new byte[0]); + writeBackendFrame('n', new byte[0]); + writeBackendFrame('C', cString("CREATE ROLE")); + writeBackendFrame('Z', new byte[]{'I'}); + for (char expected : new char[]{'Z', '1', '2', 'n', 'C', 'Z'}) { + assertEquals(expected, clientDecoder.nextMessage().type()); + } + verify(audit, timeout(2000)).publishRegisteredUserChange( + "000000000000", "c", "dev", "after_error", "Create", null); + } + + private void sendUnnamedExtendedQuery(String sql) throws IOException { + PostgresWireDecoder.ParseMessage parse = new PostgresWireDecoder.ParseMessage("", sql, List.of()); + ByteArrayOutputStream pipeline = new ByteArrayOutputStream(); + pipeline.write(PostgresWireDecoder.encodeParse(parse, sql)); + pipeline.write(frame('B', new byte[8])); + pipeline.write(frame('D', new byte[]{'P', 0})); + pipeline.write(frame('E', new byte[5])); + pipeline.write(frame('S', new byte[0])); + testClientEnd.getOutputStream().write(pipeline.toByteArray()); + testClientEnd.getOutputStream().flush(); + } + @Test @Timeout(5) void extendedUnloadWithManifestCompletesAfterCopyOutCommandComplete() throws Exception {