rdblue commented on a change in pull request #796: Support Spark Structured Streaming Read for Iceberg URL: https://github.com/apache/incubator-iceberg/pull/796#discussion_r392452229
########## File path: spark/src/main/java/org/apache/iceberg/spark/source/StreamingReader.java ########## @@ -0,0 +1,298 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iceberg.spark.source; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.collect.Streams; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import org.apache.iceberg.CombinedScanTask; +import org.apache.iceberg.FileScanTask; +import org.apache.iceberg.Table; +import org.apache.iceberg.TableProperties; +import org.apache.iceberg.encryption.EncryptionManager; +import org.apache.iceberg.io.CloseableIterable; +import org.apache.iceberg.io.FileIO; +import org.apache.iceberg.util.SnapshotUtil; +import org.apache.iceberg.util.TableScanUtil; +import org.apache.spark.broadcast.Broadcast; +import org.apache.spark.sql.sources.v2.DataSourceOptions; +import org.apache.spark.sql.sources.v2.reader.streaming.MicroBatchReader; +import org.apache.spark.sql.sources.v2.reader.streaming.Offset; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A mirco-batch based Spark Structured Streaming reader for Iceberg table. It will track the added + * files and generate tasks per batch to process newly added files. By default it will process + * all the newly added files to the current snapshot in each batch, user could also set this + * configuration "max-files-per-trigger" to control the number of files processed per batch. + */ +class StreamingReader extends Reader implements MicroBatchReader { + private static final Logger LOG = LoggerFactory.getLogger(StreamingReader.class); + private static final int DEFAULT_MAX_FILES_PER_TRIGGER = 1000; + + private static final Comparator<FileScanTask> COMPARATOR = (left, right) -> { + int pathCompare = left.file().path().toString().compareTo(right.file().path().toString()); + int startCompare = Long.compare(left.start(), right.start()); + int lengthCompare = Long.compare(left.length(), right.length()); + return pathCompare == 0 ? (startCompare == 0 ? lengthCompare : startCompare) : pathCompare; + }; + + private StreamingOffset startOffset; + private StreamingOffset endOffset; + + private final Table table; + private final int maxFilesPerTrigger; + private final long splitSize; + private final int lookback; + private final long openFileCost; + private final Long startSnapshotId; + + /** + * Utility class to track the snapshotId, task and index of task within this snapshot. + */ + @VisibleForTesting + static class IndexedTask { + private final long snapshotId; + private final FileScanTask task; + private final int index; + + IndexedTask(long snapshotId, FileScanTask task, int index) { + this.snapshotId = snapshotId; + this.task = task; + this.index = index; + } + + long snapshotId() { + return snapshotId; + } + + FileScanTask task() { + return task; + } + + int index() { + return index; + } + } + + StreamingReader(Table table, Broadcast<FileIO> io, Broadcast<EncryptionManager> encryptionManager, + boolean caseSensitive, DataSourceOptions options) { + super(table, io, encryptionManager, caseSensitive, options); + + this.table = table; + this.maxFilesPerTrigger = + options.get("max-files-per-trigger").map(Integer::parseInt).orElse(DEFAULT_MAX_FILES_PER_TRIGGER); + Preconditions.checkArgument(maxFilesPerTrigger > 0, + "Option max-files-per-trigger '%d' should > 0", maxFilesPerTrigger); + + this.startSnapshotId = options.get("starting-snapshot-id").map(Long::parseLong).orElse(null); + if (startSnapshotId != null) { + if (!SnapshotUtil.ancestorOf(table, table.currentSnapshot().snapshotId(), startSnapshotId)) { + throw new IllegalStateException("The option starting-snapshot-id " + startSnapshotId + + "is not a valid snapshot id"); + } + } + + this.splitSize = options.get("split-size").map(Long::parseLong).orElse( + Optional.ofNullable(table.properties().get(TableProperties.SPLIT_SIZE)) + .map(Long::parseLong) + .orElse(TableProperties.SPLIT_SIZE_DEFAULT)); + this.lookback = options.get("lookback").map(Integer::parseInt).orElse( + Optional.ofNullable(table.properties().get(TableProperties.SPLIT_LOOKBACK)) + .map(Integer::parseInt) + .orElse(TableProperties.SPLIT_LOOKBACK_DEFAULT)); + this.openFileCost = options.get("file-open-cost").map(Long::parseLong).orElse( + Optional.ofNullable(table.properties().get(TableProperties.SPLIT_OPEN_FILE_COST)) + .map(Long::parseLong) + .orElse(TableProperties.SPLIT_OPEN_FILE_COST_DEFAULT)); + } + + @Override + @SuppressWarnings("unchecked") + public void setOffsetRange(Optional<Offset> start, Optional<Offset> end) { + table.refresh(); + + if (start.isPresent() && !StreamingOffset.START_OFFSET.equals(start.get())) { + this.startOffset = (StreamingOffset) start.get(); + this.endOffset = (StreamingOffset) end.orElse(calculateEndOffset(startOffset)); + } else { + // If starting offset is "START_OFFSET" (there's no snapshot in the last batch), or starting + // offset is not set, then we need to calculate the starting offset again. + this.startOffset = calculateStartingOffset(); + this.endOffset = calculateEndOffset(startOffset); + } + } + + @Override + public Offset getStartOffset() { + if (startOffset == null) { + throw new IllegalStateException("Start offset is not set"); + } + + return startOffset; + } + + @Override + public Offset getEndOffset() { + if (endOffset == null) { + throw new IllegalStateException("End offset is not set"); + } + + return endOffset; + } + + @Override + public Offset deserializeOffset(String json) { + return StreamingOffset.fromJson(json); + } + + @Override + public void commit(Offset end) { + // Since all the data and metadata of Iceberg is as it is, nothing needs to commit when + // offset is processed, so no need to implement this method. + } + + @Override + public void stop() {} + + @Override + @SuppressWarnings("unchecked") + protected List<CombinedScanTask> tasks() { + LOG.info("Processing data from {} exclusive to {} inclusive", startOffset, endOffset); + + if (startOffset.equals(StreamingOffset.START_OFFSET) || endOffset.equals(StreamingOffset.START_OFFSET)) { + return Collections.emptyList(); + } + if (startOffset.equals(endOffset)) { + return Collections.emptyList(); + } + + CloseableIterable<IndexedTask> tasks = + getChanges(startOffset.snapshotId(), startOffset.index(), startOffset.isStartingSnapshotId()); + List<IndexedTask> pendingTasks = Lists.newArrayList(); + for (IndexedTask t : tasks) { + if (t.snapshotId() == endOffset.snapshotId()) { + pendingTasks.add(t); + break; + } else { + pendingTasks.add(t); + } + } + + CloseableIterable<FileScanTask> splitTasks = TableScanUtil.splitFiles( + CloseableIterable.combine(pendingTasks.stream().map(IndexedTask::task).collect(Collectors.toList()), tasks), + splitSize); + return Lists.newArrayList( + TableScanUtil.planTasks(splitTasks, splitSize, lookback, openFileCost)); + } + + private StreamingOffset calculateStartingOffset() { + StreamingOffset startingOffset; + if (startSnapshotId != null) { + startingOffset = new StreamingOffset(startSnapshotId, -1, true); + } else { + List<Long> snapshotIds = SnapshotUtil.currentAncestors(table); + if (snapshotIds.isEmpty()) { + // there's no snapshot currently. + startingOffset = StreamingOffset.START_OFFSET; + } else { + startingOffset = new StreamingOffset(snapshotIds.get(snapshotIds.size() - 1), -1, true); + } + } + + return startingOffset; + } + + private StreamingOffset calculateEndOffset(StreamingOffset start) { + if (start.equals(StreamingOffset.START_OFFSET)) { + return StreamingOffset.START_OFFSET; + } + + CloseableIterable<IndexedTask> pendingTasks = getChanges(start.snapshotId(), start.index(), + start.isStartingSnapshotId()); + CloseableIterable<IndexedTask> rateLimitedTasks = rateLimit(pendingTasks, maxFilesPerTrigger); + IndexedTask last = Iterables.size(rateLimitedTasks) == 0 ? null : Iterables.getLast(rateLimitedTasks); + + if (last == null) { + return start; + } else { + boolean isStarting = last.snapshotId() == start.snapshotId() && start.isStartingSnapshotId(); + return new StreamingOffset(last.snapshotId(), last.index(), isStarting); + } + } + + @VisibleForTesting + CloseableIterable<IndexedTask> getChanges(long snapshotId, int index, boolean isStarting) { + List<CloseableIterable<IndexedTask>> indexedTasks = Lists.newArrayList(); + long currentSnapshotId = table.currentSnapshot().snapshotId(); + + if (isStarting) { + CloseableIterable<FileScanTask> iter = sortByFile(buildTableScan().useSnapshot(snapshotId).planFiles()); + List<IndexedTask> tasks = Streams.mapWithIndex(Streams.stream(iter), + (t, i) -> new IndexedTask(snapshotId, t, (int) i)) + .collect(Collectors.toList()); + indexedTasks.add(CloseableIterable.combine(tasks, iter)); + } + + Long start = isStarting ? Long.valueOf(snapshotId) : table.snapshot(snapshotId).parentId(); + Preconditions.checkState(start != null, "Start snapshot id should exist"); + ImmutableList<Long> snapshotIds = ImmutableList.<Long>builder() + .addAll(SnapshotUtil.snapshotIdsBetween(table, start, currentSnapshotId)) + .add(start) + .build() + .reverse(); + + for (int i = 0; i < snapshotIds.size() - 1; i++) { + long fromSnapshotId = snapshotIds.get(i); + long toSnapshotId = snapshotIds.get(i + 1); + + CloseableIterable<FileScanTask> iter = sortByFile( + buildTableScan().appendsBetween(fromSnapshotId, toSnapshotId).planFiles()); + List<IndexedTask> tasks = Streams.mapWithIndex(Streams.stream(iter), + (t, idx) -> new IndexedTask(toSnapshotId, t, (int) idx)) + .collect(Collectors.toList()); + indexedTasks.add(CloseableIterable.combine(tasks, iter)); + } + + return CloseableIterable.filter(CloseableIterable.concat(indexedTasks), + t -> t.snapshotId() != snapshotId || t.index > index); + } + + @VisibleForTesting + CloseableIterable<IndexedTask> rateLimit(CloseableIterable<IndexedTask> pendingTasks, int maxFiles) { + return CloseableIterable.combine(Iterables.limit(pendingTasks, maxFiles), pendingTasks); + } + + private CloseableIterable<FileScanTask> sortByFile(CloseableIterable<FileScanTask> tasks) { + List<FileScanTask> sortedFiles = Streams.stream(tasks) + .sorted(COMPARATOR) + .collect(Collectors.toList()); Review comment: This is still loading all tasks into memory, which could be very large if the table is big and this needs to handle the whole table. I think that sorting task files is probably the wrong design choice -- sorry that I suggested it! I think the right way is to disable the thread-pool used by `planFiles` so that the order is reliable. I suggested earlier to sort the manifest files, but disabling the thread-pool should have the same effect to make behavior deterministic. I took a look at disabling the thread-pool and you can do it easily by adding an option to the scan, like this: ```java buildTableScan().option("use-worker-pool", "false").useSnapshotId(...).planFiles(); ``` Then I changed `DataTableScan.planFiles` to use the new option: ```java boolean useWorkerPool = PropertyUtil.propertyAsBoolean(options(), "use-worker-pool", PLAN_SCANS_WITH_WORKER_POOL); if (useWorkerPool && snapshot.manifests().size() > 1) { manifestGroup.planWith(ThreadPools.getWorkerPool()); } ``` Then you have deterministic behavior without loading all data files into memory at once. ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: us...@infra.apache.org With regards, Apache Git Services --------------------------------------------------------------------- To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org For additional commands, e-mail: issues-h...@iceberg.apache.org