Skip to content

[SpannerIO] Add write results and write options to the Spanner write SchemaTransform - #41769

Open
jonathansudhakar1 wants to merge 2 commits into
apache:masterfrom
jonathansudhakar1:spanner-write-results-22480
Open

jonathansudhakar1 wants to merge 2 commits into
apache:masterfrom
jonathansudhakar1:spanner-write-results-22480

Conversation

@jonathansudhakar1

@jonathansudhakar1 jonathansudhakar1 commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Addresses #22480.

This follows the plan @stankiewicz laid out on the issue: expose SpannerIO.Write#withWriteResults() and the missing write options on the Spanner write SchemaTransform (spanner_write:v1, YAML WriteToSpanner), since Abacn noted it's the recommended Spanner write path for Python. The legacy SpannerTransformRegistrar transforms in apache_beam.io.gcp.spanner don't change.

Changes

SpannerWriteSchemaTransformProvider:

  • emit_write_results (optional, default false) adds a write_results output with one row per batch committed to Spanner:

    • mutation_count (INT64)
    • commit_timestamp and snapshot_timestamp (nullable MicrosInstant)

    post-write and the error_handling output don't change. With the flag off, the transform expands the same way as before.

  • Works together with error_handling ([Bug]: SpannerIO.Write#withWriteResults() silently drops failed mutations when FailureMode.REPORT_FAILURES is set #41764). The provider turns on commit stats on SpannerIO.Write itself (it's in the same package) instead of going through withWriteResults(), which returns only the WriteResults. So the same SpannerWriteResult still has the failed mutations, and Reject REPORT_FAILURES with SpannerIO withWriteResults #41765's new check, which only guards WriteWithResults/WriteGroupedWithResults, doesn't apply.

  • New optional options: priority (LOW/MEDIUM/HIGH, any case; the default stays MEDIUM), max_commit_delay_millis, transaction_tag and exclude_txn_from_change_streams. Each maps to the matching SpannerIO.Write/SpannerConfig setting and is left alone when unset.

  • Validation at construction: the transform now calls configuration.validate() when it's built, as SpannerReadSchemaTransformProvider already does. validate() also rejects an unknown priority and a negative max_commit_delay_millis.

  • Docs: the field descriptions and description() explain the new output, and outputCollectionNames() lists write_results.

Also:

  • standard_io.yaml maps the five new fields for YAML WriteToSpanner.
  • CHANGES.md has a bullet under I/Os.

Testing

All with JDK 21. Checker Framework was on, as in CI.

  • ./gradlew :sdks:java:io:google-cloud-platform:spotlessCheck :sdks:java:io:google-cloud-platform:compileJava :sdks:java:io:google-cloud-platform:compileTestJava :sdks:java:io:google-cloud-platform:checkstyleMain :sdks:java:io:google-cloud-platform:checkstyleTest :sdks:java:io:google-cloud-platform:javadoc: passed.
  • ./gradlew :sdks:java:io:google-cloud-platform:test --tests '…SpannerSchemaTransformProviderTest' --tests '…SpannerIOWriteTest' --tests '…SpannerTransformRegistrarTest': 13/13, 46/46 and 22/22 passed (rerun after the review fix).
    • The new provider tests use FakeServiceFactory. They cover the write-results rows (microsecond timestamps round-trip exactly; a nanosecond snapshot timestamp is truncated to microseconds and the row encodes), write results and error_handling together (one key fails, one commits), the options reaching SpannerIO.Write, the unchanged defaults (only post-write, no commit stats), and validation.
    • As a mutation check, I swapped the snapshot and commit timestamps in the row conversion and dropped the transaction tag. Three of the new tests failed, as expected.
  • YAML end to end, construction only (no Spanner connection):
    • I built :sdks:java:io:google-cloud-platform:expansion-service:shadowJar and expanded a YAML WriteToSpanner through it, with all five new fields plus error_handling.
    • The outputs were post-write, write_results and the error output, and Python sees the timestamps as Optional[Timestamp].
    • priority: urgent fails at expansion with priority must be one of LOW, MEDIUM or HIGH, but was 'urgent'.
  • pytest apache_beam/yaml/yaml_provider_unit_test.py apache_beam/yaml/yaml_io_test.py: 49 passed, 23 skipped. pre-commit on the changed files passed.
  • Not run: SpannerWriteIT and the YAML Spanner extended tests. They need GCP or the Docker emulator.

Open questions

  • Naming (resolved, kept): I used max_commit_delay_millis rather than the max_commit_delay I wrote on the issue, to match other SchemaTransform configs that put the unit in the name (poll_interval_millis, triggering_frequency_seconds).
  • Snapshot timestamp precision (resolved): Spanner documents commit timestamps as microsecond-granular, so MicrosInstant keeps commit_timestamp exactly. Snapshot timestamps can carry nanoseconds. The first version of this PR was wrong to say those would be truncated: MicrosInstant throws an AssertionError on them. Since 98152b6, both timestamps are explicitly truncated to microseconds, and that's documented and tested.
  • Possible follow-ups: the batching knobs the legacy Python wrappers expose (max_batch_size_bytes, max_number_mutations, max_number_rows, commit_deadline), and a write operation other than insert-or-update. Both would be separate PRs, if they're wanted.

@github-actions github-actions Bot 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.

📋 Review Summary

This PR cleanly adds emit_write_results and additional write configuration options (priority, max_commit_delay_millis, transaction_tag, and exclude_txn_from_change_streams) to SpannerWriteSchemaTransformProvider and exposes them in Beam YAML's WriteToSpanner transform. The implementation properly preserves compatibility with error_handling by enabling commit stats directly on SpannerIO.Write, and includes thorough unit test coverage.

🔍 General Feedback

  • Enabling commitStats on the SpannerIO.Write builder rather than calling withWriteResults() is a clean approach that allows write_results and error_handling outputs to coexist on the same SpannerWriteResult.
  • Configuration validation, schema logical types (MicrosInstant), and YAML mappings align well with existing Beam SchemaTransform conventions.

💡 Tip: Comment /gemini review on this pull request to trigger a new Gemini code review.

@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

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

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).

…SchemaTransform

The Spanner write SchemaTransform (spanner_write:v1, YAML WriteToSpanner)
is the recommended way to write to Spanner from Python and YAML, but it
can't return SpannerIO.Write#withWriteResults() commit metadata, and it
exposes none of the newer write options.

Add an opt-in emit_write_results flag. When it's set, a new write_results
output gets one row per committed batch: mutation_count (INT64) plus
commit_timestamp and snapshot_timestamp (nullable MicrosInstant; Spanner
commit timestamps have microsecond granularity). post-write and the
error_handling output don't change. The transform turns on commit stats on
SpannerIO.Write itself instead of using withWriteResults(), so the failed
mutations stay available and error_handling works together with the write
results (see apache#41764).

Also add the optional priority (LOW/MEDIUM/HIGH), max_commit_delay_millis,
transaction_tag and exclude_txn_from_change_streams options, map all new
fields in standard_io.yaml, and validate the configuration when the
transform is built, as the read SchemaTransform does.
@jonathansudhakar1
jonathansudhakar1 force-pushed the spanner-write-results-22480 branch from c10a399 to 09d3c7b Compare December 2, 2026 14:03
@stankiewicz

Copy link
Copy Markdown
Contributor

naming looks fine.
regarding snapshot precision loss - it's a bummer, but I think more important is commit timestamp here which doesn't suffer from precision loss.

private static @Nullable Instant toInstant(@Nullable Timestamp timestamp) {
return timestamp == null
? null
: Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos());

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.

Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos())
.truncatedTo(ChronoUnit.MICROS);

otherwise MicrosInstant will throw AssertionError

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, good catch. I was wrong in the description: a nanosecond snapshot timestamp would have hit that AssertionError instead of being truncated. Fixed in 98152b6: toInstant now truncates to ChronoUnit.MICROS, the schema Javadoc and the emit_write_results description say so, and there are two new tests. testWriteResultsRowTruncatesTimestampsToMicros encodes the row with RowCoder, and testWriteEmitsWriteResults now uses a nanosecond snapshot timestamp end to end. Both failed with that AssertionError before the fix.

…onds

Spanner snapshot timestamps can carry nanoseconds, and MicrosInstant
rejects sub-microsecond values with an AssertionError when the row is
encoded. Truncate both timestamps to microseconds before building the
write_results row, document it, and test it with a nanosecond snapshot
timestamp (directly and through a pipeline).
@jonathansudhakar1

Copy link
Copy Markdown
Contributor Author

Thanks for the review! I kept max_commit_delay_millis. Agreed on precision: commit timestamps are exact, and snapshot timestamps are now explicitly truncated to microseconds (98152b6, details in the inline thread). That also fixes the AssertionError you spotted. I updated the open questions in the description to match.

After the change I reran spotlessCheck, compile (Checker on), checkstyle and javadoc, plus SpannerSchemaTransformProviderTest 13/13, SpannerIOWriteTest 46/46 and SpannerTransformRegistrarTest 22/22. The branch still merges cleanly with master after #41881.

@stankiewicz

Copy link
Copy Markdown
Contributor

thanks for working on this. Feel free to work on follow-ups, I think it makes sense to expose similar knobs as legacy wrappers, to give possibility in the future to remove them/ invoke schematransform from those methods.

@codecov

codecov Bot commented Dec 3, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 58.95%. Comparing base (3b166fb) to head (98152b6).
⚠️ Report is 29 commits behind head on master.

Additional details and impacted files
@@              Coverage Diff              @@
##             master   #41769       +/-   ##
=============================================
+ Coverage     37.41%   58.95%   +21.53%     
  Complexity     2336     2336               
=============================================
  Files           646     1136      +490     
  Lines         86550   171277    +84727     
  Branches       1552     1552               
=============================================
+ Hits          32386   100975    +68589     
- Misses        51608    67746    +16138     
  Partials       2556     2556               
Flag Coverage Δ
python 80.83% <ø> (+27.29%) ⬆️

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.

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.

2 participants