mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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.
This commit is contained in:
1 parent
0e32c55191
commit
8216c2b382
5 files changed
+210
-3
No files matched your search
+76
@@ -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<BackendResponseCoordinator.GateResult> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String> commands = new ArrayList<>();
|
||||
CompletableFuture<Void> 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<String> before, List<String> after, boolean fragmentNotice) throws Exception {
|
||||
withBridgeSockets((client, bridgeClient, bridgeBackend, backend) -> {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
|
||||
+50
@@ -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 {
|
||||
|
||||
Reference in new issue
Block a user