From c541f2abd1dfa2a2e07c1e23383f2b4ecbc984dd Mon Sep 17 00:00:00 2001 From: Maksym Tymoshyk Date: Thu, 12 Nov 2026 00:03:03 +0200 Subject: [PATCH] Allow disk use in MongoDbIO aggregations to avoid sort memory limit MongoDbIO now sets allowDiskUse(true) on the $bucketAuto query that computes splits and on AggregationQuery reads. Without it, servers older than 6.0 fail on any collection whose sort needs more than 100 MB, with "Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting". Fixes #26495 --- CHANGES.md | 1 + .../beam/sdk/io/mongodb/AggregationQuery.java | 4 +- .../apache/beam/sdk/io/mongodb/MongoDbIO.java | 6 +- .../beam/sdk/io/mongodb/MongoDbIOTest.java | 67 +++++++++++++++++++ 4 files changed, 76 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index df28ef6a3fff..90e3022f6c7f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -135,6 +135,7 @@ ## Bugfixes +* (Java) Fixed `MongoDbIO` reads with `withBucketAuto(true)` or an `AggregationQuery` failing on large collections with `Sort exceeded memory limit of 104857600 bytes` on MongoDB servers older than 6.0. The connector now sets `allowDiskUse` on its aggregations, as the Python and Go connectors do ([#26495](https://github.com/apache/beam/issues/26495)). * (Python) Fixed cross-language `ReadFromKafka(redistribute=True)` creating one key per record when `redistribute_num_keys` is not set. It now uses the KafkaIO default of 32768 keys, as Java `withRedistribute()` does. On Flink the per-record keys left timer state that grew until the job ran out of memory ([#41103](https://github.com/apache/beam/issues/41103)). * (Python/YAML) Beam YAML `generic` filters now accept `>=`, `<=`, `==` and `!=`; previously only `<` and `>` were recognized ([#41043](https://github.com/apache/beam/issues/41043)). * (Python) Fixed batched DoFns whose input must be rebatched into a `pyarrow.Table` with more than one column, which failed with `ArrowInvalid: Column 1 ... expected length N but got length 0`. This affected, for example, Beam YAML `ReadFromCsv` or `ReadFromJson` followed directly by `WriteToParquet` ([#41042](https://github.com/apache/beam/issues/41042)). diff --git a/sdks/java/io/mongodb/src/main/java/org/apache/beam/sdk/io/mongodb/AggregationQuery.java b/sdks/java/io/mongodb/src/main/java/org/apache/beam/sdk/io/mongodb/AggregationQuery.java index a96641123ac2..3d1d3a328b4c 100644 --- a/sdks/java/io/mongodb/src/main/java/org/apache/beam/sdk/io/mongodb/AggregationQuery.java +++ b/sdks/java/io/mongodb/src/main/java/org/apache/beam/sdk/io/mongodb/AggregationQuery.java @@ -70,6 +70,8 @@ public MongoCursor apply(MongoCollection collection) { if (bucket() != null) { pipeline.add(bucket()); } - return collection.aggregate(pipeline).iterator(); + // stages such as $sort, $group and $bucketAuto are capped at 100 MB of memory. Servers older + // than 6.0 fail past that cap unless the request allows spilling to disk + return collection.aggregate(pipeline).allowDiskUse(true).iterator(); } } diff --git a/sdks/java/io/mongodb/src/main/java/org/apache/beam/sdk/io/mongodb/MongoDbIO.java b/sdks/java/io/mongodb/src/main/java/org/apache/beam/sdk/io/mongodb/MongoDbIO.java index 501eaa4867c4..91db87f73480 100644 --- a/sdks/java/io/mongodb/src/main/java/org/apache/beam/sdk/io/mongodb/MongoDbIO.java +++ b/sdks/java/io/mongodb/src/main/java/org/apache/beam/sdk/io/mongodb/MongoDbIO.java @@ -731,7 +731,11 @@ static List buildAutoBuckets(MongoDatabase mongoDatabase, Read spec) { BsonDocument bucketAuto = new BsonDocument("$bucketAuto", bucketAutoConfig); List aggregates = new ArrayList<>(); aggregates.add(bucketAuto); - AggregateIterable buckets = mongoCollection.aggregate(aggregates); + // $bucketAuto sorts every document in the collection, and MongoDB caps an in-memory sort at + // 100 MB. Servers older than 6.0 fail past that cap with "Sort exceeded memory limit" unless + // the request allows spilling the sort to disk + AggregateIterable buckets = + mongoCollection.aggregate(aggregates).allowDiskUse(true); for (Document bucket : buckets) { Document filter = new Document(); diff --git a/sdks/java/io/mongodb/src/test/java/org/apache/beam/sdk/io/mongodb/MongoDbIOTest.java b/sdks/java/io/mongodb/src/test/java/org/apache/beam/sdk/io/mongodb/MongoDbIOTest.java index e0a0eabd5be3..43dc6ac8ac9b 100644 --- a/sdks/java/io/mongodb/src/test/java/org/apache/beam/sdk/io/mongodb/MongoDbIOTest.java +++ b/sdks/java/io/mongodb/src/test/java/org/apache/beam/sdk/io/mongodb/MongoDbIOTest.java @@ -21,11 +21,15 @@ import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.assertEquals; +import com.mongodb.ConnectionString; +import com.mongodb.MongoClientSettings; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; +import com.mongodb.event.CommandListener; +import com.mongodb.event.CommandStartedEvent; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -38,6 +42,7 @@ import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterators; +import org.bson.BsonBoolean; import org.bson.BsonDocument; import org.bson.BsonInt32; import org.bson.BsonString; @@ -207,6 +212,68 @@ public void testBuildAutoBuckets() { assertEquals(10, buckets.size()); } + @Test + public void testBuildAutoBucketsAllowsDiskUse() { + List commands = new ArrayList<>(); + try (MongoClient recordingClient = createCommandRecordingClient(commands)) { + MongoDbIO.Read spec = + MongoDbIO.read() + .withUri(MONGO_CONTAINER.getReplicaSetUrl()) + .withDatabase(DATABASE_NAME) + .withCollection(COLLECTION_NAME); + + MongoDbIO.BoundedMongoDbSource.buildAutoBuckets( + recordingClient.getDatabase(DATABASE_NAME), spec); + } + + assertEquals(BsonBoolean.TRUE, findAggregateCommand(commands).get("allowDiskUse")); + } + + @Test + public void testAggregationQueryAllowsDiskUse() { + List commands = new ArrayList<>(); + try (MongoClient recordingClient = createCommandRecordingClient(commands)) { + MongoCollection collection = + recordingClient.getDatabase(DATABASE_NAME).getCollection(COLLECTION_NAME); + + AggregationQuery.create() + .withMongoDbPipeline(Collections.emptyList()) + .apply(collection) + .close(); + } + + assertEquals(BsonBoolean.TRUE, findAggregateCommand(commands).get("allowDiskUse")); + } + + /** Creates a client that adds every command it sends to the server to {@code commands}. */ + private static MongoClient createCommandRecordingClient(List commands) { + CommandListener listener = + new CommandListener() { + @Override + public void commandStarted(CommandStartedEvent event) { + // the driver frees the buffer behind getCommand() once this callback returns, so + // reading the original document later throws IndexOutOfBoundsException + synchronized (commands) { + commands.add(event.getCommand().clone()); + } + } + }; + return MongoClients.create( + MongoClientSettings.builder() + .applyConnectionString(new ConnectionString(MONGO_CONTAINER.getReplicaSetUrl())) + .addCommandListener(listener) + .build()); + } + + private static BsonDocument findAggregateCommand(List commands) { + synchronized (commands) { + return commands.stream() + .filter(command -> command.containsKey("aggregate")) + .findFirst() + .orElseThrow(() -> new AssertionError("no aggregate command was sent")); + } + } + @Test public void testFullRead() { PCollection output =