Skip to content

Prevent array.tofile re-entrant deadlock and add regression snippet - #6559

Merged
youknowone merged 2 commits into
mainfrom
copilot/fix-deadlock-array-tofile
Dec 28, 2025
Merged

youknowone merged 2 commits into
mainfrom
copilot/fix-deadlock-array-tofile

Conversation

Copilot AI commented Dec 28, 2025 •

Copy link
Copy Markdown
Contributor

array.tofile held a read lock while calling user write; re-entrant mutations (e.g., append) then blocked on a write lock, hanging the interpreter.

  • Locking: Copy array bytes before writing so write runs without holding the array read lock, avoiding deadlock on re-entrancy.
  • Regression coverage: Added snippet exercising a writer that mutates the same array during tofile.

Example:

class Writer:
    def __init__(self, arr):
        self.arr = arr
        self.reentered = False
    def write(self, chunk):
        if not self.reentered:
            self.reentered = True
            self.arr.append(0)
        return len(chunk)

arr = array('b', range(128))
arr.tofile(Writer(arr))  # no hang; length becomes 129
Original prompt

This section details on the original issue you should resolve

<issue_title>Deadlock when writer mutates the same array via array.tofile</issue_title>
<issue_description>### What happened?

array.tofile holds a read lock on the array buffer while calling the user-provided file object's write method. If that write re-enters and mutates the array (e.g., append), it tries to take a write lock that is blocked by the outstanding read lock, causing the interpreter to hang.

Proof of Concept:

import array

class Writer:
    def __init__(self, arr):
        self.arr = arr
        self.reentered = False

    def write(self, chunk):
        if not self.reentered:
            self.reentered = True
            self.arr.append(0)
        return len(chunk)

arr = array.array('b', range(128))
arr.tofile(Writer(arr))
Affected Versions
RustPython Version Status Exit Code
Python 3.13.0alpha (heads/main-dirty:21300f689, Dec 13 2025, 22:16:49) [RustPython 0.4.0 with rustc 1.90.0-nightly (11ad40bb8 2025-06-28)] Deadlock 124
Vulnerable Code
fn tofile(&self, f: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
    const BLOCKSIZE: usize = 64 * 1024;

    let bytes = self.read();                 // Holds the array read lock for the whole write
    let bytes = bytes.get_bytes();

    for b in bytes.chunks(BLOCKSIZE) {
        let b = PyBytes::from(b.to_vec()).into_ref(&vm.ctx);
        vm.call_method(&f, "write", (b,))?;  // Re-enters Python; user `write` may mutate the same array
    }
    Ok(())
}

#[pymethod]
fn append(zelf: &Py<Self>, x: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
    zelf.try_resizable(vm)?.push(x, vm)       // Requires a write lock while `tofile` still holds the read lock
}

fn try_resizable_opt(&self) -> Option<PyRwLockWriteGuard<'_, ArrayContentType>> {
    let w = self.write();                     // Blocks forever when `append` runs during `tofile`'s read lock
    (self.exports.load(atomic::Ordering::SeqCst) == 0).then_some(w)
}
Rust Output
Program hangs forever
CPython Output
(No output)

</issue_description>

<agent_instructions>Add the poc code to extra_tests/snippets/stdlib_array.py and fix the problem.</agent_instructions>

Comments on the Issue (you are @copilot in this section)


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

@coderabbitai

coderabbitai Bot commented Dec 28, 2025

Copy link
Copy Markdown
Contributor

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Comment @coderabbitai help to get the list of available commands and usage tips.

Copilot AI changed the title [WIP] Fix deadlock when writer mutates array during tofile Prevent array.tofile re-entrant deadlock and add regression snippet Dec 28, 2025
Copilot AI requested a review from youknowone December 28, 2025 04:23
@youknowone
youknowone marked this pull request as ready for review December 28, 2025 05:14
@youknowone
youknowone merged commit 04a4d1e into main Dec 28, 2025
@youknowone
youknowone deleted the copilot/fix-deadlock-array-tofile branch December 28, 2025 05:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Deadlock when writer mutates the same array via array.tofile

2 participants