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

@@ -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);
}
}