feat(redshift): support COPY FORMAT AS PARQUET (#9637)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-28 23:12:22 -04:00
1 parent 7d3049d218
commit 3c97fbe849
18 files changed
+782 -85

No files matched your search

+5 -2
View File
@@ -1257,7 +1257,7 @@ Query protocol is emulated: Floci reads the object (or every object under the pr
order) through its own S3 service and streams the rows into the backing PostgreSQL container with
`COPY ... FROM STDIN`.
- Supported options: `DELIMITER`, `FORMAT CSV` (or a bare `CSV`), `GZIP`, `IGNOREHEADER <n>` and
- Supported options: `DELIMITER`, `FORMAT CSV` (or a bare `CSV`), `FORMAT AS PARQUET` (or bare `PARQUET`), `GZIP`, `IGNOREHEADER <n>` and
`HEADER`, `NULL AS`, `FORMAT AS JSON 'auto'`, `FORMAT AS JSON 'auto ignorecase'` (or bare `JSON 'auto'`),
`MANIFEST`, `COMPUPDATE`, `STATUPDATE`, `TRIMBLANKS`, `IGNOREBLANKLINES`, `ROUNDEC`,
`IGNOREALLERRORS`, and an explicit column list.
@@ -1381,7 +1381,10 @@ order) through its own S3 service and streams the rows into the backing PostgreS
session user's records and superusers all records; raw rows live in a private backing table. Existing
catalog rows are retained when an older cluster's catalog is bootstrapped again.
Floci deviations: `position` and `copy_job_id` are zero, and unknown error categories use code 1200.
- Any other clause (`FIXEDWIDTH`, `PARQUET`, `AVRO`, `ORC`,
- `FORMAT AS PARQUET` (also `FORMAT PARQUET` or bare `PARQUET`) reads Parquet files from S3 through `floci-duck`
and loads them into the target table. It can be combined with `MANIFEST`, `COMPUPDATE`, `STATUPDATE`, and
authorization clauses, and cannot be combined with `REGION`, text/CSV framing, or field-transform options.
- Any other clause (`FIXEDWIDTH`, `AVRO`, `ORC`,
`ENCODING`, `ESCAPE`, `ENCRYPTED`, `MASTER_SYMMETRIC_KEY`,
`KMS_KEY_ID`, and so on) is not recognized: the statement is forwarded unchanged and PostgreSQL
returns its own error.
@@ -23,6 +23,32 @@ final class CopyBulkLoader {
private CopyBulkLoader() {
}
static long loadParquet(CopyBackendSession backend, CopyInput input, RedshiftParquetWriter parquetWriter,
String effectiveAccount) throws IOException {
if (parquetWriter == null) {
throw new S3TransferException("0A000", "COPY FORMAT AS PARQUET requires floci-duck", null);
}
CopyStatementParser.S3CopyFrom spec = input.spec();
String sql = S3CopySimulator.copyBackendSql(spec);
long accepted = 0;
for (String key : input.keys()) {
S3CopySimulator.authorizeCopyObject(spec, input.s3(), input.iamService(), input.roleSession(), key);
byte[] parquet = S3CopySimulator.readBoundedParquetObject(input, key);
try (RedshiftParquetWriter.StagedCsv csv = parquetWriter.readToCsv(
parquet, effectiveAccount, input.roleSession())) {
if (csv.bytes().length == 0) {
continue;
}
accepted += backend.copy(sql, output -> {
OutputStream buffered = new BufferedOutputStream(output, 8192);
S3CopySimulator.writeStreamedBytes(csv.bytes(), buffered);
buffered.flush();
});
}
}
return accepted;
}
static long load(CopyBackendSession backend, CopyInput input, List<String> discovered, List<Integer> widths,
List<CopyRecordTransformer.ColumnKind> kinds, List<Integer> scales,
List<ColumnInfo> catalog, CopyLoadError.Context context) throws IOException {
@@ -41,6 +41,13 @@ final class CopyEtlLoader {
static boolean runSimple(Socket client, Socket socket, CopyStatementParser.S3Statement spec,
S3Service s3, IamService iam, String account, List<String> roles,
char status, IntConsumer onStatusChange, Consumer<CopyLoadError> errorSink) throws IOException {
return runSimple(client, socket, spec, s3, iam, account, roles, status, onStatusChange, errorSink, null);
}
static boolean runSimple(Socket client, Socket socket, CopyStatementParser.S3Statement spec,
S3Service s3, IamService iam, String account, List<String> roles,
char status, IntConsumer onStatusChange, Consumer<CopyLoadError> errorSink,
RedshiftParquetWriter parquetWriter) throws IOException {
CopyBackendSession backend = new CopyBackendSession(socket, response -> {
client.getOutputStream().write(response.toPacketBytes());
client.getOutputStream().flush();
@@ -49,7 +56,7 @@ final class CopyEtlLoader {
long accepted = 0;
S3TransferException failure = null;
try {
accepted = execute(backend, spec, s3, iam, account, roles, status != 'I');
accepted = execute(backend, spec, s3, iam, account, roles, status != 'I', parquetWriter);
} catch (S3TransferException exception) {
failure = exception;
} catch (AwsException exception) {
@@ -85,13 +92,21 @@ final class CopyEtlLoader {
static long execute(CopyBackendSession backend, CopyStatementParser.S3Statement spec,
S3Service s3, IamService iam, String account, List<String> roles,
boolean callerTransaction) throws IOException {
return execute(backend, spec, s3, iam, account, roles, callerTransaction, null);
}
static long execute(CopyBackendSession backend, CopyStatementParser.S3Statement spec,
S3Service s3, IamService iam, String account, List<String> roles,
boolean callerTransaction, RedshiftParquetWriter parquetWriter) throws IOException {
backend.begin(callerTransaction);
String savepoint = "floci_load_" + UUID.randomUUID().toString().replace("-", "");
backend.execute("SAVEPOINT " + savepoint);
try {
long rows = switch (spec) {
case CopyStatementParser.S3CopyFrom copy -> load(backend, copy, null, null, s3, iam, account, roles, false);
case CopyStatementParser.S3CopyJobRun run -> CopyJobRunner.load(backend, run.name(), s3, iam, account, roles);
case CopyStatementParser.S3CopyFrom copy -> load(backend, copy, null, null, s3, iam, account, roles,
false, parquetWriter);
case CopyStatementParser.S3CopyJobRun run -> CopyJobRunner.load(backend, run.name(), s3, iam, account, roles,
parquetWriter);
default -> throw new IllegalArgumentException("Expected COPY statement");
};
backend.execute("RELEASE SAVEPOINT " + savepoint);
@@ -114,13 +129,20 @@ final class CopyEtlLoader {
static long executeObject(CopyBackendSession backend, CopyStatementParser.S3CopyFrom spec,
String expectedETag, String versionId,
S3Service s3, IamService iam, String account, List<String> roles) throws IOException {
return load(backend, spec, expectedETag, versionId, s3, iam, account, roles, true);
return executeObject(backend, spec, expectedETag, versionId, s3, iam, account, roles, null);
}
static long executeObject(CopyBackendSession backend, CopyStatementParser.S3CopyFrom spec,
String expectedETag, String versionId,
S3Service s3, IamService iam, String account, List<String> roles,
RedshiftParquetWriter parquetWriter) throws IOException {
return load(backend, spec, expectedETag, versionId, s3, iam, account, roles, true, parquetWriter);
}
private static long load(CopyBackendSession backend, CopyStatementParser.S3CopyFrom spec,
String expectedETag, String versionId,
S3Service s3, IamService iam, String account, List<String> roles,
boolean exactObject) throws IOException {
boolean exactObject, RedshiftParquetWriter parquetWriter) throws IOException {
List<ColumnInfo> catalog = columns(backend, spec);
List<String> discovered = spec.jsonAuto() && (spec.columns() == null || spec.columns().isEmpty())
? catalog.stream().map(ColumnInfo::name).toList() : null;
@@ -136,10 +158,16 @@ final class CopyEtlLoader {
: S3CopySimulator.prepareCopy(spec, s3, iam, account, roles);
try {
try {
return RequestScopes.callAsChecked(S3CopySimulator.keyAccount(spec, s3, iam),
() -> spec.transforms().toleratesErrors()
? loadRecords(backend, input, discovered, widths, kinds, scales, catalog, context)
: CopyBulkLoader.load(backend, input, discovered, widths, kinds, scales, catalog, context));
String keyAccount = S3CopySimulator.keyAccount(spec, s3, iam);
String effectiveAccount = keyAccount != null ? keyAccount : account;
return RequestScopes.callAsChecked(keyAccount, () -> {
if (spec.parquet()) {
return CopyBulkLoader.loadParquet(backend, input, parquetWriter, effectiveAccount);
}
return spec.transforms().toleratesErrors()
? loadRecords(backend, input, discovered, widths, kinds, scales, catalog, context)
: CopyBulkLoader.load(backend, input, discovered, widths, kinds, scales, catalog, context);
});
} catch (IOException | RuntimeException exception) {
throw exception;
} catch (Exception exception) {
@@ -30,6 +30,11 @@ final class CopyJobRunner {
static long load(CopyBackendSession backend, String name, S3Service s3, IamService iam,
String account, List<String> roles) throws IOException {
return load(backend, name, s3, iam, account, roles, null);
}
static long load(CopyBackendSession backend, String name, S3Service s3, IamService iam,
String account, List<String> roles, RedshiftParquetWriter parquetWriter) throws IOException {
List<List<String>> jobs = backend.query("SELECT job_id, job_text, bucket, prefix, "
+ "extract(epoch FROM created_at), owner FROM floci_internal.copy_job_for_run("
+ PostgresWire.quoteLiteral(name) + ")");
@@ -46,7 +51,7 @@ final class CopyJobRunner {
RedshiftRoleAccess.authorizeRoleList(s3, iam, session, copy.iamRoleArn(), copy.bucket(), copy.keyOrPrefix());
String caller = backend.query("SELECT current_user").getFirst().getFirst();
backend.execute("SET LOCAL ROLE " + identifier(job.get(5)));
long count = loadFiles(backend, job, copy, s3, iam, account, roles);
long count = loadFiles(backend, job, copy, s3, iam, account, roles, parquetWriter);
backend.execute("SET LOCAL ROLE " + identifier(caller));
return count;
} finally {
@@ -55,7 +60,8 @@ final class CopyJobRunner {
}
private static long loadFiles(CopyBackendSession backend, List<String> job, CopyStatementParser.S3CopyFrom copy,
S3Service s3, IamService iam, String account, List<String> roles) throws IOException {
S3Service s3, IamService iam, String account, List<String> roles,
RedshiftParquetWriter parquetWriter) throws IOException {
long id = Long.parseLong(job.get(0));
// S3 stores lastModified at millisecond precision.
Instant created = Instant.ofEpochMilli(new BigDecimal(job.get(4)).movePointRight(3).longValue());
@@ -101,13 +107,15 @@ final class CopyJobRunner {
continue;
}
count += CopyEtlLoader.executeObject(backend, forObject(copy, object.getKey()),
object.getETag(), object.getVersionId(), s3, iam, account, roles);
object.getETag(), object.getVersionId(), s3, iam, account, roles, parquetWriter);
backend.execute("RELEASE SAVEPOINT " + fileSavepoint);
checkpointed.add(object.getKey());
failedFiles.remove(object.getKey());
} catch (IOException | RuntimeException exception) {
rollbackFileSavepoint(backend, fileSavepoint, exception);
if (exception instanceof S3TransferException transfer && S3TransferException.isJobFailure(transfer.sqlState())) {
if (exception instanceof S3TransferException transfer
&& (S3TransferException.isJobFailure(transfer.sqlState())
|| "53400".equals(transfer.sqlState()))) {
throw transfer;
}
backend.query("SELECT floci_internal.record_copy_job_file_error("
@@ -146,7 +154,7 @@ final class CopyJobRunner {
return new CopyStatementParser.S3CopyFrom(copy.targetTable(), copy.columns(), copy.bucket(), key,
copy.delimiter(), copy.headerLines(), copy.gzip(), copy.csv(), copy.nullAs(), copy.iamRoleArn(),
copy.jsonAuto(), copy.jsonAutoIgnoreCase(), copy.manifest(), copy.transforms(),
copy.defaultIamRoleRequested(), copy.accessKeys());
copy.defaultIamRoleRequested(), copy.accessKeys(), copy.parquet());
}
private static String literal(String value) {
@@ -142,7 +142,8 @@ public final class CopyStatementParser {
boolean manifest,
CopyTransforms transforms,
boolean defaultIamRoleRequested,
AccessKeys accessKeys) implements S3Statement {
AccessKeys accessKeys,
boolean parquet) implements S3Statement {
public S3CopyFrom {
if (transforms == null) {
@@ -150,6 +151,28 @@ public final class CopyStatementParser {
}
}
public S3CopyFrom(
String targetTable,
List<String> columns,
String bucket,
String keyOrPrefix,
String delimiter,
int headerLines,
boolean gzip,
boolean csv,
String nullAs,
String iamRoleArn,
boolean jsonAuto,
boolean jsonAutoIgnoreCase,
boolean manifest,
CopyTransforms transforms,
boolean defaultIamRoleRequested,
AccessKeys accessKeys) {
this(targetTable, columns, bucket, keyOrPrefix, delimiter, headerLines, gzip, csv,
nullAs, iamRoleArn, jsonAuto, jsonAutoIgnoreCase, manifest, transforms,
defaultIamRoleRequested, accessKeys, false);
}
public S3CopyFrom(
String targetTable,
List<String> columns,
@@ -428,7 +451,7 @@ public final class CopyStatementParser {
* silently loading the data with the wrong framing.
*/
private static final Pattern UNSUPPORTED_CLAUSE = Pattern.compile(
"(?i)\\b(FIXEDWIDTH|PARQUET|AVRO|ORC|SHAPEFILE|BZIP2|LZOP|ZSTD"
"(?i)\\b(FIXEDWIDTH|AVRO|ORC|SHAPEFILE|BZIP2|LZOP|ZSTD"
+ "|ENCRYPTED|ENCODING"
+ "|MASTER_SYMMETRIC_KEY|KMS_KEY_ID"
+ "|ESCAPE|EXPLICIT_IDS"
@@ -750,6 +773,7 @@ public final class CopyStatementParser {
options = options.substring(0, semiIdx);
}
boolean parquet = false;
boolean csv = false;
boolean gzip = false;
boolean jsonAuto = false;
@@ -792,6 +816,7 @@ public final class CopyStatementParser {
boolean seenDelimiter = false;
boolean seenHeader = false;
Matcher parquetMatcher = PARQUET_PATTERN.matcher(options);
Matcher csvMatcher = CSV_PATTERN.matcher(options);
Matcher gzipMatcher = GZIP_PATTERN.matcher(options);
Matcher jsonAutoMatcher = JSON_AUTO_PATTERN.matcher(options);
@@ -829,15 +854,21 @@ public final class CopyStatementParser {
break;
}
if (matchClause(csvMatcher, offset, len)) {
if (seenCsv || seenJson) {
if (matchClause(parquetMatcher, offset, len)) {
if (parquet || seenCsv || seenJson) {
return null;
}
parquet = true;
offset = parquetMatcher.end();
} else if (matchClause(csvMatcher, offset, len)) {
if (seenCsv || seenJson || parquet) {
return null;
}
seenCsv = true;
csv = true;
offset = csvMatcher.end();
} else if (matchClause(jsonAutoMatcher, offset, len)) {
if (seenJson || seenCsv) {
if (seenJson || seenCsv || parquet) {
return null;
}
seenJson = true;
@@ -1027,6 +1058,10 @@ public final class CopyStatementParser {
blanksAsNull, emptyAsNull, removeQuotes, truncateColumns, invalidChar,
dateFormat, timeFormat, acceptAnyDate, fillRecord, maxError, trimBlanks,
ignoreBlankLines, roundDecimal, ignoreAllErrors);
if (parquet && (csv || jsonAuto || gzip || seenHeader || seenDelimiter || seenNull
|| auth.seenRegion || transforms.any() || transforms.toleratesErrors())) {
return null;
}
if (jsonAuto && (blanksAsNull || emptyAsNull || removeQuotes || truncateColumns || invalidChar != null
|| transforms.temporal() || fillRecord || trimBlanks)) {
return null;
@@ -1043,7 +1078,7 @@ public final class CopyStatementParser {
return new S3CopyFrom(table, columns, bucket, keyOrPrefix, delimiter, headerLines, gzip, csv,
nullAs, iamRoleArn, jsonAuto, jsonAutoIgnoreCase, manifest, transforms, auth.defaultIamRoleRequested,
auth.accessKeys());
auth.accessKeys(), parquet);
}
/**
@@ -45,9 +45,9 @@ final class ExtendedS3Exchange {
try {
failed = !switch (statement) {
case CopyStatementParser.S3CopyJobRun run -> runEtlCopy(client, backend, executeFrame, run,
s3Service, iamService, clusterAccountId, iamRoleArns, coordinator, copyBackend);
s3Service, iamService, clusterAccountId, iamRoleArns, coordinator, copyBackend, parquetWriter);
case CopyStatementParser.S3CopyFrom copy -> runEtlCopy(client, backend, executeFrame, copy,
s3Service, iamService, clusterAccountId, iamRoleArns, coordinator, copyBackend);
s3Service, iamService, clusterAccountId, iamRoleArns, coordinator, copyBackend, parquetWriter);
case CopyStatementParser.S3Unload unload -> runOwnedUnload(client, backend, executeFrame, unload,
s3Service, iamService, clusterAccountId, iamRoleArns, coordinator, ticket, copyBackend, parquetWriter);
};
@@ -157,7 +157,8 @@ final class ExtendedS3Exchange {
private static boolean runEtlCopy(Socket client, Socket backend,
PostgresWireDecoder.FrontendMessage executeFrame, CopyStatementParser.S3Statement spec,
S3Service s3, IamService iam, String account, List<String> roles,
BackendResponseCoordinator coordinator, CopyBackendSession copyBackend) throws IOException {
BackendResponseCoordinator coordinator, CopyBackendSession copyBackend,
RedshiftParquetWriter parquetWriter) throws IOException {
OutputStream output = backend.getOutputStream();
output.write(executeFrame.toPacketBytes());
output.write(new byte[]{'H', 0, 0, 0, 4});
@@ -174,7 +175,7 @@ final class ExtendedS3Exchange {
}
try {
long count = CopyEtlLoader.execute(copyBackend, spec, s3, iam, account, roles,
coordinator.lastReadyStatus() != 'I');
coordinator.lastReadyStatus() != 'I', parquetWriter);
forward(client, new PostgresWireDecoder.FrontendMessage('C',
("COPY " + count + "\0").getBytes(StandardCharsets.UTF_8)));
return true;
@@ -359,12 +359,14 @@ public class RedshiftInterceptingBridge {
boolean intercepted = runWithBackendOwned(() -> switch (statement) {
case CopyStatementParser.S3CopyJobRun run -> CopyEtlLoader.runSimple(
client, backend, run, s3Service, iamService, clusterAccountId, iamRoleArns,
coordinator.lastReadyStatus(), status -> coordinator.onBackendFrame('Z', new byte[]{(byte) status}), loadErrorSink);
coordinator.lastReadyStatus(), status -> coordinator.onBackendFrame('Z', new byte[]{(byte) status}),
loadErrorSink, parquetWriter);
case CopyStatementParser.S3CopyFrom copy -> loadErrorSink != null ? CopyEtlLoader.runSimple(
client, backend, copy, s3Service, iamService, clusterAccountId, iamRoleArns, coordinator.lastReadyStatus(),
status -> coordinator.onBackendFrame('Z', new byte[]{(byte) status}), loadErrorSink) : S3CopySimulator.runCopyFrom(
status -> coordinator.onBackendFrame('Z', new byte[]{(byte) status}), loadErrorSink, parquetWriter)
: S3CopySimulator.runCopyFrom(
client, backend, copy, s3Service, iamService, clusterAccountId, iamRoleArns, coordinator.lastReadyStatus(),
status -> coordinator.onBackendFrame('Z', new byte[]{(byte) status}));
status -> coordinator.onBackendFrame('Z', new byte[]{(byte) status}), parquetWriter);
case CopyStatementParser.S3Unload unload -> S3CopySimulator.runUnload(
client, backend, unload, s3Service, iamService, clusterAccountId, iamRoleArns, coordinator.lastReadyStatus(),
status -> coordinator.onBackendFrame('Z', new byte[]{(byte) status}), parquetWriter);
@@ -33,12 +33,85 @@ public class RedshiftParquetWriter {
private final S3Service s3;
private final IamService iam;
private final String region;
private final String defaultAccountId;
public RedshiftParquetWriter(FlociDuckClient duck, S3Service s3, IamService iam, EmulatorConfig config) {
this.duck = duck;
this.s3 = s3;
this.iam = iam;
region = config.defaultRegion();
String configuredAccount = config.defaultAccountId();
defaultAccountId = configuredAccount != null && !configuredAccount.isBlank()
? configuredAccount : "000000000000";
}
/** CSV bytes converted from Parquet together with their reservation on {@code COPY_TRANSFORM_HEAP_MIB}. */
static final class StagedCsv implements AutoCloseable {
static final StagedCsv EMPTY = new StagedCsv(new byte[0], 0);
private final byte[] bytes;
private int heldMib;
StagedCsv(byte[] bytes, int heldMib) {
this.bytes = bytes;
this.heldMib = heldMib;
}
byte[] bytes() {
return bytes;
}
@Override
public void close() {
if (heldMib > 0) {
S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.release(heldMib);
heldMib = 0;
}
}
}
private final class StagingSession implements AutoCloseable {
private final String accountId;
private final RedshiftRoleAccess.RoleSession credentials;
private StagingSession(String accountId, RedshiftRoleAccess.RoleSession credentials) {
this.accountId = accountId;
this.credentials = credentials;
}
List<Map<String, Object>> query(String sql, String setup) {
if (credentials == null) {
return duck.query(sql, setup, accountId);
}
return duck.query(sql, setup, credentials.accessKeyId(),
credentials.secretAccessKey(), credentials.sessionToken());
}
@Override
public void close() {
if (credentials != null) {
iam.clearScratchResource(credentials.accessKeyId());
iam.unregisterSession(accountId, credentials.accessKeyId());
}
}
}
private StagingSession openStagingSession(String accountId, String root, boolean authenticated) {
if (!authenticated) {
return new StagingSession(accountId, null);
}
String stagingAccountId = accountId != null && !accountId.isBlank() ? accountId : defaultAccountId;
String partition = AwsRegions.partitionFor(region);
RedshiftRoleAccess.RoleSession staging = RedshiftRoleAccess.mintStagingSession(iam, stagingAccountId, partition);
try {
iam.registerScratchResource(staging.accessKeyId(), AwsArnUtils.Arn.global(
partition, "s3", "", STAGING_BUCKET + "/" + root).toString());
return new StagingSession(stagingAccountId, staging);
} catch (RuntimeException exception) {
iam.clearScratchResource(staging.accessKeyId());
iam.unregisterSession(stagingAccountId, staging.accessKeyId());
throw exception;
}
}
record Column(String name, String type) { }
@@ -156,32 +229,44 @@ public class RedshiftParquetWriter {
+ "\" of type " + type + ". " + hint, null);
}
List<byte[]> convert(byte[] csv, List<Column> columns, String accountId,
RedshiftRoleAccess.RoleSession session, long maxFileSizeBytes) throws IOException {
@FunctionalInterface
private interface StagingWork<T> {
T run(String root, StagingSession staging) throws IOException;
}
private <T> T withStaging(String accountId, RedshiftRoleAccess.RoleSession session,
String operation, String errorMessage, StagingWork<T> work) throws IOException {
try {
return RequestScopes.callAsChecked(accountId,
() -> convertScoped(csv, columns, accountId, session, maxFileSizeBytes));
return RequestScopes.callAsChecked(accountId, () -> {
S3ScratchSpace.UNLOAD.ensureBucket(s3, region);
String root = "unload/" + UUID.randomUUID() + "/";
try (StagingSession staging = openStagingSession(accountId, root, session != null)) {
return work.run(root, staging);
} finally {
try {
s3.deleteObjectsWithPrefix(STAGING_BUCKET, root, ignored -> {
// Internal staging cleanup does not use the external role.
});
} catch (RuntimeException exception) {
LOG.warnv(exception, "Could not remove {0} staging prefix {1}", operation, root);
}
}
});
} catch (RuntimeException | IOException exception) {
throw exception;
} catch (Exception exception) {
throw new IOException("Unable to convert UNLOAD slice", exception);
throw new IOException(errorMessage, exception);
}
}
private List<byte[]> convertScoped(byte[] csv, List<Column> columns, String accountId,
RedshiftRoleAccess.RoleSession session, long maxFileSizeBytes) throws IOException {
List<byte[]> convert(byte[] csv, List<Column> columns, String accountId,
RedshiftRoleAccess.RoleSession session, long maxFileSizeBytes) throws IOException {
if (columns.isEmpty()) {
throw new IOException("UNLOAD query has no Parquet columns");
}
S3ScratchSpace.UNLOAD.ensureBucket(s3, region);
String root = "unload/" + UUID.randomUUID() + "/";
String inputKey = root + "input.csv";
String outputKey = root + "output.parquet";
try {
if (session != null) {
iam.registerScratchResource(session.accessKeyId(), AwsArnUtils.Arn.global(
AwsRegions.partitionFor(region), "s3", "", STAGING_BUCKET + "/" + root).toString());
}
return withStaging(accountId, session, "UNLOAD", "Unable to convert UNLOAD slice", (root, staging) -> {
String inputKey = root + "input.csv";
String outputKey = root + "output.parquet";
s3.putObject(STAGING_BUCKET, inputKey, csv, "text/csv", null);
StringBuilder schema = new StringBuilder();
StringBuilder projection = new StringBuilder();
@@ -210,9 +295,7 @@ public class RedshiftParquetWriter {
+ "' (FORMAT PARQUET, COMPRESSION SNAPPY, PARQUET_VERSION V1, FILE_SIZE_BYTES "
+ maxFileSizeBytes + ", RETURN_STATS true)";
String setup = "SET TimeZone = 'UTC'; SET threads = 1;";
List<Map<String, Object>> files = session == null
? duck.query(sql, setup, accountId)
: duck.query(sql, setup, session.accessKeyId(), session.secretAccessKey(), session.sessionToken());
List<Map<String, Object>> files = staging.query(sql, setup);
if (files.isEmpty()) {
throw new IOException("DuckDB returned no Parquet output files");
}
@@ -224,18 +307,96 @@ public class RedshiftParquetWriter {
}
}
return result;
} finally {
if (session != null) {
iam.clearScratchResource(session.accessKeyId());
}
try {
s3.deleteObjectsWithPrefix(STAGING_BUCKET, root, ignored -> {
// Internal staging cleanup does not use the external role.
});
} catch (RuntimeException exception) {
LOG.warnv(exception, "Could not remove UNLOAD staging prefix {0}", root);
}
});
}
/**
* Converts one already-authorized Parquet object into headerless UTF-8 CSV via {@code floci-duck},
* bounded by {@link S3CopySimulator#COPY_TRANSFORM_MAX_OBJECT_BYTES} and sharing
* {@link S3CopySimulator#COPY_TRANSFORM_HEAP_MIB} until the caller closes the returned {@link StagedCsv}.
*/
StagedCsv readToCsv(byte[] parquetBytes, String accountId,
RedshiftRoleAccess.RoleSession session) throws IOException {
if (parquetBytes == null || parquetBytes.length == 0) {
return StagedCsv.EMPTY;
}
long maxBytes = S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES;
if (parquetBytes.length > maxBytes) {
throw new S3CopySimulator.S3TransferException("54000",
"COPY Parquet object exceeds the " + maxBytes + "-byte limit", null);
}
return withStaging(accountId, session, "COPY Parquet", "Unable to read Parquet COPY object",
(root, staging) -> {
String inputKey = root + "input.parquet";
String outputKey = root + "output.csv";
int[] heldMib = new int[]{0};
boolean handedOff = false;
try {
// Stage the authorized bytes under a literal key so DuckDB never globs caller object names.
s3.putObject(STAGING_BUCKET, inputKey, parquetBytes, "application/octet-stream", null);
s3.registerScratchWriteLimit(STAGING_BUCKET, outputKey, maxBytes);
String sourceUri = "s3://" + STAGING_BUCKET + "/" + inputKey;
String sql = "COPY (SELECT * FROM read_parquet('" + literal(sourceUri)
+ "', hive_partitioning = false)) TO '"
+ literal("s3://" + STAGING_BUCKET + "/" + outputKey)
+ "' (FORMAT CSV, HEADER false, DELIMITER ',', QUOTE '\"', ESCAPE '\"', NULL '')";
String setup = "SET TimeZone = 'UTC'; SET threads = 1;";
try {
staging.query(sql, setup);
} catch (RuntimeException exception) {
if (isEntityTooLarge(exception)) {
throw new S3CopySimulator.S3TransferException("54000",
"COPY Parquet object exceeds the " + maxBytes + "-byte decompressed limit",
exception);
}
throw exception;
}
if (!s3.objectExists(STAGING_BUCKET, outputKey)) {
return StagedCsv.EMPTY;
}
byte[] csv;
try (InputStream input = s3.openObjectStream(STAGING_BUCKET, outputKey, null)) {
csv = readBounded(input, maxBytes, heldMib);
}
StagedCsv staged = new StagedCsv(csv, heldMib[0]);
handedOff = true;
return staged;
} finally {
s3.clearScratchWriteLimit(STAGING_BUCKET, outputKey);
if (!handedOff && heldMib[0] > 0) {
S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.release(heldMib[0]);
}
}
});
}
private static boolean isEntityTooLarge(Throwable throwable) {
Throwable current = throwable;
while (current != null) {
String message = current.getMessage();
if (message != null && message.contains("EntityTooLarge")) {
return true;
}
current = current.getCause();
}
return false;
}
private static byte[] readBounded(InputStream input, long maxBytes, int[] heldMib) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
byte[] chunk = new byte[8192];
long total = 0;
int read;
while ((read = input.read(chunk)) != -1) {
total += read;
if (total > maxBytes) {
throw new S3CopySimulator.S3TransferException("54000",
"COPY Parquet object exceeds the " + maxBytes + "-byte decompressed limit", null);
}
S3CopySimulator.acquireTransformHeap(heldMib, (int) ((total * 2L) / (1024 * 1024)) + 1);
buffer.write(chunk, 0, read);
}
return buffer.toByteArray();
}
private static String emptyQuery(List<Column> columns) {
@@ -125,6 +125,22 @@ public final class RedshiftRoleAccess {
return new RoleSession(accessKeyId, secretAccessKey, sessionToken);
}
/**
* Mints an ephemeral session owned by {@code accountId} for an internal DuckDB staging transfer.
* Using a dedicated session per transfer lets IAM user keys work when auth is enforced and keeps
* concurrent transfers from overwriting each other's scratch prefix.
*/
static RoleSession mintStagingSession(IamService iamService, String accountId, String partition) {
String accessKeyId = "ASIA" + randomString(UPPER_ALPHANUMERIC, 16);
String sessionToken = randomString(SECRET_CHARACTERS, 200);
String secretAccessKey = randomString(SECRET_CHARACTERS, 40);
String stagingRoleArn = AwsArnUtils.Arn.global(
partition, "iam", accountId, "role/floci-internal-redshift-staging").toString();
iamService.registerSessionForAccount(accountId, accessKeyId, secretAccessKey, sessionToken,
stagingRoleArn, Instant.now().plus(ROLE_SESSION_TTL), null);
return new RoleSession(accessKeyId, secretAccessKey, sessionToken);
}
/**
* Looks up the role {@code iamRoleArn} names, honouring its path through {@link IamService#roleArnMatches}.
*/
@@ -290,10 +290,19 @@ public final class S3CopySimulator {
static void streamCopyInput(CopyInput input, List<String> discoveredColumns,
List<Integer> columnMaxBytes, List<CopyRecordTransformer.ColumnKind> columnKinds,
OutputStream backendOut) throws IOException {
String account = keyAccount(input.spec(), input.s3(), input.iamService());
streamCopyInput(input, discoveredColumns, columnMaxBytes, columnKinds, backendOut, null, null);
}
static void streamCopyInput(CopyInput input, List<String> discoveredColumns,
List<Integer> columnMaxBytes, List<CopyRecordTransformer.ColumnKind> columnKinds,
OutputStream backendOut, RedshiftParquetWriter parquetWriter,
String clusterAccountId) throws IOException {
String keyAccount = keyAccount(input.spec(), input.s3(), input.iamService());
String effectiveAccount = keyAccount != null ? keyAccount : clusterAccountId;
try {
RequestScopes.callAsChecked(account, () -> {
streamObjects(input, discoveredColumns, columnMaxBytes, columnKinds, backendOut);
RequestScopes.callAsChecked(keyAccount, () -> {
streamObjects(input, discoveredColumns, columnMaxBytes, columnKinds, backendOut, parquetWriter,
effectiveAccount);
return null;
});
} catch (IOException | RuntimeException e) {
@@ -322,7 +331,8 @@ public final class S3CopySimulator {
RedshiftParquetWriter parquetWriter) {
requireDefaultIamRole(spec);
RedshiftRoleAccess.RoleSession roleSession = spec.iamRoleArn() != null
? RedshiftRoleAccess.resolveRoleSession(spec.iamRoleArn(), iamService, clusterAccountId, associatedRoleArns)
? RedshiftRoleAccess.resolveRoleSession(spec.iamRoleArn(), iamService, clusterAccountId,
associatedRoleArns)
: null;
String probeKey = unloadDataKey(spec, 0);
boolean cleanPath = false;
@@ -420,9 +430,18 @@ public final class S3CopySimulator {
CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService,
String clusterAccountId, List<String> associatedRoleArns,
char txStatus, IntConsumer onStatusChange) throws IOException {
return runCopyFrom(client, backend, spec, s3, iamService, clusterAccountId, associatedRoleArns,
txStatus, onStatusChange, null);
}
public static boolean runCopyFrom(Socket client, Socket backend,
CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService,
String clusterAccountId, List<String> associatedRoleArns,
char txStatus, IntConsumer onStatusChange,
RedshiftParquetWriter parquetWriter) throws IOException {
if (spec.transforms().toleratesErrors()) {
return CopyEtlLoader.runSimple(client, backend, spec, s3, iamService, clusterAccountId,
associatedRoleArns, txStatus, onStatusChange);
associatedRoleArns, txStatus, onStatusChange, null, parquetWriter);
}
CopyInput input;
try {
@@ -491,7 +510,8 @@ public final class S3CopySimulator {
// a CopyFail to the backend, whose ErrorResponse/ReadyForQuery is relayed to the client;
// or, if the backend is unreachable, one synthesized ErrorResponse/ReadyForQuery.
try {
streamCopyInput(input, discoveredColumns, columnMaxBytes, columnKinds, backendOut);
streamCopyInput(input, discoveredColumns, columnMaxBytes, columnKinds, backendOut, parquetWriter,
clusterAccountId);
writeCopyDone(backendOut);
drainToReadyForQuery(backendDecoder, client, onStatusChange);
} catch (RuntimeException | IOException e) {
@@ -557,9 +577,10 @@ public final class S3CopySimulator {
.append(String.join(", ", spec.columns()))
.append(")");
}
boolean csv = spec.csv() || spec.jsonAuto();
boolean csv = spec.csv() || spec.jsonAuto() || spec.parquet();
sql.append(" FROM STDIN WITH (FORMAT ").append(csv ? "csv" : "text");
String delimiter = spec.jsonAuto() ? "," : (spec.delimiter() != null ? spec.delimiter() : (csv ? "," : "|"));
String delimiter = (spec.jsonAuto() || spec.parquet())
? "," : (spec.delimiter() != null ? spec.delimiter() : (csv ? "," : "|"));
sql.append(", DELIMITER '").append(quoteLiteral(delimiter)).append("'");
if (spec.nullAs() != null) {
sql.append(", NULL '").append(quoteLiteral(spec.nullAs())).append("'");
@@ -606,7 +627,8 @@ public final class S3CopySimulator {
private static void streamObjects(CopyInput input, List<String> discoveredColumns,
List<Integer> columnMaxBytes, List<CopyRecordTransformer.ColumnKind> columnKinds,
OutputStream backendOut) throws IOException {
OutputStream backendOut, RedshiftParquetWriter parquetWriter,
String effectiveAccount) throws IOException {
CopyStatementParser.S3CopyFrom spec = input.spec();
if (spec.transforms().truncateColumns() && columnMaxBytes == null) {
// Extended Query fixes the statement at Parse time, so there is no catalog round trip to
@@ -620,10 +642,21 @@ public final class S3CopySimulator {
"COPY ... DATEFORMAT, TIMEFORMAT, FILLRECORD and TRIMBLANKS need catalog column types, which are only "
+ "available over the Simple Query protocol; connect with preferQueryMode=simple", null);
}
if (spec.parquet() && parquetWriter == null) {
throw new S3TransferException("0A000", "COPY FORMAT AS PARQUET requires floci-duck", null);
}
byte[] buffer = new byte[CHUNK];
List<String> keys = input.keys();
for (int i = 0; i < keys.size(); i++) {
authorizeCopyObject(spec, input.s3(), input.iamService(), input.roleSession(), keys.get(i));
if (spec.parquet()) {
byte[] parquet = readBoundedParquetObject(input, keys.get(i));
try (RedshiftParquetWriter.StagedCsv csv = parquetWriter.readToCsv(
parquet, effectiveAccount, input.roleSession())) {
writeStreamedBytes(csv.bytes(), backendOut);
}
continue;
}
S3Object object = input.readObject(keys.get(i));
byte[] data = object != null && object.getData() != null ? object.getData() : new byte[0];
InputStream rawIn = new ByteArrayInputStream(data);
@@ -661,6 +694,21 @@ public final class S3CopySimulator {
backendOut.flush();
}
static void writeStreamedBytes(byte[] data, OutputStream backendOut) throws IOException {
if (data.length == 0) {
return;
}
for (int offset = 0; offset < data.length; offset += CHUNK) {
int length = Math.min(CHUNK, data.length - offset);
byte[] slice = new byte[length];
System.arraycopy(data, offset, slice, 0, length);
writeCopyData(backendOut, slice, length);
}
if (data[data.length - 1] != '\n') {
writeCopyData(backendOut, new byte[]{'\n'}, 1);
}
}
private static void checkTransformObjectLimit(long bytes) {
if (bytes > COPY_TRANSFORM_MAX_OBJECT_BYTES) {
throw new S3TransferException(SQLSTATE_PROGRAM_LIMIT_EXCEEDED,
@@ -671,7 +719,22 @@ public final class S3CopySimulator {
}
}
private static void acquireTransformHeap(int[] heldMib, int wantedMib) {
static byte[] readBoundedParquetObject(CopyInput input, String key) {
S3Object metadata = input.s3().getObjectMetadata(input.spec().bucket(), key, input.versionId());
if (metadata != null && metadata.getSize() > COPY_TRANSFORM_MAX_OBJECT_BYTES) {
throw new S3TransferException(SQLSTATE_PROGRAM_LIMIT_EXCEEDED,
"COPY Parquet object exceeds the " + COPY_TRANSFORM_MAX_OBJECT_BYTES + "-byte limit", null);
}
S3Object object = input.readObject(key);
byte[] data = object != null && object.getData() != null ? object.getData() : new byte[0];
if (data.length > COPY_TRANSFORM_MAX_OBJECT_BYTES) {
throw new S3TransferException(SQLSTATE_PROGRAM_LIMIT_EXCEEDED,
"COPY Parquet object exceeds the " + COPY_TRANSFORM_MAX_OBJECT_BYTES + "-byte limit", null);
}
return data;
}
static void acquireTransformHeap(int[] heldMib, int wantedMib) {
while (heldMib[0] < wantedMib) {
if (!COPY_TRANSFORM_HEAP_MIB.tryAcquire(1)) {
throw new S3TransferException(SQLSTATE_CONFIGURATION_LIMIT_EXCEEDED,
@@ -1442,7 +1505,8 @@ public final class S3CopySimulator {
if (roleSession != null) {
RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject",
RedshiftRoleAccess.objectArn(spec.iamRoleArn(), spec.bucket(), key));
s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), key);
s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(),
spec.bucket(), key);
} else {
s3.authorizeAnonymousPutObject(spec.bucket(), key);
}
@@ -1543,7 +1607,8 @@ public final class S3CopySimulator {
if (roleSession != null) {
RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject",
RedshiftRoleAccess.objectArn(spec.iamRoleArn(), spec.bucket(), key));
s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), key);
s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(),
spec.bucket(), key);
} else {
s3.authorizeAnonymousPutObject(spec.bucket(), key);
}
@@ -159,6 +159,63 @@ public class S3Service implements Resettable, ResourceProvider {
/** Last {@code s3.object.sequencer} handed out, in microseconds since the epoch. */
private final AtomicLong lastEventSequencer = new AtomicLong();
private final AtomicLong dataGenerations = new AtomicLong();
private final Map<String, Long> scratchWriteLimits = new ConcurrentHashMap<>();
public void registerScratchWriteLimit(String bucketName, String key, long maxBytes) {
if (bucketName != null && key != null && maxBytes >= 0) {
scratchWriteLimits.put(bucketName + "\0" + key, maxBytes);
}
}
public void clearScratchWriteLimit(String bucketName, String key) {
if (bucketName != null && key != null) {
scratchWriteLimits.remove(bucketName + "\0" + key);
}
}
private Long scratchWriteLimit(String bucketName, String key) {
return bucketName == null || key == null ? null : scratchWriteLimits.get(bucketName + "\0" + key);
}
private static AwsException scratchWriteTooLarge(long maxBytes) {
return new AwsException("EntityTooLarge",
"Your proposed upload exceeds the maximum allowed size of " + maxBytes + " bytes", 400);
}
private static InputStream limitScratchBody(InputStream body, long maxBytes, long reportedLimit) {
return new InputStream() {
private long readTotal;
@Override
public int read() throws IOException {
int value = body.read();
if (value != -1) {
readTotal++;
if (readTotal > maxBytes) {
throw scratchWriteTooLarge(reportedLimit);
}
}
return value;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int read = body.read(b, off, len);
if (read > 0) {
readTotal += read;
if (readTotal > maxBytes) {
throw scratchWriteTooLarge(reportedLimit);
}
}
return read;
}
@Override
public void close() throws IOException {
body.close();
}
};
}
record RequestAuthorization(boolean signed, String accessKeyId, String sessionToken) {
static RequestAuthorization unsigned() {
@@ -864,6 +921,13 @@ public class S3Service implements Resettable, ResourceProvider {
// A checksum the client sent is stored as sent; otherwise the declared algorithm's, or CRC64NVME.
ChecksumAlgorithm computed = effectiveOptions.getClientChecksum() != null ? null
: declared != null ? declared : ChecksumAlgorithm.CRC64NVME;
Long scratchLimit = scratchWriteLimit(bucketName, key);
if (scratchLimit != null) {
if (declaredSize > scratchLimit) {
throw scratchWriteTooLarge(scratchLimit);
}
body = limitScratchBody(body, scratchLimit, scratchLimit);
}
if (inMemory) {
VerifiedBody verified = readVerified(body, checksums, "PutObject of " + bucketName + "/" + key,
declaredSize, computed);
@@ -4974,6 +5038,16 @@ public class S3Service implements Resettable, ResourceProvider {
// Each upload of a part gets its own storage, so a record and the bytes it describes are
// published together and never change: a re-upload adds new bytes and drops the old ones.
String storageId = partNumber + "-" + UUID.randomUUID();
Long scratchLimit = scratchWriteLimit(bucket, key);
if (scratchLimit != null) {
long otherParts = upload.getParts().values().stream()
.filter(part -> part.getPartNumber() != partNumber)
.mapToLong(Part::getSize)
.sum();
if (otherParts + data.length > scratchLimit) {
throw scratchWriteTooLarge(scratchLimit);
}
}
if (inMemory) {
// A re-uploaded part number replaces its earlier part, so that part does not count.
long otherParts = upload.getParts().values().stream()
@@ -5018,14 +5092,29 @@ public class S3Service implements Resettable, ResourceProvider {
UploadChecksums checksums,
String sseCustomerAlgorithm, String sseCustomerKey, String sseCustomerKeyMd5) {
checksums.requireWellFormedContentMd5();
Long scratchLimit = scratchWriteLimit(bucket, key);
long[] scratchRemaining = new long[]{-1L};
ChecksumAlgorithm declared = withMultipartOperationLock(bucket, uploadId, () -> {
MultipartUpload upload = getMultipartUpload(bucket, key, uploadId);
if (partNumber < 1 || partNumber > 10000) {
throw PartRange.invalidPartNumber(Integer.toString(partNumber));
}
validateSseCustomerAccess(upload, sseCustomerAlgorithm, sseCustomerKey, sseCustomerKeyMd5);
if (scratchLimit != null) {
long otherParts = upload.getParts().values().stream()
.filter(part -> part.getPartNumber() != partNumber)
.mapToLong(Part::getSize)
.sum();
if (otherParts > scratchLimit) {
throw scratchWriteTooLarge(scratchLimit);
}
scratchRemaining[0] = scratchLimit - otherParts;
}
return upload.getChecksumAlgorithm();
});
if (scratchLimit != null) {
body = limitScratchBody(body, scratchRemaining[0], scratchLimit);
}
if (inMemory) {
byte[] data = readVerified(body, checksums, "Multipart upload " + uploadId, -1, null).data();
return storePart(bucket, key, uploadId, partNumber, data,
@@ -23,6 +23,7 @@ import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@ResourceLock(value = ParallelLocks.PORTS, mode = ResourceAccessMode.READ)
@ResourceLock(ParallelLocks.REDSHIFT_COPY_LIMITS)
class CopyEtlLoaderTest {
@Test
void bulkLoadingDecodesEscapedDecimalsUsingCatalogScales() throws Exception {
@@ -28,7 +28,14 @@ class CopyJobRunTest {
assertEquals("prefix/a'b.csv", object.keyOrPrefix());
assertEquals("role", object.iamRoleArn());
assertTrue(object.csv());
assertFalse(object.parquet());
assertEquals("bucket", object.bucket());
CopyStatementParser.S3CopyFrom parquetSpec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY t FROM 's3://bucket/prefix/' IAM_ROLE 'role' FORMAT AS PARQUET");
CopyStatementParser.S3CopyFrom parquetObject = CopyJobRunner.forObject(parquetSpec, "prefix/part-0.parquet");
assertTrue(parquetObject.parquet());
assertEquals("prefix/part-0.parquet", parquetObject.keyOrPrefix());
}
@Test
@@ -28,6 +28,7 @@ import static org.mockito.Mockito.*;
@Timeout(10)
@ResourceLock(value = ParallelLocks.PORTS, mode = ResourceAccessMode.READ)
@ResourceLock(value = ParallelLocks.REDSHIFT_COPY_LIMITS, mode = ResourceAccessMode.READ)
class CopyJobRunnerTest {
private static final String ACCOUNT = "000000000000";
private static final String ROLE = "arn:aws:iam::000000000000:role/Load";
@@ -111,6 +112,66 @@ class CopyJobRunnerTest {
verify(s3).getObject("bucket", "prefix/b", "v1");
}
@Test
void loadsParquetCopyJobThroughParquetWriter() throws Exception {
S3Service s3 = mock(S3Service.class);
IamService iam = jobIam();
byte[] parquetBytes = "PAR1rowsPAR1".getBytes(StandardCharsets.UTF_8);
S3Object file = new S3Object("bucket", "prefix/part-0.parquet", parquetBytes, "application/octet-stream");
file.setLastModified(Instant.ofEpochSecond(40));
when(s3.listObjectsWithPrefixes("bucket", "prefix/", null, 1000, null, null))
.thenReturn(new S3Service.ListObjectsResult(List.of(file), List.of(), false, null));
when(s3.getObject("bucket", "prefix/part-0.parquet")).thenReturn(file);
RedshiftParquetWriter parquetWriter = mock(RedshiftParquetWriter.class);
when(parquetWriter.readToCsv(eq(parquetBytes), eq(ACCOUNT), any()))
.thenReturn(new RedshiftParquetWriter.StagedCsv("1\n".getBytes(StandardCharsets.UTF_8), 0));
String parquetCopy = "COPY t FROM 's3://bucket/prefix/' IAM_ROLE '" + ROLE + "' FORMAT AS PARQUET";
ByteArrayOutputStream copied = new ByteArrayOutputStream();
withBackend(copied, new ArrayList<>(), sql -> {
if (sql.contains("copy_job_for_run")) {
return List.of(List.of("1", parquetCopy, "bucket", "prefix/", "20", "job_owner"));
}
return jobRows(sql, List.of());
}, backend -> {
backend.begin(false);
long count = CopyJobRunner.load(backend, "job", s3, iam, ACCOUNT, List.of(ROLE), parquetWriter);
backend.finish(false);
assertEquals(1, count);
});
assertEquals("1\n", copied.toString(StandardCharsets.UTF_8));
verify(parquetWriter).readToCsv(eq(parquetBytes), eq(ACCOUNT), any());
}
@Test
void abortsWithoutCheckpointingFileErrorWhenMemoryBudgetIsExhausted() throws Exception {
S3Service s3 = mock(S3Service.class);
IamService iam = jobIam();
byte[] parquetBytes = "PAR1rowsPAR1".getBytes(StandardCharsets.UTF_8);
S3Object file = new S3Object("bucket", "prefix/part-0.parquet", parquetBytes, "application/octet-stream");
file.setLastModified(Instant.ofEpochSecond(40));
when(s3.listObjectsWithPrefixes("bucket", "prefix/", null, 1000, null, null))
.thenReturn(new S3Service.ListObjectsResult(List.of(file), List.of(), false, null));
when(s3.getObject("bucket", "prefix/part-0.parquet")).thenReturn(file);
RedshiftParquetWriter parquetWriter = mock(RedshiftParquetWriter.class);
when(parquetWriter.readToCsv(eq(parquetBytes), eq(ACCOUNT), any()))
.thenThrow(new S3CopySimulator.S3TransferException("53400", "COPY memory budget exhausted; retry shortly", null));
String parquetCopy = "COPY t FROM 's3://bucket/prefix/' IAM_ROLE '" + ROLE + "' FORMAT AS PARQUET";
List<String> statements = new ArrayList<>();
withBackend(new ByteArrayOutputStream(), statements, sql -> {
if (sql.contains("copy_job_for_run")) {
return List.of(List.of("1", parquetCopy, "bucket", "prefix/", "20", "job_owner"));
}
return jobRows(sql, List.of());
}, backend -> {
backend.begin(false);
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
() -> CopyJobRunner.load(backend, "job", s3, iam, ACCOUNT, List.of(ROLE), parquetWriter));
assertEquals("53400", error.sqlState());
backend.finish(true);
});
assertFalse(statements.stream().anyMatch(sql -> sql.contains("record_copy_job_file_error")));
}
private static long runJob(CopyBackendSession backend, S3Service s3, IamService iam) throws Exception {
backend.begin(false);
long count = CopyJobRunner.load(backend, "job", s3, iam, ACCOUNT, List.of(ROLE));
@@ -240,7 +240,7 @@ class CopyStatementParserTest {
@Test
void returnsNullForUnsupportedClauses() {
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' FORMAT AS PARQUET"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' FORMAT AS AVRO 'auto'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' JSON 's3://mybucket/jsonpaths.json'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' FIXEDWIDTH 'a:1,b:2'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' GZIP ESCAPE"));
@@ -794,10 +794,25 @@ class CopyStatementParserTest {
}
@Test
void parseCopy_rejectsUnsupportedJsonPathsAndParquet() {
void parseCopy_rejectsUnsupportedJsonPathsAndAvro() {
// Only JSON 'auto' is supported; jsonpaths or bare JSON must be rejected
assertNull(CopyStatementParser.parse("COPY tbl FROM 's3://b/k' JSON 's3://b/paths.json'"));
assertNull(CopyStatementParser.parse("COPY tbl FROM 's3://b/k' PARQUET"));
assertNull(CopyStatementParser.parse("COPY tbl FROM 's3://b/k' AVRO 'auto'"));
}
@Test
void parseCopy_acceptsParquetFormatsWithManifestAndRejectsTextOptions() {
for (String format : List.of("PARQUET", "FORMAT PARQUET", "FORMAT AS PARQUET", "format as parquet")) {
CopyStatementParser.S3CopyFrom spec = copyFrom(
"COPY tbl FROM 's3://b/prefix/' " + format + " MANIFEST COMPUPDATE OFF STATUPDATE OFF");
assertTrue(spec.parquet(), format);
assertTrue(spec.manifest(), format);
}
for (String option : List.of("CSV", "GZIP", "JSON 'auto'", "HEADER", "IGNOREHEADER 1",
"DELIMITER ','", "NULL AS 'nil'", "BLANKSASNULL", "EMPTYASNULL", "TRUNCATECOLUMNS",
"MAXERROR 5", "REGION 'us-east-1'", "PARQUET")) {
assertNull(CopyStatementParser.parse("COPY tbl FROM 's3://b/k' FORMAT AS PARQUET " + option), option);
}
}
@Test
@@ -5,7 +5,9 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.floci.duck.FlociDuckClient;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.testing.ParallelLocks;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.ResourceLock;
import org.mockito.ArgumentCaptor;
import java.io.ByteArrayInputStream;
@@ -18,6 +20,7 @@ import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ResourceLock(ParallelLocks.REDSHIFT_COPY_LIMITS)
class RedshiftParquetWriterTest {
@Test
void mapsDeclaredNumericTypesAndRejectsLossyConversions() {
@@ -105,17 +108,41 @@ class RedshiftParquetWriterTest {
}
@Test
void forwardsRoleSessionCredentialsToTheSidecar() throws Exception {
void mintsDedicatedStagingSessionPerTransferInsteadOfReusingCallerKey() throws Exception {
S3Service s3 = mock(S3Service.class);
IamService iam = mock(IamService.class);
FlociDuckClient duck = mock(FlociDuckClient.class);
when(duck.query(anyString(), anyString(), eq("access"), eq("secret"), eq("token")))
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.defaultRegion()).thenReturn("us-east-1");
when(config.defaultAccountId()).thenReturn("123456789012");
when(duck.query(anyString(), anyString(), anyString(), anyString(), anyString()))
.thenReturn(List.of(Map.of("filename", "s3://floci-internal-redshift-unload-staging/output/data_0.parquet")));
when(s3.openObjectStream(anyString(), anyString(), isNull()))
.thenReturn(new ByteArrayInputStream(new byte[0]));
RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("access", "secret", "token");
writer(s3, duck).convert(new byte[0], List.of(new RedshiftParquetWriter.Column("id", "INTEGER")),
"123456789012", session, 8192);
verify(duck).query(anyString(), anyString(), eq("access"), eq("secret"), eq("token"));
.thenReturn(new ByteArrayInputStream(new byte[0]), new ByteArrayInputStream(new byte[0]));
RedshiftRoleAccess.RoleSession callerKey = new RedshiftRoleAccess.RoleSession("AKIAUSERKEY", "secret", null);
RedshiftParquetWriter writer = new RedshiftParquetWriter(duck, s3, iam, config);
writer.convert(new byte[0], List.of(new RedshiftParquetWriter.Column("id", "INTEGER")),
"123456789012", callerKey, 8192);
writer.convert(new byte[0], List.of(new RedshiftParquetWriter.Column("id", "INTEGER")),
"123456789012", callerKey, 8192);
ArgumentCaptor<String> keys = ArgumentCaptor.forClass(String.class);
verify(duck, times(2)).query(anyString(), anyString(), keys.capture(), anyString(), anyString());
String firstKey = keys.getAllValues().get(0);
String secondKey = keys.getAllValues().get(1);
assertTrue(firstKey.startsWith("ASIA"));
assertTrue(secondKey.startsWith("ASIA"));
assertNotEquals("AKIAUSERKEY", firstKey);
assertNotEquals(firstKey, secondKey);
verify(iam).registerSessionForAccount(eq("123456789012"), eq(firstKey), anyString(), anyString(),
eq("arn:aws:iam::123456789012:role/floci-internal-redshift-staging"), any(), isNull());
verify(iam).registerSessionForAccount(eq("123456789012"), eq(secondKey), anyString(), anyString(),
eq("arn:aws:iam::123456789012:role/floci-internal-redshift-staging"), any(), isNull());
verify(iam).clearScratchResource(firstKey);
verify(iam).clearScratchResource(secondKey);
verify(iam).unregisterSession("123456789012", firstKey);
verify(iam).unregisterSession("123456789012", secondKey);
}
@Test
@@ -125,16 +152,20 @@ class RedshiftParquetWriterTest {
FlociDuckClient duck = mock(FlociDuckClient.class);
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.defaultRegion()).thenReturn("us-east-1");
when(duck.query(anyString(), anyString(), eq("access"), eq("secret"), eq("token")))
when(config.defaultAccountId()).thenReturn("123456789012");
when(duck.query(anyString(), anyString(), anyString(), anyString(), anyString()))
.thenThrow(new IllegalStateException("sidecar failed"));
RedshiftParquetWriter writer = new RedshiftParquetWriter(duck, s3, iam, config);
assertThrows(IllegalStateException.class, () -> writer.convert(new byte[0],
List.of(new RedshiftParquetWriter.Column("id", "INTEGER")), "123456789012",
new RedshiftRoleAccess.RoleSession("access", "secret", "token"), 8192));
ArgumentCaptor<String> stagingKey = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> scopes = ArgumentCaptor.forClass(String.class);
verify(iam).registerScratchResource(eq("access"), scopes.capture());
verify(iam).clearScratchResource("access");
assertTrue(scopes.getAllValues().get(0).matches(
verify(iam).registerScratchResource(stagingKey.capture(), scopes.capture());
verify(iam).clearScratchResource(stagingKey.getValue());
verify(iam).unregisterSession("123456789012", stagingKey.getValue());
assertNotEquals("access", stagingKey.getValue());
assertTrue(scopes.getValue().matches(
"arn:aws:s3:::floci-internal-redshift-unload-staging/unload/[0-9a-f-]{36}/"));
verify(s3).deleteObjectsWithPrefix(eq(RedshiftParquetWriter.STAGING_BUCKET), anyString(), any());
}
@@ -152,6 +183,103 @@ class RedshiftParquetWriterTest {
verify(s3, never()).putObject(anyString(), anyString(), any(byte[].class), anyString(), any());
}
@Test
void readToCsvStagesParquetDisablesHivePartitioningAndReservesHeapUntilClosed() throws Exception {
S3Service s3 = mock(S3Service.class);
IamService iam = mock(IamService.class);
FlociDuckClient duck = mock(FlociDuckClient.class);
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.defaultRegion()).thenReturn("us-east-1");
when(config.defaultAccountId()).thenReturn("123456789012");
byte[] parquet = "PAR1payloadPAR1".getBytes(StandardCharsets.UTF_8);
byte[] csv = "1,alice\n2,bob\n".getBytes(StandardCharsets.UTF_8);
when(s3.objectExists(eq(RedshiftParquetWriter.STAGING_BUCKET), startsWith("unload/"))).thenReturn(true);
when(s3.openObjectStream(eq(RedshiftParquetWriter.STAGING_BUCKET), startsWith("unload/"), isNull()))
.thenReturn(new ByteArrayInputStream(csv));
RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("AKIAUSER", "secret", null);
RedshiftParquetWriter writer = new RedshiftParquetWriter(duck, s3, iam, config);
int permitsBefore = S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.availablePermits();
try (RedshiftParquetWriter.StagedCsv result = writer.readToCsv(parquet, "123456789012", session)) {
assertArrayEquals(csv, result.bytes());
assertTrue(S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.availablePermits() < permitsBefore);
}
assertEquals(permitsBefore, S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.availablePermits());
ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> stagingKey = ArgumentCaptor.forClass(String.class);
verify(duck).query(sql.capture(), contains("SET threads = 1"), stagingKey.capture(), anyString(), anyString());
assertNotEquals("AKIAUSER", stagingKey.getValue());
assertTrue(sql.getValue().contains("read_parquet('s3://floci-internal-redshift-unload-staging/unload/"));
assertTrue(sql.getValue().contains("/input.parquet', hive_partitioning = false)"));
assertTrue(sql.getValue().contains("FORMAT CSV, HEADER false"));
verify(s3).putObject(eq(RedshiftParquetWriter.STAGING_BUCKET), endsWith("/input.parquet"),
eq(parquet), eq("application/octet-stream"), isNull());
verify(s3).registerScratchWriteLimit(eq(RedshiftParquetWriter.STAGING_BUCKET), endsWith("/output.csv"),
eq(S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES));
verify(s3).clearScratchWriteLimit(eq(RedshiftParquetWriter.STAGING_BUCKET), endsWith("/output.csv"));
verify(iam).registerScratchResource(eq(stagingKey.getValue()),
startsWith("arn:aws:s3:::floci-internal-redshift-unload-staging/unload/"));
verify(iam).clearScratchResource(stagingKey.getValue());
verify(iam).unregisterSession("123456789012", stagingKey.getValue());
verify(s3).deleteObjectsWithPrefix(eq(RedshiftParquetWriter.STAGING_BUCKET), startsWith("unload/"), any());
}
@Test
void readToCsvRejectsOversizedSourceAndStagedOutputExceedingLimit() throws Exception {
long previous = S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES;
int permitsBefore = S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.availablePermits();
S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES = 8;
try {
S3Service s3 = mock(S3Service.class);
FlociDuckClient duck = mock(FlociDuckClient.class);
S3CopySimulator.S3TransferException oversizedInput = assertThrows(S3CopySimulator.S3TransferException.class,
() -> writer(s3, duck).readToCsv("0123456789".getBytes(StandardCharsets.UTF_8), "123456789012", null));
assertEquals("54000", oversizedInput.sqlState());
verifyNoInteractions(duck);
when(duck.query(anyString(), anyString(), eq("123456789012")))
.thenThrow(new RuntimeException("HTTP 400 EntityTooLarge: upload exceeds limit"));
S3CopySimulator.S3TransferException cappedWrite = assertThrows(S3CopySimulator.S3TransferException.class,
() -> writer(s3, duck).readToCsv("PAR1".getBytes(StandardCharsets.UTF_8), "123456789012", null));
assertEquals("54000", cappedWrite.sqlState());
reset(duck);
when(s3.objectExists(eq(RedshiftParquetWriter.STAGING_BUCKET), startsWith("unload/"))).thenReturn(true);
when(s3.openObjectStream(eq(RedshiftParquetWriter.STAGING_BUCKET), startsWith("unload/"), isNull()))
.thenReturn(new ByteArrayInputStream("1,exceeds-eight-bytes\n".getBytes(StandardCharsets.UTF_8)));
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
() -> writer(s3, duck).readToCsv("PAR1".getBytes(StandardCharsets.UTF_8), "123456789012", null));
assertEquals("54000", error.sqlState());
assertEquals(permitsBefore, S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.availablePermits());
verify(s3, atLeastOnce()).deleteObjectsWithPrefix(eq(RedshiftParquetWriter.STAGING_BUCKET), startsWith("unload/"), any());
} finally {
S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES = previous;
}
}
@Test
void readToCsvFailsWhenSharedHeapBudgetIsExhausted() throws Exception {
int availableBefore = S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.availablePermits();
S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.acquireUninterruptibly(availableBefore);
try {
S3Service s3 = mock(S3Service.class);
FlociDuckClient duck = mock(FlociDuckClient.class);
when(s3.objectExists(eq(RedshiftParquetWriter.STAGING_BUCKET), startsWith("unload/"))).thenReturn(true);
when(s3.openObjectStream(eq(RedshiftParquetWriter.STAGING_BUCKET), startsWith("unload/"), isNull()))
.thenReturn(new ByteArrayInputStream("1,alice\n".getBytes(StandardCharsets.UTF_8)));
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
() -> writer(s3, duck).readToCsv("PAR1".getBytes(StandardCharsets.UTF_8), "123456789012", null));
assertEquals("53400", error.sqlState());
} finally {
S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.release(availableBefore);
}
assertEquals(availableBefore, S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.availablePermits());
}
private RedshiftParquetWriter writer(S3Service s3, FlociDuckClient duck) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.defaultRegion()).thenReturn("us-east-1");
@@ -58,6 +58,7 @@ import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@ResourceLock(value = ParallelLocks.PORTS, mode = ResourceAccessMode.READ)
@ResourceLock(ParallelLocks.REDSHIFT_COPY_LIMITS)
class S3CopySimulatorTest {
@Test
@@ -127,6 +128,48 @@ class S3CopySimulatorTest {
assertTrue(json.contains("20"));
}
@Test
void copyParquetStreamsConvertedCsvToBackendAndRejectsMissingDuckClient() throws Exception {
S3Service s3 = mock(S3Service.class);
byte[] parquetBytes = "PAR1dataPAR1".getBytes(StandardCharsets.UTF_8);
when(s3.objectExists("b", "p/part-0.parquet")).thenReturn(true);
when(s3.getObject("b", "p/part-0.parquet"))
.thenReturn(new S3Object("b", "p/part-0.parquet", parquetBytes, "application/octet-stream"));
RedshiftParquetWriter parquetWriter = mock(RedshiftParquetWriter.class);
when(parquetWriter.readToCsv(eq(parquetBytes), eq("000000000000"), isNull()))
.thenReturn(new RedshiftParquetWriter.StagedCsv("1,alice\n2,bob\n".getBytes(StandardCharsets.UTF_8), 0));
CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY people FROM 's3://b/p/part-0.parquet' FORMAT AS PARQUET");
assertEquals("COPY people FROM STDIN WITH (FORMAT csv, DELIMITER ',')", S3CopySimulator.copyBackendSql(spec));
S3CopySimulator.CopyInput input = S3CopySimulator.prepareCopy(spec, s3, null, "000000000000");
ByteArrayOutputStream backendOut = new ByteArrayOutputStream();
S3CopySimulator.streamCopyInput(input, null, null, null, backendOut, parquetWriter, "000000000000");
String streamed = backendOut.toString(StandardCharsets.UTF_8);
assertTrue(streamed.contains("1,alice\n2,bob\n"));
S3CopySimulator.S3TransferException missingDuck = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.streamCopyInput(input, null, null, null, new ByteArrayOutputStream(), null,
"000000000000"));
assertEquals("0A000", missingDuck.sqlState());
long saved = S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES;
S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES = 4;
try {
S3Object oversizedMeta = new S3Object("b", "p/part-0.parquet", new byte[0], "application/octet-stream");
oversizedMeta.setSize(1024);
when(s3.getObjectMetadata("b", "p/part-0.parquet", null)).thenReturn(oversizedMeta);
S3CopySimulator.S3TransferException oversized = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.streamCopyInput(input, null, null, null, new ByteArrayOutputStream(),
parquetWriter, "000000000000"));
assertEquals("54000", oversized.sqlState());
verify(s3, times(1)).getObject("b", "p/part-0.parquet");
} finally {
S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES = saved;
}
}
@Test
void quotedDefaultIsValidatedAsAnArnForCopyAndUnload() {
IamService iamService = mock(IamService.class);
@@ -35,6 +35,14 @@ public final class ParallelLocks {
/** The process-wide count of active Floci Docker callbacks. Producers read-lock; exact observers write-lock. */
public static final String DOCKER_ACTIVE_STREAMS = "floci-docker-active-streams";
/**
* Static COPY/UNLOAD size and heap ceilings on {@code S3CopySimulator}
* ({@code COPY_TRANSFORM_MAX_OBJECT_BYTES}, {@code COPY_TRANSFORM_HEAP_MIB},
* {@code UNLOAD_TARGET_FILE_BYTES}, {@code UNLOAD_MAX_TOTAL_BYTES}, {@code UNLOAD_HEAP_MIB}),
* which plain unit tests shrink or drain temporarily.
*/
public static final String REDSHIFT_COPY_LIMITS = "floci-redshift-copy-limits";
private ParallelLocks() {
}
}