Skip to content

Create batch_process_storage.py sample - #14993

Open
cbonnie wants to merge 2 commits into
mainfrom
cbonnie-patch-1
Open

cbonnie wants to merge 2 commits into
mainfrom
cbonnie-patch-1

Conversation

@cbonnie

@cbonnie cbonnie commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Add a new code sample for a batch pipeline that reads CSV sales records from Cloud Storage with ReadFromText, totals sales per product with CombinePerKey, and writes the results back to Cloud Storage with WriteToText.

Code sample will be used here: http://cl/1013782122

Description

Addresses # http://b/589715201

Checklist

Testing

  • I have tested this change on a live environment and verified it works as intended.

Compliance & Style


Post-Approval Actions

  • Please merge this PR for me once it is approved

Add a new code sample for a batch pipeline that reads CSV sales records from Cloud Storage with ReadFromText, totals sales per product with CombinePerKey, and writes the results back to Cloud Storage with WriteToText.
@cbonnie
cbonnie requested review from a team as code owners November 23, 2026 16:31
@snippet-bot

snippet-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Here is the summary of changes.

You are about to add 1 region tag.

This comment is generated by snippet-bot.
If you find problems with this result, please file an issue at:
https://github.com/googleapis/repo-automation-bots/issues.
To update this comment, add snippet-bot:force-run label or use the checkbox below:

  • Refresh this comment

@product-auto-label product-auto-label Bot added the samples Issues that are directly related to samples. label Nov 23, 2026

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request introduces a new Apache Beam pipeline snippet in Python (batch_process_storage.py) that reads CSV data from Google Cloud Storage, aggregates sales amounts by product, and writes the results back to GCS. The review feedback highlights a potential issue where parsing CSV lines using a simple split(',') without error handling could crash the pipeline on malformed rows. To make the pipeline more resilient, the reviewer suggests refactoring parse_record to yield parsed records safely within a try-except block, importing Iterable for typing, and updating the pipeline step to use beam.FlatMap instead of beam.Map.

Comment on lines +24 to +27
def parse_record(line: str) -> Tuple[str, float]:
"""Parses a CSV line into a (product, amount) tuple."""
_, product, amount = line.split(",")
return product, float(amount)

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.

medium

Parsing CSV lines directly using split(',') without error handling can crash the entire pipeline if there are empty lines, headers, or malformed rows (e.g., raising ValueError during unpacking or float conversion).

Using a generator that yields results only on successful parsing, combined with beam.FlatMap, makes the pipeline resilient to malformed input.

Suggested change
def parse_record(line: str) -> Tuple[str, float]:
"""Parses a CSV line into a (product, amount) tuple."""
_, product, amount = line.split(",")
return product, float(amount)
def parse_record(line: str) -> Iterable[Tuple[str, float]]:
"""Parses a CSV line into a (product, amount) tuple."""
try:
parts = line.split(",")
if len(parts) >= 3:
yield parts[1], float(parts[2])
except ValueError:
pass

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, but I'm keeping parse_record as is on purpose. This is a docs snippet, so the goal is to show the core read → parse → aggregate → write pattern as clearly as possible.

  • The header row is already handled by ReadFromText(..., skip_header_lines=1), and the sample assumes well-formed input.

  • except ValueError: pass would silently drop bad rows and produce wrong totals with no signal. I'd rather not teach readers that pattern. In production you'd send bad records to a dead-letter output, which is beyond the scope of this snippet.

  • len(parts) >= 3 would also quietly accept rows with extra columns, which hides a different kind of bad data.

pipeline
| "ReadFromGCS"
>> beam.io.ReadFromText(known_args.input, skip_header_lines=1)
| "Parse" >> beam.Map(parse_record)

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.

medium

Use beam.FlatMap instead of beam.Map to support the generator-based parse_record function, which filters out malformed or empty rows gracefully.

Suggested change
| "Parse" >> beam.Map(parse_record)
| "Parse" >> beam.FlatMap(parse_record)

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.

Not adopting: FlatMap is only needed if parse_record becomes a generator, which I'm declining (see the thread on that function). Since parse_record returns exactly one (product, amount) tuple per line, beam.Map is the right transform.

@cbonnie
cbonnie requested a review from shunping December 1, 2026 13:56
@iennae

iennae commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

hey @cbonnie,

Thanks for this sample. I ran it unmodified on Dataflow (DataflowRunner, Beam 2.76.0, Python 3.14) against two CSV files in Cloud Storage. The job finished and the per-product totals matched values I computed separately. It also passes the repo's flake8 and black checks.

Kokoro is not running at the moment, so ignore its failure statuses on this PR.

Two requests before merging:

  • Add a test. The other samples in dataflow/snippets each have one under tests/, and with Kokoro not running, nothing in CI has run this file. The test below passes against this PR on Python 3.12 and 3.14 with the directory's pinned Beam version, and needs no bucket. Feel free to use it as is.

dataflow/snippets/tests/test_batch_process_storage.py

   ```python
   #  Copyright 2026 Google LLC
   #
   #  Licensed under the Apache License, Version 2.0 (the "License");
   #  you may not use this file except in compliance with the License.
   #  You may obtain a copy of the License at
   #
   #      http://www.apache.org/licenses/LICENSE-2.0
   #
   #  Unless required by applicable law or agreed to in writing, software
   #  distributed under the License is distributed on an "AS IS" BASIS,
   #  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   #  See the License for the specific language governing permissions and
   #  limitations under the License.
   from pathlib import Path

   from ..batch_process_storage import parse_record, run


   def test_parse_record() -> None:
       assert parse_record("1001,widget,19.99") == ("widget", 19.99)


   def test_run_sums_sales_per_product(tmp_path: Path) -> None:
       input_dir = tmp_path / "input"
       input_dir.mkdir()
       (input_dir / "sales_1.csv").write_text(
           "order_id,product,amount\n"
           "1001,widget,19.99\n"
           "1002,gadget,5.50\n"
           "1003,widget,0.01\n"
       )
       (input_dir / "sales_2.csv").write_text(
           "order_id,product,amount\n2001,gadget,4.50\n2002,gizmo,100\n"
       )
       output_dir = tmp_path / "output"

       # No --runner flag, so Apache Beam uses the local DirectRunner.
       run([f"--input={input_dir}/*.csv", f"--output={output_dir}/sales"])

       output_files = sorted(output_dir.glob("sales-*.csv"))
       assert output_files

       rows = []
       for output_file in output_files:
           header, *file_rows = output_file.read_text().splitlines()
           assert header == "product,total_sales"
           rows.extend(file_rows)

       # The header row of each input file is skipped, not summed or emitted.
       assert sorted(rows) == ["gadget,10.00", "gizmo,100.00", "widget,20.00"]
   ```
  • State the input the sample expects. It requires a header row in every input file and exactly three unquoted, comma-separated columns.
  • A file without a header row: the job succeeds and drops the first data row, so the total is wrong.
  • A quoted field containing a comma ("widget, large"), a blank line, a missing field, or a non-numeric amount: the job fails with a ValueError in Parse.

Describing the format in the --input help text or a docstring on run is enough, for example: "CSV files with a header row and three columns: order ID, product, amount." Parsing with the csv module would also make quoted fields work. I would not skip bad rows silently, as the automated review suggests: for a sales total, a failed job is better than a wrong number.

Optional:

  • if name == "main": run() is inside the region tag. batch_write_storage.py keeps it outside. Leave it if the docs page should show the complete file.
  • Amounts are summed as floats, so 100 + 0.125 is written as 100.12. That is fine for a sample unless the page presents it as financial reporting.

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

Please add a test and state the inputs required.

@cbonnie

cbonnie commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @iennae, thank you for the review. Here's the PR for the test for this sample: #15024

Also updated this batch processing sample as you suggested. I chose to keep if __name__ == "__main__": inside the region tag because the guide shows the complete file. Also, amounts stay as floats because the guide doesn't present the totals as financial reporting.

Add expected input in docstring. Parse rows with the `csv` module.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

samples Issues that are directly related to samples.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants