Skip to content

Flink: auto compact small files - #3213

Closed
myandpr wants to merge 5 commits into
apache:mainfrom
myandpr:flink-auto-compact-small-file
Closed

myandpr wants to merge 5 commits into
apache:mainfrom
myandpr:flink-auto-compact-small-file

Conversation

@myandpr

@myandpr myandpr commented Oct 2, 2021 •

Copy link
Copy Markdown
Contributor

What problem does this pr solved?

when we write data into icebeg table using flink, it will produce a lot of small files.

This branch supports compacting small files automatically when writing data into iceberg table for flink.

How was this problem solved?

We added the following configuration

// auto compact
write.flink.auto-compact.enabled
write.flink.compact.interval-ms
write.flink.compact.target-file-size-bytes
write.flink.compact.small-file-size-bytes   (small file size threshold)
write.flink.compact.small-file-nums          (small file number threshold)

In this PR, we add 3 operators(CompactFileGenerator, CompactFileOperator, CompactFileCommitter) for compaction function.

Compact function:

  1. In IcebergFilesCommitter.notifyCheckpointComplete(), we emit a 'EndCheckpoint' message to downstream operator 'CompactFileGenerator'.
  2. ‘CompactFileGenerator’ generates all 'CombinedScanTask' that needs to be rewrited and distributes them to downstream operator 'CompactFileOperator'.
  3. 'CompactFileOperator' starts actually compacting files in parallel when receiving upstream 'CombinedScanTask' and emit compaction result to downstream operator 'CompactFileCommitter'.
  4. 'CompactFileCommitter' commits a compaction transaction and emit 'EndCheckpoint' message to downstream 'ExpireSnapshotGenerator' when receiving all compaction results from upstream.

@myandpr

myandpr commented Oct 2, 2021

Copy link
Copy Markdown
Contributor Author

@rdblue @kbendick @stevenzwu , could you help to review this PR? :)

@rdblue

rdblue commented Oct 3, 2021

Copy link
Copy Markdown
Contributor

I'll take a look. The first thing is separating the features into different PRs. Can you open a PR for auto-compaction and one for automatic expiration?


@Override
protected void validate(TableMetadata base) {
// update startingSnapshotId.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changing the starting snapshot ID breaks the correctness of certain operations, so I don't think that's what you want to do. What are you trying to do here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We ran into a problem in v2 format when we compact files and delete expired files at the same time .
I found a related issue #2482, but this issue has no follow-up conclusion.

This is other relate issue #2371, and I used #2511 to temporarily solve this problem #2482

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I found the underlying problem. See my comment on #2482: #2482 (comment)

}
}

public ExpireSnapshotResult getExpiredSnapshotResult() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Iceberg doesn't use get in method names because it signals that either there is a better noun (like find) or it is unnecessary and should be omitted.

});
deleteDataFiles(manifestsToScan, manifestsToRevert, validIds);
deleteMetadataFiles(manifestsToDelete, manifestListsToDelete);
if (cleanExpiredFiles) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't cleanExpiredFiles always true if this is reached?

.rewriteFiles(Sets.newHashSet(currentDataFiles), Sets.newHashSet(dataFiles));
rewriteFiles.commit();
table.updateProperties()
.set(TableProperties.WRITE_COMPACT_LAST_REWRITE_MS, Long.toString(System.currentTimeMillis()))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Table properties should not be updated to keep track of this kind of information. Instead, keep it in snapshot properties by calling set on rewriteFiles.

.caseSensitive(caseSensitive)
.ignoreResiduals()
.filter(filter)
.planFiles();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it is a good idea to attempt to compact the entire table.

The design that we've talked about for this feature is to emit the DataFile instances from the committer after a successful commit. Then add a keyBy to group the data files by partition in parallel tasks and finally to have each task compact the data files when enough data arrives. Then that compaction writer sends a list of data files to replace and the rewritten data file to another committer that also commits on checkpoint boundaries. Any commit that fails is simply ignored at that point.

I think that's a better model than performing a full table scan.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let me make sure I understand. In IcebergFilesCommitter.notifyCheckpointComplete(), we emit DataFile that need to be compacted to downstream after a successful commit.

But there is a problem. IcebergFilesCommitter only committed the files added in current checkpoint and emited them to downstream. Some files that have not been compacted will never be compacted.

e.g.

compact target fise size: 10M
checkpoint:1, added files(f1->5M, f2->5M, f3->1M), compact files: (f1->5M, f2->5M) -> 10M
checkpoint:2, added files(f1->5M,f2->2M, f3->2M, f4->3M), compact files(f1->5M,f2->2M, f3->2M) -> 9M

so, f3 in checkpoint 1 and f4 in checkpoint 2 will never be compacted.

And could you send me the design document about auto compacting small files? Maybe I have not seen the discussion of compacting small files.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the misunderstanding is that this should not just compact within a checkpoint, but across checkpoints.

Say you have writers w1 and w2 producing files for partitions p1 and p2 in checkpoints c1, c2, etc. You end up writing
p1/w1-c1, p2/w1-c1, p1/w2-c1, p2/w2-c1, p1/w1-c2, p2/w1-c2, p1/w2-c2, p2/w2-c2, p1/w1-c3, p2/w1-c3, p1/w2-c3, p2/w2-c3, and so on.

As those files are committed, they get sent to compactor tasks keyed by partition. So one gets p1/w1-c1, p1/w2-c1, p1/w1-c2, p1/w2-c2, ... and another task gets p2/w1-c1, p2/w2-c1, p2/w1-c2, p2/w2-c2, ... Those can be compacted together. The main benefit of compaction is to compact across checkpoints. As files arrive, the compactor task checks whether a file should be added to the currently open file or if it should start a new file. When it starts a new file because some limit has been reached, then it emits the files it compacted to swap. For example, (p1/w1-c1, p1/w2-c1, p1/w1-c2) for p1/c1-c2-compacted.

Note that:

  • No table scanning is required
  • Only files produced by this Flink job will be compacted, so parallel jobs don't conflict with one another

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the patient explanation, @rdblue . I think I understand what you mean.

This solution is obviously better, I will implement the function of compacting small files later.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, @myandpr! It's great to have someone working on this!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hugely agree on the above. Thank you so much for your work on this @myandpr! This will be greatly appreciated by the community! 🙂

@rdblue

rdblue commented Oct 3, 2021

Copy link
Copy Markdown
Contributor

Thanks for working on this, @myandpr. I took a quick look at mainly the file compaction part. I think that the implementation here is inspired by the batch compaction planning, but there is a much better way to do it for streaming. I think that this should go with a model that's more designed for Flink instead to avoid full (or large) table scans in the compaction planner.

@kbendick

kbendick commented Oct 5, 2021 •

Copy link
Copy Markdown
Contributor

@rdblue @kbendick @stevenzwu , could you help to review this PR? :)

Thanks for working on this @myandpr. I am off this week but am interested in this so will review but might be a bit slow to respond. 🙂

I agree with @rdblue's that it makes sense to avoid trying to compact the whole table (or scan the whole table) in an online streaming context, but rather pass around the file names that need to be compacted and committed.

@kbendick

kbendick commented Oct 5, 2021

Copy link
Copy Markdown
Contributor

I'll take a look. The first thing is separating the features into different PRs. Can you open a PR for auto-compaction and one for automatic expiration?

I also agree that this seems like a good candidate for multiple PRs. If it helps you, you can keep things together for shared functionality and then branch off of that for the two PRs (or some other approach to help consume in smaller parts overall).

@kbendick kbendick left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left some initial feedback. Thanks again for working on this. Would be great to have it split into two PRs as mentioned 🙂.

}

public ExpireSnapshotResult getExpiredSnapshotResult() {
cleanExpiredSnapshots();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there any way to avoid this side-effecting call in this function? Maybe Ryan's comment that there's a more appropriate noun is relevant as I don't typically expect a getter to have side effects.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fine, i will refactor the code later.

/**
* Returns whether small files should be merged.
*/
public static boolean shouldMergeSmallFiles(Table table) {

@kbendick kbendick Oct 5, 2021 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Presently, users can bin-pack data using Spark. I believe it uses a threshold on the lower bound that's not a simple check if the file is smaller than the small file size, but some fraction of a target size.

A simple size check might be best here, but it would be great if the continuous Flink action could compact files in a way that would return results that wouldn't be further changed by calling the Spark size based bin-packing action (haven't checked yet if that's the case here but wanted to draw your attention to that).

I'd love to hear other's opinions on this though 🙂

/**
* Returns whether expire snapshot files should be removed.
*/
public static boolean shouldExpireSnapshot(Table table) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In my eyes, this doesn't exactly fit into a "SmallFileUtil". The snapshot expiration is time based, not size based. Does it make sense to move it elsewhere? Possibly there's similar code within the Spark actions for maintaining snapshots that can be leveraged or shared.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about changing this class name SmallFileUtil to ExpireSnapshotUtil as follows

@fapaul

fapaul commented Oct 5, 2021

Copy link
Copy Markdown

Hi folks,

I am an Apache Flink contributor and we are currently evaluating different options for this "small-file" problem. So far we only support the compaction of small files when using the StreamingFileSink [1]. Apparently, you have implemented your own way of writing files before committing them to Iceberg I'd also be happy to know the reason.

We are open to feedback on what you need from Flink to support your use case because we are seeing a lot of other projects hitting the same problems (Hive, DeltaLake etc.)

[1] https://github.com/apache/flink/blob/ac203a7a26d78fe270bd9941bb721be53a893040/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/filesystem/stream/StreamingSink.java#L82

@rdblue

rdblue commented Oct 5, 2021

Copy link
Copy Markdown
Contributor

@fapaul, Iceberg has its own file writers because we track more information for each column. Schema evolution is done using field IDs rather than names so that we can make all schema evolution metadata operations that are side-effect free. We also track additional metadata so that we can prune more unnecessary files at jobs planning time.

As for the design here, I think that we have a good plan but no one has picked up the implementation of it yet. We plan to send the files that were committed from the committer to a parallel set of tasks to rewrite them, keyed by partition. When there is enough file content, the compactor tasks will release the new data file and the set of files to replace to a compaction committer, which will commit the compactions it receives in a given checkpoint. You could do the same with other formats, I guess.

@myandpr myandpr closed this Oct 8, 2021
@myandpr myandpr reopened this Oct 8, 2021
@myandpr myandpr changed the title Flink: auto compact small files and expire snapshots Flink: auto compact small files Oct 8, 2021
@myandpr

myandpr commented Oct 8, 2021

Copy link
Copy Markdown
Contributor Author

I'll take a look. The first thing is separating the features into different PRs. Can you open a PR for auto-compaction and one for automatic expiration?

@rdblue I’m on vacation and can’t connect to github, so the reply is a bit slow. I think you are right, and I have separated this PR into auto compaction PR and expire snapshot PR. This PR is for 'suto compact small files', and I will commit a new PR 'expire snapshot' later.

@myandpr

myandpr commented Oct 8, 2021

Copy link
Copy Markdown
Contributor Author

I'll take a look. The first thing is separating the features into different PRs. Can you open a PR for auto-compaction and one for automatic expiration?

I also agree that this seems like a good candidate for multiple PRs. If it helps you, you can keep things together for shared functionality and then branch off of that for the two PRs (or some other approach to help consume in smaller parts overall).

Hi @kbendick , sorry for the late reply, because I am on vacation and cannot connect to GitHub these days.

I have separated this PR into Flink: auto compact small files PR #3213 and [Iceberg] Flink:auto delete expired snapshots PR #3255

You can continue to review the two PRs in #3255 and #3213

@myandpr

myandpr commented Oct 8, 2021

Copy link
Copy Markdown
Contributor Author

@rdblue @kbendick @stevenzwu , could you help to review this PR? :)

Thanks for working on this @myandpr. I am off this week but am interested in this so will review but might be a bit slow to respond. 🙂

I agree with @rdblue's that it makes sense to avoid trying to compact the whole table (or scan the whole table) in an online streaming context, but rather pass around the file names that need to be compacted and committed.

Hi @kbendick , I'd like to hear your opinion on my doubts https://github.com/apache/iceberg/pull/3213#discussion_r724905119🙂

@kbendick

Copy link
Copy Markdown
Contributor

@rdblue @kbendick @stevenzwu , could you help to review this PR? :)

Thanks for working on this @myandpr. I am off this week but am interested in this so will review but might be a bit slow to respond. 🙂
I agree with @rdblue's that it makes sense to avoid trying to compact the whole table (or scan the whole table) in an online streaming context, but rather pass around the file names that need to be compacted and committed.

Hi @kbendick , I'd like to hear your opinion on my doubts https://github.com/apache/iceberg/pull/3213#discussion_r724905119🙂

Hi @myandpr! Sorry I was also out of office for a bit so catching up on things still somewhat. Will take a look ASAP!

new Date(lastCommittedTimestamp),
smallFileThreshold);

if (autoMergeEnable && (currentTimeMillis - lastCommittedTimestamp >= mergeIntervalMillis ||

@kbendick kbendick Oct 18, 2021 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of just using a no-op, would it make more sense to skip adding these operators to the DAG if they're not used?

Comment on lines +306 to +316
SingleOutputStreamOperator<EndCheckpoint> committerStream = appendCommitter(writerStream);

// Add single-parallelism compact task generator
SingleOutputStreamOperator<CommonControllerMessage> compactStream = appendCompactGenerator(committerStream);

// Add parallel rewrite task operator
SingleOutputStreamOperator<CommonControllerMessage> rewriteStream =
appendCompactOperator(compactStream.broadcast());

// Add single-parallelism compact committer operator
SingleOutputStreamOperator<Void> compactCommitterStream = appendCompactCommitter(rewriteStream);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Commented above, but do we think we should avoid adding the additional nodes to the user's jobgraph if they've disabled compaction? It's extra processing time and resources that aren't necessarily needed if they're not doing anything. Would also help to visually see that you're not compacting files when you (as a user) look at the job graph.

If users enable it, and it adds to their job graph and they don't properly handle UIDs, given that we properly handle UIDs on our added operators, I can't remember if that causes issues or not. Is likely a concern we should look into as I know that not properly handling UIDs with job graph changes has caused some of my users to have to abandon state before.

But for me, it feels like we shouldn't add unused processing nodes to the job graph is this whole workflow is disabled (e.g. users might choose to focus their flink compute on just writing as Flink doesn't autoscale as well as some might like it to and instead compact files in a separate workflow entirely, maybe with Spark even).

@kbendick

Copy link
Copy Markdown
Contributor

Hi folks,

I am an Apache Flink contributor and we are currently evaluating different options for this "small-file" problem. So far we only support the compaction of small files when using the StreamingFileSink [1]. Apparently, you have implemented your own way of writing files before committing them to Iceberg I'd also be happy to know the reason.

We are open to feedback on what you need from Flink to support your use case because we are seeing a lot of other projects hitting the same problems (Hive, DeltaLake etc.)

[1] https://github.com/apache/flink/blob/ac203a7a26d78fe270bd9941bb721be53a893040/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/filesystem/stream/StreamingSink.java#L82

Hi @fapaul! I wanted to firstly thank you for dropping by and introduce myself. I believe Ryan already answered your questions, but if you have any other questions you can always feel free to reach out to me (or anyone) and I'd be happy to help or try to point you in the right place. I often work or review Flink-Iceberg related stuff and there are some things I've seen here and there that might have been helpful for us or would be helpful for us in the future. Hope to collaborate with you over there or in here in the future! 🙂

@fapaul

fapaul commented Oct 19, 2021

Copy link
Copy Markdown

@kbendick
thanks for the introduction. I think @rdblue already made a good point noting that Flink's current FileSink is not extensible enough and can thereof not support most of the use cases. We are currently working on bringing compaction to the FileSink and as a next step try to generify it to support more usecases.

One thing I am still curious about is what drove the decision that the Flink Iceberg connector is built with the low-level operator API rather than using the unified Sink interface[1].
In general, we designed the interface to allow users to support batch and streaming executions without the need to worry about the different semantics.

I know there have been problems in the past about Flink's API stability and I am a bit worried that the operator model the Iceberg Sink currently uses, might be become difficult to maintain in the future.

Sorry for abusing this pull request thread for some general discussion ...

[1] https://cwiki.apache.org/confluence/display/FLINK/FLIP-143%3A+Unified+Sink+API

@stevenzwu

Copy link
Copy Markdown
Contributor

@fapaul current Flink Iceberg connector was implemented before the FLIP-143 unified sink API. I have participated in the discussion for FLIP-143 interfaces and make sure the requirements for Iceberg sink are reflected in the new FLIP-143 sink interface [1].

Nobody has got time to pick up the work of moving to the new sink API. Also we are waiting for the new sink interface to mature/stabalize.

[1] https://www.mail-archive.com/[email protected]&q=subject:%22Re%5C%3A+%5C%5BDISCUSS%5C%5D+FLIP%5C-143%5C%3A+Unified+Sink+API%22&o=newest&f=1

Comment on lines +132 to +136
Joiner.on(", ").join(task.getCombinedScanTask().files().stream()
.map(t -> t.file().content() + "=>" + t.file().fileSizeInBytes() / 1024 / 1024 + "M")
.collect(Collectors.toList())),
task.getCombinedScanTask().files().size(),
endCheckpoint.getCheckpointId());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

feels a method on Task is better to display these infos

@github-actions

Copy link
Copy Markdown

This pull request has been marked as stale due to 30 days of inactivity. It will be closed in 1 week if no further activity occurs. If you think that’s incorrect or this pull request requires a review, please simply write any comment. If closed, you can revive the PR at any time and @mention a reviewer or discuss it on the [email protected] list. Thank you for your contributions.

@github-actions github-actions Bot added the stale label Jul 28, 2024
@github-actions

github-actions Bot commented Aug 5, 2024

Copy link
Copy Markdown

This pull request has been closed due to lack of activity. This is not a judgement on the merit of the PR in any way. It is just a way of keeping the PR queue manageable. If you think that is incorrect, or the pull request requires review, you can revive the PR at any time.

@github-actions github-actions Bot closed this Aug 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants