feat(redshift): prune Spectrum partitions for bind parameters (#7758) (#7863)

A prepared statement with a predicate on a bound value (WHERE day = $1) loaded every Glue partition, because the pruner read only literals. The Bind message now carries its text-format values, and the pruner reads each $n as the value bound to it.

A statement that is only being parsed has no values yet, so it loads no partition, enough for PostgreSQL to plan it; each Bind loads the partitions its values select. A NULL, binary-format or unreadable value leaves its predicate out and the query loads every partition. A malformed Bind parameter section leaves the values unknown instead of failing the connection.

Parse of a parameterized Spectrum statement no longer deletes partitions by cast key,
which could remove rows of overlapping partitions that stay recorded as loaded; the
Bind reconciles the table. Bind parameters are decoded only when a Spectrum statement
needs them, and binary values are skipped instead of copied.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-10 10:57:23 -04:00
1 parent 9dae9f8036
commit 2964140717
12 files changed
+491 -41

No files matched your search

@@ -9,6 +9,7 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.IntPredicate;
@@ -146,9 +147,54 @@ public class PostgresWireDecoder {
/** Decode the leading names of a Bind ({@code 'B'}) message body. */
public BindMessage decodeBind(FrontendMessage message) throws IOException {
BodyCursor cursor = cursorFor(message, 'B');
String portalName = cursor.readCString();
String statementName = cursor.readCString();
return new BindMessage(portalName, statementName);
return new BindMessage(cursor.readCString(), cursor.readCString());
}
/**
* 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
* {@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 {
BodyCursor cursor = cursorFor(message, 'B');
cursor.readCString();
cursor.readCString();
try {
return readBindParameters(cursor);
} catch (IOException expected) {
return List.of();
}
}
private static List<String> readBindParameters(BodyCursor cursor) throws IOException {
int formatCount = cursor.readInt16();
int[] formats = new int[formatCount];
for (int i = 0; i < formatCount; i++) {
formats[i] = cursor.readInt16();
}
int parameterCount = cursor.readInt16();
if (formatCount > 1 && formatCount != parameterCount) {
throw new IOException("Bind has " + formatCount + " parameter format codes for " + parameterCount
+ " parameters");
}
List<String> values = new ArrayList<>(parameterCount);
for (int i = 0; i < parameterCount; i++) {
int length = cursor.readInt32();
if (length < 0) {
values.add(null);
continue;
}
// zero format codes mean every parameter is text, one applies to all, otherwise one per parameter
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 {
cursor.skip(length);
values.add(null);
}
}
return values;
}
/** Decode an Execute ({@code 'E'}) message body. */
@@ -262,6 +308,18 @@ public class PostgresWireDecoder {
return value;
}
private void skip(int count) throws IOException {
requireRemaining(count);
offset += count;
}
private byte[] readBytes(int count) throws IOException {
requireRemaining(count);
byte[] value = Arrays.copyOfRange(body, offset, offset + count);
offset += count;
return value;
}
private int readInt32() throws IOException {
requireRemaining(4);
int value = ((body[offset] & 0xFF) << 24)
@@ -374,7 +374,8 @@ public class RedshiftInterceptingBridge {
try {
write(backendOut, new byte[]{'H', 0, 0, 0, 4});
boolean prepared = runWithBackendOwned(() -> {
spectrumInterceptor.preparation().prepare(parse.sql(), spectrumSession(), relationalBackend);
// no values yet: a parameterized statement is only planned here, the Bind loads its partitions
spectrumInterceptor.preparation().prepare(parse.sql(), spectrumSession(), relationalBackend, null);
return true;
});
if (!prepared) {
@@ -415,10 +416,12 @@ public class RedshiftInterceptingBridge {
PostgresWireDecoder.ParseMessage 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);
spectrumInterceptor.preparation().prepare(relational.sql(), spectrumSession(), relationalBackend,
parameterValues);
return true;
});
if (!prepared) {
@@ -213,14 +213,26 @@ public class ExternalTableMaterializer {
*/
public Outcome ensureCurrent(BackendSql backend, SpectrumSession session, ExternalSchemaBinding binding,
String tableName, String sql) {
return ensureCurrent(backend, session, binding, tableName, sql, List.of());
}
/**
* As {@link #ensureCurrent(BackendSql, SpectrumSession, ExternalSchemaBinding, String, String)} for a query
* with bind parameters: {@code parameters} holds the text of each bound value, a null where it is unusable.
* Null {@code parameters} means the statement is only being parsed and its values are not known yet; a
* partitioned table then loads no partition, enough for PostgreSQL to plan it, and the Bind loads the ones
* its values select.
*/
public Outcome ensureCurrent(BackendSql backend, SpectrumSession session, ExternalSchemaBinding binding,
String tableName, String sql, List<String> parameters) {
try (ExternalCatalogLocks.Guard ignored = catalogLocks.read(binding,
session.inTransaction() || !backend.permitsCachePublication())) {
return ensureCurrentLocked(backend, session, binding, tableName, sql);
return ensureCurrentLocked(backend, session, binding, tableName, sql, parameters);
}
}
private Outcome ensureCurrentLocked(BackendSql backend, SpectrumSession session, ExternalSchemaBinding binding,
String tableName, String sql) {
String tableName, String sql, List<String> parameters) {
Table table;
try {
table = RequestScopes.callAs(session.accountId(), () -> glueService.getTable(binding.glueDatabase(), tableName));
@@ -240,7 +252,8 @@ public class ExternalTableMaterializer {
authorizeIcebergManifests(session.accountId(), binding, roleSession, table, location);
List<Partition> partitions = partitions(session.accountId(), binding, table);
if (holdsPartitions(table, session, backend, partitions)) {
return ensurePartitions(backend, session, binding, roleSession, table, location, partitions, sql);
return ensurePartitions(backend, session, binding, roleSession, table, location, partitions, sql,
parameters);
}
List<ReadSource> sources = readSources(session.accountId(), binding, roleSession, table, location, partitions);
List<S3Object> objects = sources.stream().flatMap(source -> source.objects().stream()).toList();
@@ -339,13 +352,16 @@ public class ExternalTableMaterializer {
*/
private Outcome ensurePartitions(BackendSql backend, SpectrumSession session, ExternalSchemaBinding binding,
RedshiftRoleAccess.RoleSession roleSession, Table table, Location location,
List<Partition> partitions, String sql) {
List<Partition> partitions, String sql, List<String> parameters) {
String accountId = session.accountId();
Optional<PartitionPruner.Filter> filter = PartitionPruner.filterFor(sql, binding.schemaName(),
table.getName(), table.getPartitionKeys());
table.getName(), table.getPartitionKeys(), parameters);
// partitions that PostgreSQL's casts make equal cannot be told apart by key value, so they are all read
boolean overlapping = hasOverlappingPartitions(table, partitions);
List<Partition> qualified = filter.isEmpty() || overlapping ? partitions
// a statement still being parsed has no values to select with, and its Bind loads what it needs
boolean awaitingValues = parameters == null && PartitionPruner.hasParameters(sql);
List<Partition> qualified = awaitingValues ? List.of()
: filter.isEmpty() || overlapping ? partitions
: partitions.stream().filter(partition -> filter.get().matches(partition.getValues())).toList();
List<ReadSource> sources = readSources(accountId, binding, roleSession, table, location, qualified);
authorizeObjects(accountId, binding, roleSession, sources);
@@ -372,6 +388,11 @@ public class ExternalTableMaterializer {
previousSignature = schemaSignatures.get(cacheKey);
}
boolean reset = state == null || !state.identity().equals(identity) || !definitions.equals(previousSignature);
if (awaitingValues && !reset) {
// a statement still being parsed loads nothing; its Bind reconciles the table, because a delete by
// key value here could remove rows of partitions that stay recorded as loaded
return Outcome.CURRENT;
}
Map<List<String>, String> held = reset ? Map.of() : state.partitions();
Set<List<String>> existing = partitions.stream().map(Partition::getValues).collect(Collectors.toSet());
List<List<String>> deletions = new ArrayList<>(held.keySet().stream()
@@ -390,7 +411,7 @@ public class ExternalTableMaterializer {
loaded.put(values, fingerprint);
}
}
if (overlapping && !reset && (!deletions.isEmpty() || !toLoad.isEmpty())) {
if (overlapping && !reset &&(!deletions.isEmpty() || !toLoad.isEmpty())) {
// a delete by key value cannot tell overlapping partitions apart, so the whole table is replaced
reset = true;
toLoad.clear();
@@ -77,10 +77,20 @@ final class PartitionPruner {
* table has no usable predicate in some place it is named, or the text is not understood.
*/
static Optional<Filter> filterFor(String sql, String schema, String table, List<Column> partitionKeys) {
return filterFor(sql, schema, table, partitionKeys, List.of());
}
/**
* Like {@link #filterFor(String, String, String, List)}, reading each {@code $n} as the text of
* {@code parameters.get(n - 1)}. A parameter with no value, or a null one, stays unknown, so a predicate on
* it is not used.
*/
static Optional<Filter> filterFor(String sql, String schema, String table, List<Column> partitionKeys,
List<String> parameters) {
if (sql == null || partitionKeys == null || partitionKeys.isEmpty()) {
return Optional.empty();
}
Tokens tokens = tokenize(sql);
Tokens tokens = bindParameters(tokenize(sql), parameters);
if (tokens.unsafe || !tokens.balanced()) {
return Optional.empty();
}
@@ -723,6 +733,51 @@ final class PartitionPruner {
return words.size() == 3 && words.get(1).text.equals(schema) && words.get(2).text.equals(table);
}
/** Whether the text names a bind parameter such as {@code $1} outside strings, comments and quoted names. */
static boolean hasParameters(String sql) {
if (sql == null || sql.indexOf('$') < 0) {
return false;
}
return tokenize(sql).list.stream().anyMatch(token -> parameterIndex(token) >= 0);
}
/** Zero-based position of a {@code $n} token, or -1 when the token is not a bind parameter. */
private static int parameterIndex(Token token) {
String text = token.text;
if (token.kind != Kind.OTHER || text.length() < 2 || text.charAt(0) != '$') {
return -1;
}
for (int i = 1; i < text.length(); i++) {
if (!Character.isDigit(text.charAt(i))) {
return -1;
}
}
try {
return Integer.parseInt(text.substring(1)) - 1;
} catch (NumberFormatException expected) {
// a number too long for an int is no parameter the client could have bound
return -1;
}
}
/**
* Replaces each {@code $n} that has a text value with a string literal of it, which the predicate parser
* reads like the same literal written in the query. Quotes in the value cannot end the literal: a token
* holds the text itself, not SQL.
*/
private static Tokens bindParameters(Tokens tokens, List<String> parameters) {
if (parameters == null || parameters.isEmpty()) {
return tokens;
}
List<Token> list = new ArrayList<>(tokens.list.size());
for (Token token : tokens.list) {
int index = parameterIndex(token);
String value = index >= 0 && index < parameters.size() ? parameters.get(index) : null;
list.add(value == null ? token : new Token(Kind.STRING, value, true));
}
return new Tokens(list, tokens.unsafe);
}
private static Tokens tokenize(String sql) {
SpectrumSqlLexer.Result result = SpectrumSqlLexer.tokenize(sql);
List<Token> list = new ArrayList<>(result.tokens().size());
@@ -50,8 +50,16 @@ public class SpectrumQueryPreparation {
}
public boolean prepare(String sql, SpectrumSession session, BackendSql backend) {
return prepare(sql, session, backend, List.of());
}
/**
* Prepares a statement that has bind parameters. {@code parameters} is the text of each bound value, a null
* where it is unusable; null {@code parameters} means the statement is only being parsed, with no values yet.
*/
public boolean prepare(String sql, SpectrumSession session, BackendSql backend, List<String> parameters) {
try {
return RequestScopes.callAs(session.accountId(), () -> prepareInScope(sql, session, backend));
return RequestScopes.callAs(session.accountId(), () -> prepareInScope(sql, session, backend, parameters));
} catch (AwsException exception) {
String state = switch (exception.getErrorCode()) {
case "AlreadyExistsException" -> "42P07";
@@ -91,7 +99,7 @@ public class SpectrumQueryPreparation {
};
}
private boolean prepareInScope(String sql, SpectrumSession session, BackendSql backend) {
private boolean prepareInScope(String sql, SpectrumSession session, BackendSql backend, List<String> parameters) {
Optional<ExternalStatement> statement = parser.parse(sql);
if (statement.orElse(null) instanceof ExternalStatement.CreateSchema schema) {
return createSchema(schema, session, backend);
@@ -139,7 +147,7 @@ public class SpectrumQueryPreparation {
try (ExternalCatalogLocks.Guard ignored = catalogLocks.read(binding,
session.inTransaction() || !backend.permitsCachePublication())) {
requireCurrentBinding(session, binding);
ExternalTableMaterializer.Outcome outcome = materializer.ensureCurrent(backend, session, binding, reference.table(), sql);
ExternalTableMaterializer.Outcome outcome = materializer.ensureCurrent(backend, session, binding, reference.table(), sql, parameters);
if (outcome == ExternalTableMaterializer.Outcome.NOT_EXTERNAL) {
throw new SpectrumSqlException("42P01", "external relation \"" + reference.schema()
+ "." + reference.table() + "\" does not exist");