Skip to content

Fix SystemError in _DeferredCall.get() under GC pressure#38355

Open
arr2036 wants to merge 1 commit intoapache:masterfrom
arr2036:fix/deferred-call-gc-tuple-resize
Open

Fix SystemError in _DeferredCall.get() under GC pressure#38355
arr2036 wants to merge 1 commit intoapache:masterfrom
arr2036:fix/deferred-call-gc-tuple-resize

Conversation

@arr2036
Copy link
Copy Markdown

@arr2036 arr2036 commented May 1, 2026

Summary

_DeferredCall.get() in sdk_worker.py used a generator expression in the argument unpack position:

return self._func(*(arg.get(timeout) for arg in self._args))

Under sustained load this raises SystemError: Objects/tupleobject.c:927: bad argument to internal function.

Root cause

CPython builds the argument tuple incrementally when unpacking a generator, calling _PyTuple_Resize after each yield to grow the tuple by one slot. _PyTuple_Resize guards:

// cpython/Objects/tupleobject.c (Python 3.11)
// https://github.com/python/cpython/blob/3.11/Objects/tupleobject.c#L232
if (v == NULL || !PyTuple_Check(v) ||
    (Py_SIZE(v) != 0 && Py_REFCNT(v) != 1)) {
    *pv = 0;
    Py_XDECREF(v);
    PyErr_BadInternalCall();
    return -1;
}

Between generator yields, a GC cycle can run (triggered by allocations inside arg.get()). The GC can increment the refcount on the partially-built tuple. When _PyTuple_Resize next fires, Py_REFCNT(v) != 1 is true and it raises SystemError.

The call site is bundle_processor.py:637 (state.commit() -> to_await.get() -> _DeferredCall.get()), which is on the hot path for every bundle that commits state. High-throughput streaming pipelines hit this continuously.

Observed stack trace (Python 3.11, Beam 2.73.0, production worker)

File ".../sdk_worker.py", line 316, in _execute
    response = task()
File ".../sdk_worker.py", line 390, in <lambda>
    lambda: self.create_worker().do_instruction(request), request)
File ".../sdk_worker.py", line 707, in process_bundle
    bundle_processor.process_bundle(instruction_id))
File ".../bundle_processor.py", line 1310, in process_bundle
    op.finish()
File ".../bundle_processor.py", line 1028, in commit
    state.commit()
File ".../bundle_processor.py", line 637, in commit
    to_await.get()
File ".../sdk_worker.py", line 1457, in get
    return self._func(*(arg.get(timeout) for arg in self._args))
SystemError: Objects/tupleobject.c:927: bad argument to internal function

Fix

Change the generator expression to a list comprehension:

return self._func(*[arg.get(timeout) for arg in self._args])

CPython materialises the full list before the call. CALL_FUNCTION_EX receives a list and takes the PySequence_Fast path, which for a list is a no-op (just incref). The argument tuple is allocated once at its final size via PyTuple_New. _PyTuple_Resize is never called.

_DeferredCall.__init__ already wraps non-_Future args eagerly, so materialising the list before the call preserves existing semantics.

Why _DeferredCall.wait() is unaffected

wait() also uses a generator expression (all(arg.wait(timeout) for arg in self._args)) but passes it to all(), which is a C built-in that consumes the generator without building a resizable tuple. The crash path is specific to *(gen) unpacking in a function call.

Tests

Added DeferredCallTest in sdk_worker_test.py covering single-arg, multi-arg, non-Future arg wrapping, mixed Future+value, zero-arg, and return value type preservation.

The crash itself requires specific CPython internal timing (GC cycle between PySequence_Tuple's calls to the generator's __next__, against the C-level partial tuple) and cannot be triggered deterministically from pure Python without a C extension or a CPython debug build. The argument for the fix rests on the CPython source and the observed production stack trace above.

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a critical SystemError occurring in _DeferredCall.get() within high-throughput streaming pipelines. The error stemmed from a subtle interaction between Python's garbage collector and the incremental tuple resizing mechanism used when unpacking generator expressions. By switching to a list comprehension, the arguments are materialized into a full list before the function call, bypassing the problematic incremental resizing and significantly improving the stability of the worker SDK under load.

Highlights

  • Fixed SystemError in _DeferredCall.get(): Resolved a SystemError (Objects/tupleobject.c:927: bad argument to internal function) that occurred under garbage collector (GC) pressure when unpacking a generator expression in _DeferredCall.get().
  • Changed generator to list comprehension: Replaced the generator expression *(arg.get(timeout) for arg in self._args) with a list comprehension *[arg.get(timeout) for arg in self._args] to prevent incremental tuple resizing issues that caused the SystemError.
  • Added comprehensive unit tests: Introduced a new DeferredCallTest class with multiple test cases covering single, multiple, non-Future, mixed, and zero arguments, as well as return value type preservation for _DeferredCall.get().

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@arr2036
Copy link
Copy Markdown
Author

arr2036 commented May 1, 2026

Seeing about 4K crashes per day at a 1000PPS rate with ~12 workers.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

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 replaces a generator expression with a list comprehension in _DeferredCall.get() to prevent a CPython internal race condition that can cause a SystemError. It also introduces a new test suite, DeferredCallTest, to ensure correct behavior across various argument types. A minor correction was suggested for a method name typo in the test class docstring.

Comment thread sdks/python/apache_beam/runners/worker/sdk_worker_test.py Outdated
@arr2036 arr2036 force-pushed the fix/deferred-call-gc-tuple-resize branch 2 times, most recently from 79dafb9 to f343f1c Compare May 1, 2026 14:31
CPython builds the argument tuple incrementally via _PyTuple_Resize when
unpacking a generator: f(*(gen)).  _PyTuple_Resize guards that
Py_REFCNT(v) == 1 before resizing a non-empty tuple.  Under sustained
allocation pressure a GC cycle can run between generator yields and
temporarily increment the refcount on the partial tuple, causing
_PyTuple_Resize to call PyErr_BadInternalCall().

Change the generator expression to a list comprehension.  CPython builds
the list first and passes it to CALL_FUNCTION_EX, which takes the
PySequence_Fast list path and never calls _PyTuple_Resize.
@arr2036 arr2036 force-pushed the fix/deferred-call-gc-tuple-resize branch from f343f1c to 6628a3d Compare May 1, 2026 15:18
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 1, 2026

Checks are failing. Will not request review until checks are succeeding. If you'd like to override that behavior, comment assign set of reviewers

@arr2036
Copy link
Copy Markdown
Author

arr2036 commented May 2, 2026

assign set of reviewers

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 2, 2026

Assigning reviewers:

R: @tvalentyn for label python.

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