Skip to content

[Python] Unroll 2-component KV fast path in AbstractComponentCoderImpl - #41216

Open
damccorm wants to merge 3 commits into
apache:masterfrom
damccorm:perf/py-component-coder-kv-fastpath
Open

damccorm wants to merge 3 commits into
apache:masterfrom
damccorm:perf/py-component-coder-kv-fastpath

Conversation

@damccorm

@damccorm damccorm commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

;tldr - AbstractComponentCoderImpl is most commonly used for KVs, so we should make that specific path faster.

Note: this PR was auto-generated by tooling. Before moving it out of draft, the author has done a full review of the PR, specifically evaluating it on the following criteria:

  • Is the description accurate? In particular, are the benchmarks correct, meaningful, and reproducible.
  • Does the PR avoid doing harm (changes should be non-functional, perf only)?
  • (Judgement) Is the code change (and cost of reviewing) worth the performance improvement?

Full details of the methodology of generation and review can be found here - Apache Beam Python SDK Performance PRs Methodology & Branches Impact Ranking

If you have concerns with the PR or with the underlying methodology used to generate this, please comment below - they will be addressed by the author not the tooling :)

Summary of changes:

Optimizes AbstractComponentCoderImpl in sdks/python/apache_beam/coders/coder_impl.py and sdks/python/apache_beam/coders/coder_impl.pxd:

  1. Unroll 2-component (KV) fast path in encode_to_stream and decode_from_stream:
    • Stores Cython attributes _num_coders, _is_kv, _coder_0, and _coder_1 when len(self._coder_impls) == 2 so 2-tuples (KV pairs) encode and decode directly without range() loop overhead or list comprehension + tuple() allocation on every element.

Dataflow benchmarks showing improvement:

  • Before the change: 2026-11-12_12_17_27-13200570131762963874
  • After the change: 2026-11-12_12_17_26-14979577080798624478
  • Summary of perf improvement: In a single-worker (n1-standard-8, --autoscaling_algorithm=NONE --num_workers=1 --max_num_workers=1) Cloud Dataflow pipeline running 50,000,000 typed KV[int, tuple[int, int]] · CombinePerKey(CountCombineFn), built-in transform stage execution time improved from 613,960 ms -> 539,217 ms (1.14x faster, -12.2%) (total single-worker job vCPU time: 1860s -> 1729s).

Additional benchmarks

  • Isolated Microbenchmark Rerun (upstream/master vs upstream/master + this PR alone): bench_17_component_coder_kv_fastpath (c2feb961eef) (on branch perf/py-benchmarks-suite) — 500,000 2-tuple (KV) encode + decode round-trips in TupleCoderImpl improved from 220.40 ms -> 124.94 ms (1.76x faster, -43.3%, -95.46 ms) in compiled Cython.

  • Per-Change Attribution (Most to Least Impact, 500,000 calls each in compiled Cython):

    1. Most impact (60.7% of stream savings, -38.66 ms): 2-component encode_to_stream fast path (_coder_0.encode_to_stream / _coder_1.encode_to_stream) — 74.72 ms -> 36.06 ms (2.07x faster, -51.7%).
    2. Second (39.3% of stream savings, -25.06 ms): 2-component decode_from_stream fast path ((_coder_0.decode_from_stream, _coder_1.decode_from_stream) without list comprehension + tuple()) — 62.73 ms -> 37.67 ms (1.67x faster, -39.9%).
  • End-to-End Cloud Dataflow Benchmark (core_window_row_combine): Included in run_core_window_row_combine_pipeline (c2feb961eef) (3,000,000 generated events -> 9,000,000 sliding-windowed elements on a single n2-standard-4 worker), which improved end-to-end worker stage execution time by 1.80x (-44.5%, 599.6s -> 332.9s) and reduced total billable Dataflow vCPU/Memory/PD usage by -26.1% (1,134 -> 838 vCPU-s).

  • Per-Piece Ablation Breakdown (Compiled Cython, 465.38 ms -> 280.70 ms, 1.66x faster, -184.69 ms across 400k 2-tuple KV + 100k 3-tuple round-trips):

    Logical Piece Share of Gain (Sequential) Marginal Share (Leave-One-Out)
    2-component KV fast path in AbstractComponentCoderImpl.encode_to_stream 55.4% (-102.40 ms) 6.0% (-11.08 ms, overlaps with typed loop)
    2-component KV fast path in AbstractComponentCoderImpl.decode_from_stream 29.4% (-54.28 ms) 14.7% (-27.18 ms)
    Cached cdef int _num_coders + typed i, last loop bounds for N-ary tuples 15.2% (-28.01 ms) 15.8% (-29.22 ms)

Testing

  • Verified with pytest sdks/python/apache_beam/coders/coders_test.py sdks/python/apache_beam/coders/fast_coders_test.py.

@damccorm

Copy link
Copy Markdown
Contributor Author

/gemini review

@github-actions github-actions Bot added python core size/s S: 10-49 lines changed labels Nov 11, 2026

@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 introduces a Cython-friendly fast path in AbstractComponentCoderImpl for 2-component (KV) tuples by caching _coder_0, _coder_1, _num_coders, and _is_kv at initialization time. The optimization is clean, preserves existing wire format and nesting semantics, and yields substantial throughput gains for KV encoding/decoding.

🔍 General Feedback

  • In decode_from_stream, the non-KV fallback path replaced the c-bound loop variable with self._coder_impls[i].decode_from_stream(...), which loses the CoderImpl static Cython type on tuple indexing and falls back to Python attribute lookup.
  • coder_impl.pxd declares last=int in @cython.locals for get_estimated_size_and_observables, where last is not defined.

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

@damccorm

Copy link
Copy Markdown
Contributor Author

/gemini review

@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 adds a fast path for 2-component (KV) coders in AbstractComponentCoderImpl.encode_to_stream and AbstractComponentCoderImpl.decode_from_stream, along with corresponding Cython attribute and local variable declarations in coder_impl.pxd. The implementation preserves exact nested encoding/decoding semantics and component length validation while eliminating loop and list-allocation overhead on the hot path.

🔍 General Feedback

  • The 2-component unrolling accurately preserves the nested=True behavior for the first component and forwards nested to the second component.
  • Passing a 2-tuple directly to _construct_from_components in decode_from_stream cleanly takes advantage of TupleCoderImpl._construct_from_components (tuple(components)) returning the existing tuple without extra allocation.
  • Cython cdef attributes and @cython.locals declarations in coder_impl.pxd are properly aligned with the implementation in coder_impl.py.

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

@codecov

codecov Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 57.82%. Comparing base (d3078c1) to head (ddf9187).
⚠️ Report is 355 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master   #41216      +/-   ##
============================================
+ Coverage     57.48%   57.82%   +0.34%     
  Complexity     2492     2492              
============================================
  Files          1204     1200       -4     
  Lines        171265   171969     +704     
  Branches       2103     2103              
============================================
+ Hits          98456    99446     +990     
+ Misses        70157    69871     -286     
  Partials       2652     2652              
Flag Coverage Δ
python 80.72% <100.00%> (+0.50%) ⬆️

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.

@damccorm damccorm added the ready-for-human Draft PR with all checks passing and all review comments resolved, ready for human review label Nov 11, 2026
@damccorm damccorm removed the ready-for-human Draft PR with all checks passing and all review comments resolved, ready for human review label Nov 25, 2026
@damccorm

Copy link
Copy Markdown
Contributor Author

/gemini review

@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 introduces a fast path in AbstractComponentCoderImpl for 2-component (KV) tuples by caching Cython-typed attributes (_num_coders, _is_kv, _coder_0, _coder_1) and unrolling encode_to_stream and decode_from_stream. All previous review comments regarding Cython local typing have been properly addressed, and the implementation is clean and behaviorally identical to the general N-ary path.

🔍 General Feedback

  • The fast path accurately preserves component nesting semantics (True for the first component, nested for the second) and component length validation (self._num_coders != len(values)).
  • Cython declarations in coder_impl.pxd properly match the implementation in coder_impl.py, maintaining typed cpdef dispatch for both the 2-component fast path and the fallback loop.

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

@damccorm
damccorm marked this pull request as ready for review November 25, 2026 21:05
@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @shunping for label python.
Backup reviewer: tvalentyn (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).

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.

1 participant