Skip to content

[WriteFiles] Support direct writes of large streaming bundles to temp files (#40533) - #40543

Open
tejasiyer-dev wants to merge 27 commits into
apache:masterfrom
tejasiyer-dev:gcs-direct-write
Open

tejasiyer-dev wants to merge 27 commits into
apache:masterfrom
tejasiyer-dev:gcs-direct-write

Conversation

@tejasiyer-dev

@tejasiyer-dev tejasiyer-dev commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #40533

Summary

This PR adds an optional direct-write byte threshold that allows sufficiently large streaming bundles to write directly to temporary files, while routing smaller bundles through the existing grouped write path. Similar to IcebergIO direct write (#36720).

Changes

  • BundleLifter:
    • Updated BundleLifter to evaluate the byte threshold per (window, pane, key) (or per bundle when unkeyed) using coder-based byte-size estimation, streaming subsequent elements for a key directly to the large output once the threshold is reached.
    • Added a configurable maxBufferedBytes memory cap (defaulting to 2 * threshold) that evicts the smallest buffered keys to the small output and routes newly seen keys directly to the small output once hit.
    • Added a configurable maxLiftedKeys limit (unlimited by default). Once reached, remaining buffered keys go to the small output and newly seen keys are routed there directly.
  • WriteFiles:
    • Added withDirectWriteByteThreshold(long) to configure the byte threshold for direct writes. Falls back to the standard path with a warning for bounded inputs without a fixed shard count, side-input dynamic destinations, merging windows, or accumulating panes.
    • Direct write runs as pre-processing in expand, using BundleLifter keyed by destination with maxLiftedKeys = maxNumWritersPerBundle:
      • Large (window, pane, destination) groups (>= thresholdBytes): Written directly to temporary files via the existing WriteUnshardedTempFilesFn without shuffling.
      • Remaining records: Routed through WriteShardedBundlesToTempFiles (when a shard count is configured) or GroupIntoBatches.withShardedKey() (when auto-sharded), then merged with the direct-write FileResults and finalized together, with shard numbers assigned in finalize. With a fixed shard count, the number of files per window may differ from the configured count.
  • TextIO & FileIO:
    • Added .withDirectWriteByteThreshold(long) pass-through methods to TextIO.Write, TextIO.TypedWrite, and FileIO.Write.
  • DataflowRunner:
    • StreamingShardedWriteFactory now reuses the original WriteFiles and only applies withNumShards, instead of constructing a new one and copying selected options. This also fixes other options (e.g. batchSize) being dropped on that path.
  • Metrics:
    • Added counter under WriteFiles: directWriteBundles.

Testing

  • Added unit tests in BundleLifterTest covering streaming past threshold, per-key and per-window threshold evaluation, unkeyed bundles, null keys, maxBufferedBytes eviction and untracked-key routing, window/timestamp preservation, and coder-based sizing.
  • Added pipeline tests in WriteFilesTest:
    • testDirectWriteAllBundlesLarge (large bundles bypass shuffle and write directly)
    • testDirectWriteAllBundlesSmall (small bundles fall back to the grouped write path)
    • testDirectWriteUnshardedMixedBundles (exercises both direct-write and auto-sharded fallback paths in the same pipeline)
    • testDirectWriteThresholdIsPerDestination & testDirectWriteLargeAndSmallDestinationsInOneBundle (verifies per-destination threshold isolation)
    • testDirectWriteNonDefaultTriggerLargeBundles & testDirectWriteNonDefaultTriggerSmallBundles (verifies non-default user triggers across both paths)
    • testDirectWriteDisabledWithSideInputs & testDirectWriteDisabledWithMergingWindows (verifies fallback when ineligible)
  • Added Dataflow runner override tests in DataflowRunnerTest:
    • testStreamingWriteWithDirectWriteByteThreshold
    • testStreamingWriteDirectWriteThresholdDefaultNull
  • Added configuration pass-through tests in TextIOWriteTest and FileIOTest.

Benchmark Results (Dataflow Streaming, 60-min steady state)

Evaluated with a streaming pipeline writing ~82 MB/s (20,000 × 4 KB elements/sec, 1-min FixedWindows) to GCS via TextIO.write().withWindowedWrites().withAutoSharding() on 12 × n1-standard-4 workers (autoscaling disabled):

  • Baseline: --directWriteByteThreshold=0 (all elements shuffled through GroupIntoBatches)
  • Direct Write: --directWriteByteThreshold=16777216 (16 MB threshold)

Highlights:

  • 45% lower mean worker CPU utilization: 7.59% → 4.17%
  • 90.6% fewer GCS output files (10.6× fewer) for the same ~308 GB written: 21,254' files (~14.5 MBmean) →2,000 files (~154 MB` mean).
  • 99.99% less Streaming Engine shuffle/state overhead (Total streaming data processed): 1.04 TB → 78.63 MB while writing the same ~308 GB to GCS.

Worker CPU Utilization (Baseline = blue, Direct Write = purple)

image

Finalized Output Files — Before vs. After

image image

Streaming Data Processed (Before vs. After)

image image

@github-actions

Copy link
Copy Markdown
Contributor

Checks are failing. Will not request review until checks are succeeding. If you'd like to override that behavior, comment assign set of reviewers

@codecov

codecov Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 4.52675% with 232 lines in your changes missing coverage. Please review.
✅ Project coverage is 64.98%. Comparing base (76f6e6d) to head (3e064fd).
⚠️ Report is 319 commits behind head on master.

Files with missing lines Patch % Lines
...c/main/java/org/apache/beam/sdk/io/WriteFiles.java 1.33% 221 Missing and 1 partial ⚠️
...g/apache/beam/runners/dataflow/DataflowRunner.java 55.55% 3 Missing and 1 partial ⚠️
...e/src/main/java/org/apache/beam/sdk/io/FileIO.java 25.00% 2 Missing and 1 partial ⚠️
...e/src/main/java/org/apache/beam/sdk/io/TextIO.java 40.00% 1 Missing and 2 partials ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master   #40543      +/-   ##
============================================
+ Coverage     56.16%   64.98%   +8.81%     
- Complexity     2288    13977   +11689     
============================================
  Files          1124     1729     +605     
  Lines        178336   108641   -69695     
  Branches       1489    11332    +9843     
============================================
- Hits         100170    70595   -29575     
+ Misses        75645    33838   -41807     
- Partials       2521     4208    +1687     
Flag Coverage Δ
go ?
java 64.98% <4.52%> (-10.81%) ⬇️
python ?

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @ahmedabu98 for label java.
Backup reviewer: chamikaramj (if the main reviewer is unresponsive, you can escalate to them by tagging their username)

This pull request likely touches a core component ("core" label). Please review with scrutiny.

Note: If you would like to opt out of this review, comment assign to next reviewer.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

The PR bot will only process comments in the main thread (not review comments).

@tejasiyer-dev

Copy link
Copy Markdown
Contributor Author

R: @arunpandianp

@github-actions

Copy link
Copy Markdown
Contributor

Stopping reviewer notifications for this pull request: review requested by someone other than the bot, ceding control. If you'd like to restart, comment assign set of reviewers

@arunpandianp

Copy link
Copy Markdown
Contributor

Can we move sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/BundleLifter.java into sdks/java/io/common and reuse it?

@arunpandianp

Copy link
Copy Markdown
Contributor

cc: @tomstepp

@tomstepp

Copy link
Copy Markdown
Contributor

Agreed, it would be nice to move and reuse BundleLifter

@ahmedabu98

Copy link
Copy Markdown
Contributor

+1 to that, but please make sure it doesn't break streaming update compatibility for the iceberg sink

@tejasiyer-dev

Copy link
Copy Markdown
Contributor Author

Can we move sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/BundleLifter.java into sdks/java/io/common and reuse it?

I think moving BundleLifter to sdks/java/io/common would create a circular dependency. sdks/java/io/common already depends on sdks/java/core and WriteFiles is in sdks/java/core, so to use BundleLifter from io/common, core would also have to depend on io/common.

Would moving BundleLifter to core be better? Iceberg already depends on Core so both Iceberg and WriteFiles could share it with no new dependencies

@chamikaramj

Copy link
Copy Markdown
Contributor

@ahmedabu98 PTAL.

Also, seems like BundleLifter move is unrelated and probably should be a separate PR ?

@arunpandianp

Copy link
Copy Markdown
Contributor

Would moving BundleLifter to core be better?

I think that is okay. We could move it to sdks/java/core/src/main/java/org/apache/beam/sdk/util and mark it with @org.apache.beam.sdk.annotations.Internal

@ahmedabu98 ahmedabu98 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.

Generally LGTM, just a nit about modularization and small question about the experiment flag

TupleTagList.of(ImmutableList.of(smallBundlesTag, BAD_RECORD_TAG))));
addErrorCollection(routed);

PCollection<UserT> smallBundles = routed.get(smallBundlesTag).setCoder(input.getCoder());

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 a way to reuse the existing pipeline graph (built in WriteFilesResult's expand) and pass smallBundles through to it? Instead of attempting to recreate the same steps here?

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 see you did a good amount for that using writeAutoShardedRecordsToTempFiles(...). Wondering if other parts can be similarly modularized

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.

Partly. The small bundles now reuse the existing write steps, and both paths share the grouping steps and batch-size defaults through new helpers.

The small bundles can't go through the entire existing graph, though. If they did, the direct-write files and the small-bundle files would each go through a separate finalize step, and their file names would collide. Instead, both sets of temp files are merged before finalize, so a single finalize step assigns unique shard numbers to every file in the window.

Comment thread CHANGES.md Resolved
Comment thread CHANGES.md Outdated
* The `disableCounterMetrics`, `disableStringSetMetrics` and `disableBoundedTrieMetrics` experiments are now honored by the Python SDK, as they already were in Java (Python) ([#38746](https://github.com/apache/beam/issues/38746)).
* (Go) Pipeline-level `--resource_hints` are now forwarded to expansion services, so they apply to cross-language transforms as they do in the Java and Python SDKs. The `max_active_bundles_per_worker` hint name is now also accepted by `--resource_hints` ([#23893](https://github.com/apache/beam/issues/23893)).
* ReadFromBigQuery now supports Lakehouse runtime catalog (BigLake metastore) tables with `method=DIRECT_READ`, using 4-part `project.catalog.namespace.table` identifiers. Previously `project:catalog.namespace.table` was silently mis-parsed and tables that report no `numBytes` failed to split (Python) ([#39597](https://github.com/apache/beam/issues/39597)).
* (Java) `TextIO`, `FileIO`, and `WriteFiles`: streaming writes can skip the shuffle for large bundles by writing them directly to temp files (`withDirectWriteByteThreshold` or experiment `streaming_file_direct_write_threshold_bytes`). Off by default ([#40533](https://github.com/apache/beam/issues/40533)).

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.

Not seeing thestreaming_file_direct_write_threshold_bytes flag in the code here. is it in the Dataflow service?

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.

No, it's not in the Dataflow service. I removed that experiment so direct write is configured only through withDirectWriteByteThreshold (matching Iceberg), but forgot to update CHANGES.md. Fixed now, thanks!

Comment on lines +1418 to +1422
for (BufferedRecord<UserT> record : buffer) {
c.output(smallBundlesTag, record.value, record.timestamp, record.window);
}
for (BufferedRecord<UserT> record : spilled) {
c.output(smallBundlesTag, record.value, record.timestamp, record.window);

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.

seems like this will reorder outputs. Can we preserve the order?

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.

The two loops are no longer back to back and each one now sits inside its own branch, so only one runs per bundle.

Direct mode: the buffer is flushed when we switch, so only spilled is emitted.
Grouped mode: nothing is written directly, so only buffer is emitted.

Each list is emitted in arrival order, so nothing gets reordered.

public void finishBundle(FinishBundleContext c) throws Exception {
if (directMode) {
directBundles.inc();
} else if (!buffer.isEmpty()) {

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.

since directMode, !buffer.isEmpty() can both be true, do we need the else 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.

Yes, the else is needed, because directMode and !buffer.isEmpty() can't both be true: the buffer is flushed and cleared the moment we switch to direct mode.

@github-actions github-actions Bot added the size/xl XL: >=1000 lines changed label Nov 3, 2026
@arunpandianp

Copy link
Copy Markdown
Contributor

Should we restrict this feature to only work with AutoSharding? Not sure if it is compatible with fixed sharding, as users might expect a fixed number of files in that case. cc: @scwhittle


Long directWriteThreshold = getDirectWriteThreshold(transform);
if (directWriteThreshold != null) {
replacement = replacement.withDirectWriteByteThreshold(directWriteThreshold);

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.

why do we need to copy directWriteThreshold this here? WriteFiles have many other options (eg: batchSize) that are not 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.

The override builds a new WriteFiles.to(sink) and only copies side inputs, windowed writes and autosharding, so without this line the threshold would be null on Dataflow streaming and direct write would never run there.

You're right that batchSize and the others aren't copied, so they're silently ignored on this path today. Should I copy all of them in this PR, or do it as a follow-up?

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.

Done. The override now reuses the user's WriteFiles and only applies withNumShards, instead of building a new WriteFiles.to(sink) and copying options onto it. Options that were being dropped on this path (batchSize, maxNumWritersPerBundle, the error handler, etc.) now take effect on Dataflow streaming.

Comment on lines +1270 to +1286
if (getComputeNumShards() != null || getNumShardsProvider() != null) {
groupedFiles =
smallBundles
.apply(
"WriteShardedBundlesToTempFiles",
new WriteShardedBundlesToTempFiles(
destinationCoder, fileResultCoder, numShardsView))
.apply(
"DropShardNum",
ParDo.of(
new DoFn<FileResult<DestinationT>, FileResult<DestinationT>>() {
@ProcessElement
public void process(ProcessContext c) {
c.output(c.element().withShard(UNKNOWN_SHARDNUM));
}
}))
.setCoder(fileResultCoder);

@arunpandianp arunpandianp Nov 17, 2026 •

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.

If we are supporting only autosharding, i think this block can be removed.

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.

Removed.

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.

Update: we decided to keep fixed sharding, so this block is back. It now lives inline in expand()

}

/**
* Returns a new {@link WriteFiles} that fuses with preceding stages and writes large input from a

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.

sorry, I think I suggested it but on re-reading "large input" sounds possibly confusing with large elements not the amount of input.

Maybe "and writes directly to temporary files without shuffling if the provided threshold is reached within a single bundle processing."

writes directly to a temporary files if the provided threshold is exceeded.

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.

Updated.

* Returns a new {@link WriteFiles} that fuses with preceding stages and writes large input from a
* single bundle directly to temporary files.
*
* <p>Records are buffered per window, pane and destination until their encoded size reaches

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.

Maybe "Within a bundle processing, records are buffered in memory per ..."

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.

Updated.

* finalization, which may override {@link #withNumShards(int)} (the number of files per window
* can differ from the configured number of shards).
*
* <p>Direct writes are only used for unbounded inputs with non-merging windows and discarding

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.

any reason it has to be just unbounded inputs? seems like you could imagine batch/bounded cases where it might also preferrable that going through shuffle to write files.

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.

You're right it doesn't have to just be unbounded inputs. For bounded inputs with a fixed shard count, it is preferable to go through a shuffle, so I enabled direct write for that case too.

Without a fixed shard count, bounded inputs already write each bundle directly with WriteUnshardedBundlesToTempFiles.

Writer<DestinationT, OutputT> writer = writeOperation.createWriter();
writer.setDestination(key.destination);
writer.open(uuid);
writers.put(key, writer);

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.

checkState(writers.put(key, writer));

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.

Done. checkState takes a boolean expression so I changed to checkState(writers.put(key, writer) == null, "A writer is already open for %s", key);

PCollectionTuple routed =
lifted
.get(largeBundlesTag)
.setCoder(input.getCoder())

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.

seems like BundleLifter should take care of the coder here and for processing smallBundlesTag

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.

Done. BundleLifter now sets both outputs to the input coder.

.apply("FlattenSmallBundles", Flatten.pCollections())
.setCoder(input.getCoder());
PCollection<FileResult<DestinationT>> groupedFiles;
if (getComputeNumShards() != null || getNumShardsProvider() != null) {

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 wonder if there is a way to structure so that we can share this "small bundle" path with WriteFiles.expand

At a high level can we just add in the pre-processing which possibly removes some of the input via direct writes and then continues with normal path with the rest of the input?

I think it could be something like:

pcollection input = ...;
pcollectionlist tempfiles; // build up from stages and flatten
if (directwrite threshold) {
if (valid windowing etc) {
lift and processing direct largebundles, add to tempfiles
shuffleInput = smallBundles;
}
log error
shuffleInput = input;
} else {
shuffleInput = input;
}
shared processing of shuffleInput add to tempfiles
flatten+group tempfiles
finalize files

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.

Done. Direct write is now a pre-step in expand: it writes the large keys directly, and the rest goes through the existing sharded or autosharded write. Temp files from both are then flattened, grouped and finalized together. WriteShardedBundlesWithDirectWrite is removed, and pipelines without direct write are unchanged.

One difference from your sketch is the grouped path keeps write + group in one step as is, and the direct write case has its own branch that writes, flattens in the direct files, then groups. I left the grouped step alone to avoid changing step names.

public Integer apply(T element) {
try {
long bytes;
if (coder.isRegisterByteSizeObserverCheap(element)) {

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.

if we always want the size I think you should just use registerByteSizeObserver regardless of if it's cheap or not. If it's not cheap it seems that it also encodes but doesn't actually make an array which seems like less memory pressure for large elements.

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.

Done.

…rect write now runs as a pre-step in expand and falls back when a fixed shard count is set. BundleLifter caps lifted keys, sets its output coders, and sizes elements with SizeObserver. The direct path reuses WriteUnshardedTempFilesFn instead of a separate DoFn with spill logic.
…ing. Run direct write as a pre-step in expand and enable it for bounded inputs with fixed sharding, cap lifted keys in BundleLifter, reuse WriteUnshardedTempFilesFn, set BundleLifter output coders, and size elements with SizeObserver.
…de so all options are kept instead of copying a few.

// Keep every option of the original transform and only set the shard count.
WriteFiles<UserT, DestinationT, OutputT> original = transform.getTransform();
if (original.getWithAutoSharding()) {

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.

Can we modify the matcher for the override so that it doesn't trigger if autosharding is enabled?

Alternatively do we need to avoid setting the number of shards? It seems like autosharding can just ignore it if desired.

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.

Sure.

Done in #41469. updated the matcher (writeWithRunnerDeterminedSharding()) to skip autosharded writes so withNumShards isn't called on them. We need to avoid setting it because WriteFiles currently checks fixed sharding before autosharding, so setting numShards would override autosharding.

import org.apache.beam.sdk.coders.Coder.NonDeterministicException;
import org.apache.beam.sdk.coders.KvCoder;
import org.apache.beam.sdk.coders.VoidCoder;
import org.apache.beam.sdk.extensions.gcp.options.GcpOptions;

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.

can this change be in a separate PR since it affects a lot of WriteFiles options and would be nice to be documented in isolation

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.

Done. Reverted DataflowRunner from this PR and split it out into #41469 with a CHANGES.md entry.

// Stamp every file with this firing's pane so files from different firings of the
// same window get distinct final names.
result.add(
new FileResult<>(

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.

maybe we should add a withPane factory similar to withShard and then just do
result.add(e.withPane(c.pane()).withShard(UNKNOWN_SHARDNUM))

this will ensure that if more fields are added that they are propagated correctly

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.

Done.

package org.apache.beam.sdk.util;

import static org.apache.beam.sdk.util.Preconditions.checkArgumentNotNull;
import static org.apache.beam.sdk.util.Preconditions.checkStateNotNull;

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.

this has gotten big, can we separate it to it's own PR?

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.

Split BundleLifter out into #41468. Leaving the same BundleLifter changes here temporarily so this PR still compiles until #41468 is merged, then I'll merge master in so they drop from this diff.

long maxBufferedBytes,
int maxLiftedKeys,
SerializableFunction<T, Integer> elementSizer,
@Nullable SerializableFunction<T, ? extends @Nullable Object> keyFn) {

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.

can we just have this constructor? The BundleLifter can always pass all the params and tests can have internal helper methods if they want.

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.

Done in #41468. Removed the extra constructors on BundleLiftDoFn and moved them to private doFn(...) helpers in BundleLifterTest.

buffer.sizeBytes,
smallBatchTag.getId());
for (BufferedElement<T> e : buffer.elements) {
context.output(smallBatchTag, e.value, e.timestamp, e.window);

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.

why is this different than emit? we don't seem to output the pane 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.

FinishBundleContext.output has no pane parameter, and saving OutputReceiver from processElement to call emit here throws a NullPointerException on Runner v2. Moved to #41468.

smallBatchTag.getId());
for (BufferedElement<T> e : buffer.elements) {
context.output(smallBatchTag, e.value, e.timestamp, e.window);
}

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.

clear each buffer as you go to free up memory

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.

Done in #41468 (and synced here). finishBundle now iterates with an Iterator, calling it.remove() and buffer.elements.clear() as each key is emitted.

if (getBatchMaxBufferingDuration() != null) {
write = write.withBatchMaxBufferingDuration(getBatchMaxBufferingDuration());
}
if (getDirectWriteByteThreshold() != null) {

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 a reason not to have a reasonable default, instead of defaulting to off?

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.

I think if we had it default on, pipelines with withNumShards(N) would have their shard counts changed without opting in.

And also, turning it on by default changes the WriteFiles step graph, breaking --update for existing streaming jobs.

if (directWriteThreshold != null) {
List<String> disabledReasons = new ArrayList<>();
// Without a fixed shard count, bounded inputs already write each bundle directly.
if (input.isBounded() == IsBounded.BOUNDED && !fixedSharding) {

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.

batch pipelines might rely on fixed sharding of N generating exactly N files, which I think will break here. Maybe we should always disable if in batch?

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.

Updated to disable direct writes for all bounded inputs for now.

Since withDirectWriteByteThreshold is opt-in, we could revisit enabling it for batch/bounded writes without fixed sharding in a follow-up if useful to keep direct-write performance while coalescing small bundles to avoid creating too many small files.

if (input.isBounded() == IsBounded.BOUNDED && !fixedSharding) {
disabledReasons.add("the input is bounded without a fixed number of shards");
}
if (!getSideInputs().isEmpty()) {

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.

explain why side inputs cause us to disable this?

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.

BundleLifter keys records via a SerializableFunction, which doesn't have a ProcessContext to populate DynamicDestinations' side-input accessor before calling getDestination.

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.

See comments on BundleLifter PR. If we add a GroupedBundleLifter that takes KV it seems that we could perform the key assignment as part of writefiles to create KV and support this.

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.

Yup. Updated WriteFiles to key records into KV<DestinationT, UserT> in KeyByDestination before BundleLifter (withKeyFn(KV::getKey)), so side inputs are now supported and the disable check has been removed.

}
// Merging windows are only final after the GroupByKey, so direct writes would use
// unmerged windows.
if (input.getWindowingStrategy().needsMerge()) {

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.

do we even support merging windows in WriteFiles?

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.

Yes, WriteFiles supports merging windows when a fixed shard count is set, since GroupIntoShards uses a GroupByKey that merges them.

Because direct writes also apply when withNumShards is set, this check prevents writing files with unmerged windows before GroupByKey.

…DoFn, and move DataflowRunner override fix to separate PR.
// writers default to 64mb buffers. This comes into play when writing per-window
// or dynamic
// destination files. The first 20 files from a single WriteFiles transform will
// write 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.

can all the comment wrapping changes be reverted?

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.

Done.

* <td>None (no shuffle stage for unwritten records)</td>
* <td>Fewer, larger files (1 file per destination per bundle)</td>
* </tr>
* <tr>

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.

also revert

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.

Done

Long directWriteThreshold = getDirectWriteByteThreshold();
if (directWriteThreshold != null) {
List<String> disabledReasons = new ArrayList<>();
// Direct writes are only supported for unbounded inputs as of now.

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.

rm comment

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.

Done

lifted
.get(smallBundlesTag)
.apply("DropDestinationKey", Values.create())
.setCoder(input.getCoder());

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.

don't think this setcoder is needed, seems like it would just propagate from values

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.

Removed. It does just propagate from Values.create()

TupleTag<KV<DestinationT, UserT>> largeBundlesTag = new TupleTag<>("largeBundles");
TupleTag<FileResult<DestinationT>> directFilesTag = new TupleTag<>("directFiles");

PCollectionTuple keyed =

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.

Maybe it would look better in the UI if this was grouped under a transform that is "WriteFilesDirectly"? then that could be expanded to see the keybydest, lift, directwritelargebundles, dropkey but otherwise appears cleaner.

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.

Done. I grouped KeyByDestination, LiftLargeBundles, DirectWriteLargeBundles, and DropDestinationKey under a WriteFilesDirectly PTransform


@Test
@Category(NeedsRunner.class)
public void testDirectWriteDisabledForBoundedWithFixedSharding() throws IOException {

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 a way to verify this without actually running the pipeline? just by examining what the pipeline expands to?

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.

Done. Converted all four disabled tests to inspect the expanded pipeline graph via pipeline.traverseTopologically without p.run(), and added testDirectWriteEnabledExpansion as a positive check.


@Test
@Category(NeedsRunner.class)
public void testDirectWriteDisabledForBoundedWithoutFixedSharding() throws IOException {

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.

ditto

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.

Done.


@Test
@Category({NeedsRunner.class, UsesUnboundedPCollections.class, UsesTestStream.class})
public void testDirectWriteDisabledWithAccumulatingPanes() throws IOException {

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.

ditto see if we can verify without actually executing

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.

Done.

@Test
@Category({NeedsRunner.class, UsesUnboundedPCollections.class, UsesTestStream.class})
public void testDirectWriteDisabledWithMergingWindows() throws IOException {
List<String> elements = Lists.newArrayList();

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.

ditto

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.

Done.

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.

[Feature Request]: Optimized GCS Direct Write for Dense Keys

7 participants