From fbf8d02c5058a10ca827931a70ee65cb5e234b3c Mon Sep 17 00:00:00 2001 From: Jonathan Sudhakar <1854861+jonathansudhakar1@users.noreply.github.com> Date: Sat, 5 Dec 2026 09:16:27 -0500 Subject: [PATCH] [SpannerIO] Add batching, retry and host options to the Spanner write SchemaTransform The legacy Python Spanner write transforms (SpannerTransformRegistrar's WriteBuilder) let users tune batching, commit retries and the Spanner host, but the spanner_write:v1 SchemaTransform (YAML WriteToSpanner) exposes none of them. Users moving to the SchemaTransform can't, for example, turn off batching for low-latency streaming writes or write to the Spanner emulator. Add optional max_batch_size_bytes, max_number_mutations, max_number_rows, grouping_factor, commit_deadline_seconds, max_cumulative_backoff_seconds, host and emulator_host fields, passed to the matching SpannerIO.Write methods, and validate them when the transform is built. Map them in standard_io.yaml for YAML WriteToSpanner. Also fix SpannerIO.Write#withMaxNumRows's Javadoc, which gave the default as 1000 instead of 500. --- CHANGES.md | 1 + .../beam/sdk/io/gcp/spanner/SpannerIO.java | 2 +- .../SpannerWriteSchemaTransformProvider.java | 138 ++++++++++++++++ .../SpannerSchemaTransformProviderTest.java | 155 +++++++++++++++++- sdks/python/apache_beam/yaml/standard_io.yaml | 8 + 5 files changed, 302 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index a3adbb3d7af9..85cb2a5789b6 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -101,6 +101,7 @@ * (Python) Made `beam.managed.ICEBERG_CDC` public, for reading an Iceberg table's inserts, updates and deletes with `beam.managed.Read` ([#41654](https://github.com/apache/beam/pull/41654)). * (Java) `HL7v2Message` now exposes the parsed content of an HL7v2 message through `getParsedData()`, so HL7v2IO users who do not use schematized parsing can read it ([#20452](https://github.com/apache/beam/issues/20452)). * (Java/YAML) The Spanner write SchemaTransform (`spanner_write:v1`, YAML `WriteToSpanner`) can emit each committed batch's mutation count and commit timestamp on a `write_results` output (`emit_write_results`), and now accepts `priority`, `max_commit_delay_millis`, `transaction_tag` and `exclude_txn_from_change_streams` ([#22480](https://github.com/apache/beam/issues/22480)). +* (Java/YAML) The Spanner write SchemaTransform (`spanner_write:v1`, YAML `WriteToSpanner`) now accepts the batching, retry and host options of the legacy Python Spanner write transforms: `max_batch_size_bytes`, `max_number_mutations`, `max_number_rows`, `grouping_factor`, `commit_deadline_seconds`, `max_cumulative_backoff_seconds`, `host` and `emulator_host` ([#22480](https://github.com/apache/beam/issues/22480)). ## Improvements diff --git a/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/spanner/SpannerIO.java b/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/spanner/SpannerIO.java index fdc4456fbf8b..0d967523c906 100644 --- a/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/spanner/SpannerIO.java +++ b/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/spanner/SpannerIO.java @@ -1700,7 +1700,7 @@ public Write withMaxNumMutations(long maxNumMutations) { /** * Specifies the row mutation limit (maximum number of mutated rows per batch). Default value is - * 1000 + * 500 */ public Write withMaxNumRows(long maxNumRows) { return toBuilder().setMaxNumRows(maxNumRows).build(); diff --git a/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/spanner/SpannerWriteSchemaTransformProvider.java b/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/spanner/SpannerWriteSchemaTransformProvider.java index 5e1c24728f73..4afd9378837b 100644 --- a/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/spanner/SpannerWriteSchemaTransformProvider.java +++ b/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/spanner/SpannerWriteSchemaTransformProvider.java @@ -63,6 +63,7 @@ import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Strings; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet; import org.checkerframework.checker.nullness.qual.NonNull; +import org.joda.time.Duration; @SuppressWarnings({ "nullness" // TODO(https://github.com/apache/beam/issues/20497) @@ -221,6 +222,39 @@ SpannerIO.Write buildWrite() { if (excludeTxnFromChangeStreams != null) { write = write.withExcludeTxnFromChangeStreams(excludeTxnFromChangeStreams); } + Long maxBatchSizeBytes = configuration.getMaxBatchSizeBytes(); + if (maxBatchSizeBytes != null) { + write = write.withBatchSizeBytes(maxBatchSizeBytes); + } + Long maxNumberMutations = configuration.getMaxNumberMutations(); + if (maxNumberMutations != null) { + write = write.withMaxNumMutations(maxNumberMutations); + } + Long maxNumberRows = configuration.getMaxNumberRows(); + if (maxNumberRows != null) { + write = write.withMaxNumRows(maxNumberRows); + } + Long groupingFactor = configuration.getGroupingFactor(); + if (groupingFactor != null) { + write = write.withGroupingFactor(Math.toIntExact(groupingFactor)); + } + Long commitDeadlineSeconds = configuration.getCommitDeadlineSeconds(); + if (commitDeadlineSeconds != null) { + write = write.withCommitDeadline(Duration.standardSeconds(commitDeadlineSeconds)); + } + Long maxCumulativeBackoffSeconds = configuration.getMaxCumulativeBackoffSeconds(); + if (maxCumulativeBackoffSeconds != null) { + write = + write.withMaxCumulativeBackoff(Duration.standardSeconds(maxCumulativeBackoffSeconds)); + } + String host = configuration.getHost(); + if (!Strings.isNullOrEmpty(host)) { + write = write.withHost(host); + } + String emulatorHost = configuration.getEmulatorHost(); + if (!Strings.isNullOrEmpty(emulatorHost)) { + write = write.withEmulatorHost(emulatorHost); + } if (serviceFactory != null) { write = write.withServiceFactory(serviceFactory); } @@ -394,6 +428,58 @@ public abstract static class SpannerWriteSchemaTransformConfiguration implements @Nullable public abstract Boolean getExcludeTxnFromChangeStreams(); + @SchemaFieldDescription( + "The maximum size, in bytes, of the mutations in one batch committed to Cloud Spanner. " + + "Defaults to 1048576 (1 MiB). A value of 0 or 1 disables batching, so each row is " + + "written in its own transaction.") + @Nullable + public abstract Long getMaxBatchSizeBytes(); + + @SchemaFieldDescription( + "The maximum number of mutated cells in one batch committed to Cloud Spanner. Defaults " + + "to 5000. A value of 0 or 1 disables batching.") + @Nullable + public abstract Long getMaxNumberMutations(); + + @SchemaFieldDescription( + "The maximum number of mutated rows in one batch committed to Cloud Spanner. Defaults to " + + "500. A value of 0 or 1 disables batching.") + @Nullable + public abstract Long getMaxNumberRows(); + + @SchemaFieldDescription( + "How many batches' worth of mutations are gathered and sorted by key before they are " + + "split into batches, so that each batch touches few splits. The gathered mutations " + + "are held in worker memory. 1 turns off the sorting. Defaults to 1000 for bounded " + + "input and 1 for unbounded input.") + @Nullable + public abstract Long getGroupingFactor(); + + @SchemaFieldDescription( + "The deadline, in seconds, for each commit call to Cloud Spanner. Commits that fail with " + + "DEADLINE_EXCEEDED are retried with backoff, up to max_cumulative_backoff_seconds. " + + "Defaults to 15.") + @Nullable + public abstract Long getCommitDeadlineSeconds(); + + @SchemaFieldDescription( + "The maximum total time, in seconds, spent backing off and retrying a batch after " + + "DEADLINE_EXCEEDED errors. After that, the batch fails and is handled according to " + + "error_handling. Defaults to 900 (15 minutes).") + @Nullable + public abstract Long getMaxCumulativeBackoffSeconds(); + + @SchemaFieldDescription( + "The Cloud Spanner host to connect to. Defaults to https://batch-spanner.googleapis.com/.") + @Nullable + public abstract String getHost(); + + @SchemaFieldDescription( + "The host and port of a Cloud Spanner emulator to write to instead of Cloud Spanner, for " + + "example localhost:9010.") + @Nullable + public abstract String getEmulatorHost(); + public static Builder builder() { return new AutoValue_SpannerWriteSchemaTransformProvider_SpannerWriteSchemaTransformConfiguration .Builder(); @@ -421,6 +507,22 @@ public abstract static class Builder { public abstract Builder setExcludeTxnFromChangeStreams(Boolean excludeTxnFromChangeStreams); + public abstract Builder setMaxBatchSizeBytes(Long maxBatchSizeBytes); + + public abstract Builder setMaxNumberMutations(Long maxNumberMutations); + + public abstract Builder setMaxNumberRows(Long maxNumberRows); + + public abstract Builder setGroupingFactor(Long groupingFactor); + + public abstract Builder setCommitDeadlineSeconds(Long commitDeadlineSeconds); + + public abstract Builder setMaxCumulativeBackoffSeconds(Long maxCumulativeBackoffSeconds); + + public abstract Builder setHost(String host); + + public abstract Builder setEmulatorHost(String emulatorHost); + public abstract SpannerWriteSchemaTransformConfiguration build(); } @@ -450,6 +552,42 @@ public void validate() { maxCommitDelayMillis == null || maxCommitDelayMillis >= 0, invalidConfigMessage + "max_commit_delay_millis must not be negative, but was %s.", maxCommitDelayMillis); + + checkNotNegative(invalidConfigMessage, "max_batch_size_bytes", this.getMaxBatchSizeBytes()); + checkNotNegative(invalidConfigMessage, "max_number_mutations", this.getMaxNumberMutations()); + checkNotNegative(invalidConfigMessage, "max_number_rows", this.getMaxNumberRows()); + + Long groupingFactor = this.getGroupingFactor(); + checkArgument( + groupingFactor == null || (groupingFactor >= 1 && groupingFactor <= Integer.MAX_VALUE), + invalidConfigMessage + "grouping_factor must be between 1 and %s, but was %s.", + Integer.MAX_VALUE, + groupingFactor); + + checkPositive( + invalidConfigMessage, "commit_deadline_seconds", this.getCommitDeadlineSeconds()); + checkPositive( + invalidConfigMessage, + "max_cumulative_backoff_seconds", + this.getMaxCumulativeBackoffSeconds()); + } + + private static void checkNotNegative( + String invalidConfigMessage, String field, @Nullable Long value) { + checkArgument( + value == null || value >= 0, + invalidConfigMessage + "%s must not be negative, but was %s.", + field, + value); + } + + private static void checkPositive( + String invalidConfigMessage, String field, @Nullable Long value) { + checkArgument( + value == null || value > 0, + invalidConfigMessage + "%s must be positive, but was %s.", + field, + value); } } } diff --git a/sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/spanner/SpannerSchemaTransformProviderTest.java b/sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/spanner/SpannerSchemaTransformProviderTest.java index bf2f1c150af1..5cd397e72ea9 100644 --- a/sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/spanner/SpannerSchemaTransformProviderTest.java +++ b/sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/spanner/SpannerSchemaTransformProviderTest.java @@ -49,6 +49,7 @@ import java.util.List; import java.util.ServiceLoader; import java.util.stream.Collectors; +import java.util.stream.LongStream; import java.util.stream.StreamSupport; import org.apache.beam.sdk.coders.RowCoder; import org.apache.beam.sdk.io.gcp.spanner.SpannerIO.FailureMode; @@ -59,6 +60,7 @@ import org.apache.beam.sdk.testing.PAssert; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.Create; +import org.apache.beam.sdk.transforms.FlatMapElements; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.util.CoderUtils; import org.apache.beam.sdk.values.PCollection; @@ -67,6 +69,7 @@ import org.apache.beam.sdk.values.Row; import org.apache.beam.sdk.values.TupleTag; import org.apache.beam.sdk.values.TupleTagList; +import org.apache.beam.sdk.values.TypeDescriptors; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Lists; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Sets; @@ -75,6 +78,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import org.mockito.ArgumentCaptor; /** * Tests for {@link org.apache.beam.sdk.io.gcp.spanner.SpannerReadSchemaTransformProvider} and @@ -326,7 +330,15 @@ public void testWriteFindTransformAndMakeItWork() { "priority", "max_commit_delay_millis", "transaction_tag", - "exclude_txn_from_change_streams"), + "exclude_txn_from_change_streams", + "max_batch_size_bytes", + "max_number_mutations", + "max_number_rows", + "grouping_factor", + "commit_deadline_seconds", + "max_cumulative_backoff_seconds", + "host", + "emulator_host"), spannerWriteProvider.configurationSchema().getFields().stream() .map(field -> field.getName()) .collect(Collectors.toSet())); @@ -443,6 +455,20 @@ public void testWriteDefaultsLeaveSpannerIOWriteUnchanged() { assertNull(spannerConfig.getTransactionTag()); assertNull(spannerConfig.getExcludeTxnFromChangeStreams()); + // Batching, retries and the host keep SpannerIO's defaults. + SpannerIO.Write defaults = SpannerIO.write(); + assertEquals(defaults.getBatchSizeBytes(), write.getBatchSizeBytes()); + assertEquals(defaults.getMaxNumMutations(), write.getMaxNumMutations()); + assertEquals(defaults.getMaxNumRows(), write.getMaxNumRows()); + assertFalse(write.getGroupingFactor().isPresent()); + SpannerConfig defaultConfig = defaults.getSpannerConfig(); + assertEquals(defaultConfig.getCommitDeadline().get(), spannerConfig.getCommitDeadline().get()); + assertEquals( + defaultConfig.getMaxCumulativeBackoff().get(), + spannerConfig.getMaxCumulativeBackoff().get()); + assertEquals(defaultConfig.getHost().get(), spannerConfig.getHost().get()); + assertNull(spannerConfig.getEmulatorHost()); + PCollectionRowTuple output = PCollectionRowTuple.of( "input", pipeline.apply(Create.of(keyRow(1L)).withRowSchema(KEY_SCHEMA))) @@ -478,6 +504,133 @@ public void testWriteOptionsAreAppliedToSpannerIOWrite() { .get()); } + @Test + public void testWriteBatchingRetryAndHostOptionsAreAppliedToSpannerIOWrite() { + SpannerIO.Write write = + new SpannerSchemaTransformWrite( + writeConfig() + .setMaxBatchSizeBytes(2048L) + .setMaxNumberMutations(300L) + .setMaxNumberRows(20L) + .setGroupingFactor(5L) + .setCommitDeadlineSeconds(30L) + .setMaxCumulativeBackoffSeconds(120L) + .setHost("https://spanner.example.com") + .setEmulatorHost("localhost:9010") + .build()) + .buildWrite(); + + assertEquals(2048L, write.getBatchSizeBytes()); + assertEquals(300L, write.getMaxNumMutations()); + assertEquals(20L, write.getMaxNumRows()); + assertEquals(5, write.getGroupingFactor().getAsInt()); + SpannerConfig spannerConfig = write.getSpannerConfig(); + assertEquals(Duration.standardSeconds(30), spannerConfig.getCommitDeadline().get()); + assertEquals(Duration.standardMinutes(2), spannerConfig.getMaxCumulativeBackoff().get()); + assertEquals("https://spanner.example.com", spannerConfig.getHost().get()); + assertEquals("localhost:9010", spannerConfig.getEmulatorHost().get()); + } + + @Test + public void testWriteBatchingRetryAndHostOptionValidation() { + // Limits of 0 are allowed: they turn off batching. + writeConfig() + .setMaxBatchSizeBytes(0L) + .setMaxNumberMutations(0L) + .setMaxNumberRows(0L) + .setGroupingFactor(1L) + .setCommitDeadlineSeconds(1L) + .setMaxCumulativeBackoffSeconds(1L) + .setHost("") + .setEmulatorHost("") + .build() + .validate(); + + assertInvalidWriteConfig( + writeConfig().setMaxBatchSizeBytes(-1L), "max_batch_size_bytes must not be negative"); + assertInvalidWriteConfig( + writeConfig().setMaxNumberMutations(-1L), "max_number_mutations must not be negative"); + assertInvalidWriteConfig( + writeConfig().setMaxNumberRows(-1L), "max_number_rows must not be negative"); + assertInvalidWriteConfig( + writeConfig().setGroupingFactor(0L), "grouping_factor must be between 1 and"); + assertInvalidWriteConfig( + writeConfig().setGroupingFactor(Integer.MAX_VALUE + 1L), + "grouping_factor must be between 1 and"); + assertInvalidWriteConfig( + writeConfig().setCommitDeadlineSeconds(0L), "commit_deadline_seconds must be positive"); + assertInvalidWriteConfig( + writeConfig().setMaxCumulativeBackoffSeconds(0L), + "max_cumulative_backoff_seconds must be positive"); + + // The transform validates its configuration when it's built. + assertThrows( + IllegalArgumentException.class, + () -> + new SpannerWriteSchemaTransformProvider() + .from(writeConfig().setMaxNumberRows(-5L).build())); + } + + private static void assertInvalidWriteConfig( + SpannerWriteSchemaTransformConfiguration.Builder config, String expectedMessage) { + IllegalArgumentException e = + assertThrows(IllegalArgumentException.class, () -> config.build().validate()); + assertTrue(e.getMessage(), e.getMessage().contains(expectedMessage)); + } + + @Test + public void testWriteWithBatchingTurnedOffCommitsEachRowSeparately() { + FakeServiceFactory serviceFactory = fakeSpannerWithKeyTable(); + Timestamp commitTimestamp = Timestamp.ofTimeSecondsAndNanos(1700000000L, 0); + when(serviceFactory + .mockDatabaseClient() + .writeAtLeastOnceWithOptions( + any(), any(ReadQueryUpdateTransactionOption.class), eq(Options.commitStats()))) + .thenReturn(commitResponse(1L, commitTimestamp, commitTimestamp)); + + SpannerSchemaTransformWrite transform = + new SpannerSchemaTransformWrite( + writeConfig().setEmitWriteResults(true).setMaxNumberRows(1L).build()); + transform.setServiceFactory(serviceFactory); + + // One input element expands to three rows, so they reach the write in the same bundle, where + // SpannerIO would batch them together if batching were on. + PCollection rows = + pipeline + .apply(Create.of(3L)) + .apply( + FlatMapElements.into(TypeDescriptors.rows()) + .via( + (Long n) -> + LongStream.rangeClosed(1, n) + .mapToObj(SpannerSchemaTransformProviderTest::keyRow) + .collect(Collectors.toList()))) + .setRowSchema(KEY_SCHEMA); + PCollectionRowTuple output = PCollectionRowTuple.of("input", rows).apply(transform); + + Row writeResult = + writeResultsRow(1L, Instant.ofEpochSecond(1700000000L), Instant.ofEpochSecond(1700000000L)); + PAssert.that(output.get("write_results")) + .containsInAnyOrder(writeResult, writeResult, writeResult); + pipeline.run().waitUntilFinish(); + + // Each row was committed on its own. + @SuppressWarnings("unchecked") + ArgumentCaptor> batches = ArgumentCaptor.forClass(Iterable.class); + verify(serviceFactory.mockDatabaseClient(), times(3)) + .writeAtLeastOnceWithOptions( + batches.capture(), + any(ReadQueryUpdateTransactionOption.class), + eq(Options.commitStats())); + List committedKeys = Lists.newArrayList(); + for (Iterable batch : batches.getAllValues()) { + List mutations = Lists.newArrayList(batch); + assertEquals(1, mutations.size()); + committedKeys.add(mutations.get(0).asMap().get("key").getInt64()); + } + assertEquals(ImmutableSet.of(1L, 2L, 3L), ImmutableSet.copyOf(committedKeys)); + } + @Test public void testWriteEmitsWriteResults() { FakeServiceFactory serviceFactory = fakeSpannerWithKeyTable(); diff --git a/sdks/python/apache_beam/yaml/standard_io.yaml b/sdks/python/apache_beam/yaml/standard_io.yaml index c95e32e8a759..f483ade02217 100644 --- a/sdks/python/apache_beam/yaml/standard_io.yaml +++ b/sdks/python/apache_beam/yaml/standard_io.yaml @@ -555,6 +555,14 @@ max_commit_delay_millis: 'max_commit_delay_millis' transaction_tag: 'transaction_tag' exclude_txn_from_change_streams: 'exclude_txn_from_change_streams' + max_batch_size_bytes: 'max_batch_size_bytes' + max_number_mutations: 'max_number_mutations' + max_number_rows: 'max_number_rows' + grouping_factor: 'grouping_factor' + commit_deadline_seconds: 'commit_deadline_seconds' + max_cumulative_backoff_seconds: 'max_cumulative_backoff_seconds' + host: 'host' + emulator_host: 'emulator_host' underlying_provider: type: beamJar transforms: