fix(redshift): prune Spectrum partitions for binary integer binds (#7912)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-11 13:06:00 -04:00
1 parent 21cfcea3dd
commit 9f8593a062
6 files changed
+194 -31

No files matched your search

+5 -2
View File
@@ -820,8 +820,11 @@ partition, because that backend cannot report where its transaction ends.
A bind parameter (`$1`, `$2`) in a predicate is read as the value the client binds, so a prepared statement
prunes like the same query written with literals. When the statement is parsed its values are not yet known, so
it loads no partition at that point, only enough for PostgreSQL to plan it, and each Bind loads the partitions
its values select. A parameter that is NULL, sent in binary format, or compared in a form Floci does not read
(for example `$1::int`) leaves its predicate out, and the query loads every partition.
its values select. Text values and binary PostgreSQL `int2`, `int4` and `int8` values support pruning, including
pgjdbc's default `setInt` transfer. Binary integers use the type OIDs declared in Parse or returned by the
backend's ParameterDescription when it infers the types. A parameter that is NULL, has an unknown or unsupported
binary type, has an invalid binary width, or is compared in a form Floci does not read (for example `$1::int`)
leaves its predicate out, and the query loads every partition. The original Bind frame is forwarded unchanged.
The partitions loaded inside a transaction block, or by an extended query cycle, are staged for their connection
and recorded as loaded only when the transaction (or the cycle) commits. A rollback, an error or a
`ROLLBACK TO SAVEPOINT` discards them, so nothing is left behind that a later query would trust. Staged
@@ -7,6 +7,7 @@ import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
@@ -151,23 +152,28 @@ public class PostgresWireDecoder {
}
/**
* Text-format values of a Bind's parameters, by position. A NULL or a binary-format value is null: the
* caller cannot read it as a literal. Only a statement that prunes needs them, so they are read apart from
* Values of a Bind's parameters without known type OIDs. Binary values and NULL remain unknown.
* Only a statement that prunes needs them, so they are read apart from
* {@link #decodeBind}. A malformed section gives an empty list: the backend still gets the original frame
* and reports a malformed Bind itself, so it must not fail here.
*/
public List<String> decodeBindParameters(FrontendMessage message) throws IOException {
return decodeBindParameters(message, List.of());
}
/** Binary int2, int4 and int8 values need the types declared by Parse or inferred by the backend. */
public List<String> decodeBindParameters(FrontendMessage message, List<Integer> parameterTypeOids) throws IOException {
BodyCursor cursor = cursorFor(message, 'B');
cursor.readCString();
cursor.readCString();
try {
return readBindParameters(cursor);
return readBindParameters(cursor, parameterTypeOids);
} catch (IOException expected) {
return List.of();
}
}
private static List<String> readBindParameters(BodyCursor cursor) throws IOException {
private static List<String> readBindParameters(BodyCursor cursor, List<Integer> parameterTypeOids) throws IOException {
int formatCount = cursor.readInt16();
int[] formats = new int[formatCount];
for (int i = 0; i < formatCount; i++) {
@@ -189,6 +195,9 @@ public class PostgresWireDecoder {
int format = formatCount == 0 ? 0 : formatCount == 1 ? formats[0] : formats[i];
if (format == 0) {
values.add(new String(cursor.readBytes(length), StandardCharsets.UTF_8));
} else if (format == 1) {
int oid = i < parameterTypeOids.size() ? parameterTypeOids.get(i) : 0;
values.add(readBinaryInteger(cursor, oid, length));
} else {
cursor.skip(length);
values.add(null);
@@ -197,6 +206,38 @@ public class PostgresWireDecoder {
return values;
}
private static String readBinaryInteger(BodyCursor cursor, int oid, int length) throws IOException {
int width = switch (oid) {
case 21 -> Short.BYTES;
case 23 -> Integer.BYTES;
case 20 -> Long.BYTES;
default -> 0;
};
if (width == 0 || length != width) {
cursor.skip(length);
return null;
}
ByteBuffer bytes = ByteBuffer.wrap(cursor.readBytes(length));
long value = switch (width) {
case Short.BYTES -> bytes.getShort();
case Integer.BYTES -> bytes.getInt();
case Long.BYTES -> bytes.getLong();
default -> throw new IOException("Unsupported binary integer width");
};
return Long.toString(value);
}
static List<Integer> decodeParameterDescription(byte[] body) throws IOException {
BodyCursor cursor = new BodyCursor(body);
int count = cursor.readInt16();
List<Integer> types = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
types.add(cursor.readInt32());
}
cursor.requireEnd();
return List.copyOf(types);
}
/** Decode an Execute ({@code 'E'}) message body. */
public ExecuteMessage decodeExecute(FrontendMessage message) throws IOException {
BodyCursor cursor = cursorFor(message, 'E');
@@ -78,7 +78,7 @@ public class RedshiftInterceptingBridge {
private final String databaseUser;
private final UserChanges auditUserChanges = new UserChanges();
private final PostgresExtendedBackendSession relationalBackend;
private final Map<String, PostgresWireDecoder.ParseMessage> relationalStatements = new HashMap<>();
private final Map<String, RelationalStatement> relationalStatements = new HashMap<>();
private final ExtendedQuerySession session = new ExtendedQuerySession();
private final Map<String, SpectrumInterceptor.Plan> spectrumStatements = new HashMap<>();
private final Map<String, SpectrumInterceptor.Plan> spectrumPortals = new HashMap<>();
@@ -384,7 +384,7 @@ public class RedshiftInterceptingBridge {
if (!prepared) {
throw new SpectrumReadException("58030", "Unable to prepare external query");
}
relationalStatements.put(parse.statementName(), parse);
relationalStatements.put(parse.statementName(), new RelationalStatement(parse));
} catch (RuntimeException exception) {
spectrumInterceptor.preparation().finishCycle(relationalBackend);
writeParseSpectrumError(exception);
@@ -416,14 +416,14 @@ public class RedshiftInterceptingBridge {
private void handleBind(PostgresWireDecoder decoder, PostgresWireDecoder.FrontendMessage message,
OutputStream backendOut) throws IOException {
PostgresWireDecoder.BindMessage bind = decoder.decodeBind(message);
PostgresWireDecoder.ParseMessage relational = relationalStatements.get(bind.statementName());
RelationalStatement relational = relationalStatements.get(bind.statementName());
if (relational != null && !coordinator.isDiscardingUntilSync()) {
try {
List<String> parameterValues = decoder.decodeBindParameters(message);
// Parse/Describe responses may be buffered until Flush or Sync; drain them before taking ownership.
write(backendOut, new byte[]{'H', 0, 0, 0, 4});
boolean prepared = runWithBackendOwned(() -> {
spectrumInterceptor.preparation().prepare(relational.sql(), spectrumSession(), relationalBackend,
List<String> parameterValues = decoder.decodeBindParameters(message, relational.parameterTypeOids);
spectrumInterceptor.preparation().prepare(relational.parse.sql(), spectrumSession(), relationalBackend,
parameterValues);
return true;
});
@@ -475,7 +475,17 @@ public class RedshiftInterceptingBridge {
BackendResponseCoordinator.Operation operation = describe.targetType() == 'S'
? BackendResponseCoordinator.Operation.DESCRIBE_STATEMENT
: BackendResponseCoordinator.Operation.DESCRIBE_PORTAL;
coordinator.register(operation, null);
RelationalStatement relational = describe.targetType() == 'S' ? relationalStatements.get(describe.name()) : null;
coordinator.register(operation, null, relational == null ? null : (type, body) -> {
if (type == 't') {
try {
relational.parameterTypeOids = PostgresWireDecoder.decodeParameterDescription(body);
} catch (IOException expected) {
relational.parameterTypeOids = List.of();
LOG.debugv(expected, "Cannot read backend parameter types for statement {0}", describe.name());
}
}
});
write(backendOut, message.toPacketBytes());
}
@@ -1089,13 +1099,19 @@ public class RedshiftInterceptingBridge {
}
}
/**
* Tracks PostgreSQL wire-message boundaries in a byte stream without buffering it. Each backend
* message is {@code type(1) . length(int32, includes itself) . body}. {@link #betweenMessages()}
* is true exactly when the next byte would begin a new message. The callback fires after every
* complete frame and retains only the one-byte {@code ReadyForQuery} status payload.
*/
private static final class RelationalStatement {
private final PostgresWireDecoder.ParseMessage parse;
private volatile List<Integer> parameterTypeOids;
private RelationalStatement(PostgresWireDecoder.ParseMessage parse) {
this.parse = parse;
this.parameterTypeOids = parse.parameterTypeOids();
}
}
/** Tracks frames while retaining bounded command tags, parameter types and ReadyForQuery status. */
static final class WireFrameTracker {
private static final int MAX_PARAMETER_DESCRIPTION_BYTES = 2 + 4 * 0xFFFF;
private final FrameCompletion onFrame;
private int headerBytesSeen = 0;
private final byte[] header = new byte[5];
@@ -1103,7 +1119,7 @@ public class RedshiftInterceptingBridge {
private long declaredBodyLength = 0;
private char pendingType = 0;
private byte readyStatus;
private byte[] commandTag = EMPTY_BODY;
private byte[] retainedBody = EMPTY_BODY;
WireFrameTracker(FrameCompletion onFrame) {
this.onFrame = onFrame;
@@ -1120,8 +1136,8 @@ public class RedshiftInterceptingBridge {
if (pendingType == 'Z' && declaredBodyLength == 1) {
readyStatus = (byte) current;
}
if (pendingType == 'C' && commandTag.length > 0) {
commandTag[(int) (declaredBodyLength - bodyRemaining)] = (byte) current;
if (retainedBody.length > 0) {
retainedBody[(int) (declaredBodyLength - bodyRemaining)] = (byte) current;
}
bodyRemaining--;
if (bodyRemaining == 0) {
@@ -1136,7 +1152,9 @@ public class RedshiftInterceptingBridge {
pendingType = (char) (header[0] & 0xFF);
bodyRemaining = Math.max(0, msgLen - 4);
declaredBodyLength = bodyRemaining;
commandTag = pendingType == 'C' && bodyRemaining <= 128 ? new byte[(int) bodyRemaining] : EMPTY_BODY;
boolean retain = pendingType == 'C' && bodyRemaining <= 128
|| pendingType == 't' && bodyRemaining <= MAX_PARAMETER_DESCRIPTION_BYTES;
retainedBody = retain ? new byte[(int) bodyRemaining] : EMPTY_BODY;
headerBytesSeen = 0;
if (bodyRemaining == 0) {
publishCompletion();
@@ -1147,7 +1165,7 @@ public class RedshiftInterceptingBridge {
private void publishCompletion() {
byte[] body = pendingType == 'Z' && declaredBodyLength == 1
? new byte[]{readyStatus} : pendingType == 'C' ? commandTag : EMPTY_BODY;
? new byte[]{readyStatus} : retainedBody;
onFrame.accept(pendingType, body);
}
}
@@ -23,6 +23,7 @@ import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.postgresql.PGStatement;
@@ -680,9 +681,10 @@ class RedshiftSpectrumIntegrationTest {
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
@CsvSource({"false,false", "true,false", "true,true"})
@Timeout(120)
void readsOnlyThePartitionsTheWhereSelectsOnTheExtendedProtocolAndInATransaction(boolean bindParameters) throws Exception {
void readsOnlyThePartitionsTheWhereSelectsOnTheExtendedProtocolAndInATransaction(
boolean bindParameters, boolean binaryTransfer) throws Exception {
bucket = "spectrum-pruning-ext-" + System.nanoTime();
s3Service.createBucket(bucket, "us-east-1");
s3Service.putObject(bucket, "events/day=1/part-1.csv", "1,10\n2,20\n".getBytes(StandardCharsets.UTF_8),
@@ -730,7 +732,8 @@ class RedshiftSpectrumIntegrationTest {
}
}
String select = bindParameters ? "SELECT SUM(amount) FROM " + schemaName + ".events WHERE day = ?" : selectDayOne;
try (Connection extended = DriverManager.getConnection(baseUrl + "&preferQueryMode=extended&binaryTransfer=false",
String extendedUrl = baseUrl + "&preferQueryMode=extended" + (binaryTransfer ? "" : "&binaryTransfer=false");
try (Connection extended = DriverManager.getConnection(extendedUrl,
"admin", "Secret123");
PreparedStatement query = extended.prepareStatement(select)) {
query.unwrap(PGStatement.class).setPrepareThreshold(1);
@@ -1,6 +1,8 @@
package io.floci.aws.services.redshift.proxy;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -8,6 +10,7 @@ import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
@@ -23,6 +26,45 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class PostgresWireDecoderTest {
@ParameterizedTest
@CsvSource({"21,2,-32768", "21,2,32767", "23,4,-2147483648", "23,4,2147483647", "23,4,0",
"20,8,-9223372036854775808", "20,8,9223372036854775807", "23,4,1"})
void decodesBinaryIntegersUsingTheirDeclaredType(int oid, int width, long value) throws IOException {
byte[] encoded = Arrays.copyOfRange(ByteBuffer.allocate(8).putLong(value).array(), 8 - width, 8);
byte[] body = concat(cString("p"), cString("s"), int16(1), int16(1), int16(1),
int32(width), encoded, int16(0));
assertEquals(List.of(Long.toString(value)), parameters(body, List.of(oid)));
}
@Test
void decodesMixedFormatsWithoutGuessingUnsupportedBinaryTypesOrNullValues() throws IOException {
byte[] body = concat(cString("p"), cString("s"), int16(4), int16(0), int16(1), int16(1), int16(1),
int16(4), int32(2), new byte[]{'1', '2'}, int32(2), new byte[]{-1, -7},
int32(4), int32(42), int32(-1), int16(0));
assertEquals(Arrays.asList("12", "-7", null, null), parameters(body, List.of(23, 21, 25, 20)));
}
@Test
void binaryValuesWithUnknownTypesOrWrongWidthsRemainUnknown() throws IOException {
byte[] body = concat(cString("p"), cString("s"), int16(1), int16(1), int16(3),
int32(3), new byte[]{0, 0, 1}, int32(4), int32(2), int32(4), int32(3), int16(0));
assertEquals(Arrays.asList(null, null, null), parameters(body, List.of(23, 0, 17)));
assertEquals(Arrays.asList(null, null, null), parameters(body, List.of()));
}
@Test
void truncatedBinaryIntegerLeavesTheBindUnknown() throws IOException {
byte[] body = concat(cString("p"), cString("s"), int16(1), int16(1), int16(1), int32(4), new byte[]{0, 1});
assertEquals(List.of(), parameters(body, List.of(23)));
}
@Test
void decodesOnlyCompleteBackendParameterDescriptions() throws IOException {
assertEquals(List.of(23, 20), PostgresWireDecoder.decodeParameterDescription(concat(int16(2), int32(23), int32(20))));
assertThrows(IOException.class, () -> PostgresWireDecoder.decodeParameterDescription(concat(int16(2), int32(23))));
assertThrows(IOException.class, () -> PostgresWireDecoder.decodeParameterDescription(concat(int16(0), int32(23))));
}
@Test
void decodesParseNameSqlAndParameterTypeOids() throws IOException {
byte[] packet = frame('P', concat(
@@ -107,6 +149,11 @@ class PostgresWireDecoderTest {
return decoder.decodeBindParameters(decoder.nextMessage());
}
private static List<String> parameters(byte[] body, List<Integer> typeOids) throws IOException {
PostgresWireDecoder decoder = new PostgresWireDecoder(new ByteArrayInputStream(frame('B', body)));
return decoder.decodeBindParameters(decoder.nextMessage(), typeOids);
}
private static PostgresWireDecoder.BindMessage decodeBind(byte[] body) throws IOException {
PostgresWireDecoder decoder = new PostgresWireDecoder(new ByteArrayInputStream(frame('B', body)));
return decoder.decodeBind(decoder.nextMessage());
@@ -11,6 +11,8 @@ import org.jboss.logging.Logger;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.mockito.Mockito;
import java.io.ByteArrayOutputStream;
@@ -22,6 +24,7 @@ import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
@@ -550,9 +553,10 @@ class RedshiftInterceptingBridgeTest {
assertEquals('T', fromBridge.read());
}
@Test
@ParameterizedTest
@CsvSource({"false,23", "true,23", "true,0", "true,-1"})
@Timeout(20)
void preparesExternalQueriesWithoutValuesAtParseAndWithEachBindBeforeForwarding() throws Exception {
void preparesExternalQueriesWithoutValuesAtParseAndWithEachBindBeforeForwarding(boolean binary, int oid) throws Exception {
String sql = "SELECT SUM(amount) FROM lake.events WHERE day = $1";
SpectrumInterceptor interceptor = inlineMock(SpectrumInterceptor.class);
SpectrumQueryPreparation preparation = mock(SpectrumQueryPreparation.class);
@@ -562,7 +566,8 @@ class RedshiftInterceptingBridgeTest {
testClientEnd.setSoTimeout(5000);
testBackendEnd.setSoTimeout(5000);
InputStream response = testClientEnd.getInputStream();
byte[] parse = PostgresWireDecoder.encodeParse(new PostgresWireDecoder.ParseMessage("s", sql, List.of(23)), sql);
List<Integer> types = oid < 0 ? List.of() : List.of(oid);
byte[] parse = PostgresWireDecoder.encodeParse(new PostgresWireDecoder.ParseMessage("s", sql, types), sql);
testClientEnd.getOutputStream().write(parse);
testClientEnd.getOutputStream().flush();
@@ -573,13 +578,33 @@ class RedshiftInterceptingBridgeTest {
assertEquals('1', response.read());
skipFrameBody(response);
if (oid <= 0) {
byte[] describe = frame('D', concat(new byte[]{'S'}, cString("s")));
testClientEnd.getOutputStream().write(describe);
testClientEnd.getOutputStream().flush();
assertArrayEquals(describe, nextForwarded().toPacketBytes());
}
for (String day : List.of("1", "2")) {
byte[] value = day.getBytes(StandardCharsets.UTF_8);
byte[] bind = frame('B', concat(cString(""), cString("s"), new byte[]{0, 0, 0, 1},
byte[] value = binary ? ByteBuffer.allocate(4).putInt(Integer.parseInt(day)).array()
: day.getBytes(StandardCharsets.UTF_8);
byte[] formats = binary ? new byte[]{0, 1, 0, 1, 0, 1} : new byte[]{0, 0, 0, 1};
byte[] bind = frame('B', concat(cString(""), cString("s"), formats,
ByteBuffer.allocate(4).putInt(value.length).array(), value, new byte[]{0, 0}));
testClientEnd.getOutputStream().write(bind);
testClientEnd.getOutputStream().flush();
assertEquals('H', nextForwarded().type());
if (oid <= 0 && day.equals("1")) {
// Bind is already queued, but the backend has not yet replied to Describe.
byte[] description = frame('t', concat(new byte[]{0, 1}, ByteBuffer.allocate(4).putInt(23).array()));
testBackendEnd.getOutputStream().write(description, 0, 7);
testBackendEnd.getOutputStream().flush();
testBackendEnd.getOutputStream().write(description, 7, description.length - 7);
writeBackendFrame('n', new byte[0]);
assertArrayEquals(description, new PostgresWireDecoder(response).nextMessage().toPacketBytes());
assertEquals('n', response.read());
skipFrameBody(response);
}
assertArrayEquals(bind, nextForwarded().toPacketBytes());
verify(preparation).prepare(eq(sql), any(), any(), eq(List.of(day)));
writeBackendFrame('2', new byte[0]);
@@ -588,6 +613,32 @@ class RedshiftInterceptingBridgeTest {
}
verify(preparation, never()).prepare(anyString(), any(), any());
verify(preparation, times(3)).prepare(eq(sql), any(), any(), any());
if (binary && oid == 0) {
byte[] close = frame('C', concat(new byte[]{'S'}, cString("s")));
testClientEnd.getOutputStream().write(close);
testClientEnd.getOutputStream().flush();
assertArrayEquals(close, nextForwarded().toPacketBytes());
writeBackendFrame('3', new byte[0]);
assertEquals('3', response.read());
skipFrameBody(response);
testClientEnd.getOutputStream().write(parse);
testClientEnd.getOutputStream().flush();
assertEquals('H', nextForwarded().type());
assertArrayEquals(parse, nextForwarded().toPacketBytes());
writeBackendFrame('1', new byte[0]);
assertEquals('1', response.read());
skipFrameBody(response);
byte[] bind = frame('B', concat(cString(""), cString("s"), new byte[]{0, 1, 0, 1, 0, 1},
ByteBuffer.allocate(4).putInt(4).array(), ByteBuffer.allocate(4).putInt(3).array(), new byte[]{0, 0}));
testClientEnd.getOutputStream().write(bind);
testClientEnd.getOutputStream().flush();
assertEquals('H', nextForwarded().type());
assertArrayEquals(bind, nextForwarded().toPacketBytes());
verify(preparation).prepare(eq(sql), any(), any(), eq(Collections.singletonList(null)));
writeBackendFrame('2', new byte[0]);
assertEquals('2', response.read());
skipFrameBody(response);
}
}
@Test