Skip to content

fix: Read and write regular files natively so streams release the GIL - #1

Open
christopher5106 wants to merge 1 commit into
upstream-mainfrom
fix-native-file-streams
Open

christopher5106 wants to merge 1 commit into
upstream-mainfrom
fix-native-file-streams

Conversation

@christopher5106

Copy link
Copy Markdown
Collaborator

Tracks the upstream fix in contentauth#349 (issue contentauth#348). Never merged here: the branch is the head of the upstream PR.

Stream hands regular files to the native library with libc read / lseek / write on a private duplicate of their descriptor, instead of Python callbacks that retake the GIL tens of thousands of times per asset. With this change, signing from several threads scales (8 threads: 2.2 → 19.2 signatures/s on a 4K PNG, 5.8 → 36.3 on a 73 MB MP4), and a busy Python thread no longer stalls a signature for tens of seconds.

Based on upstream-main at ae8628a. Once upstream merges the PR: delete fix-native-file-streams, close this PR, and sync upstream-main.

A Stream serves every read, seek and write of the native library through a
Python callback, tens of thousands per asset (one or more per PNG chunk or BMFF
box), and each callback retakes the GIL. Signing or reading files from several
threads is therefore slower than from one, and any busy Python thread stalls a
signature for tens of seconds.

When the wrapped object is a regular file on a 64-bit POSIX platform, Stream now
hands the native library libc read/lseek/write with a private duplicate of the
file descriptor as context: the native call never re-enters Python. The
duplicate starts at the Python object's position and gives the final position
back on close(), and closing the Python file meanwhile cannot hand its number to
another file. In-memory streams, pipes, append-mode files and other platforms
keep the Python callbacks, as does Stream.native_file_io = False.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.

1 participant