Comfy-Org / Comfy-Org/ComfyUI

Unclosed file handle when loading mask image in /upload/mask endpoint

Open
#13,335 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Python
Stars
133k
Forks
15.7k
Avg merge
1d 7h
Merged PRs (30d)
158

Description

## Bug

In `server.py`, the `/upload/mask` endpoint opens the uploaded mask image file without using a context manager, which means the underlying file handle is never explicitly closed:

```python
# line ~488
mask_pil = Image.open(image.file).convert('RGBA')
```

The `convert()` call returns a new `Image` object that is a copy in memory, but the original file opened by `Image.open()` still holds a file descriptor. Without `with Image.open(...) as ...` or an explicit `.close()`, the file handle leaks and is only eventually closed by the garbage collector (which is non-deterministic in CPython and unreliable in other runtimes).

Compare with the original image a few lines above, which correctly uses a context manager:

```python
with Image.open(file) as original_pil: # correct
...
mask_pil = Image.open(image.file).convert('RGBA') # missing context manager
```

Under heavy upload load this can exhaust the process's open file descriptor limit (typically 1024 on Linux).

## Fix

Wrap the mask open in a context manager:

```python
with Image.open(image.file) as mask_pil_raw:
mask_pil = mask_pil_raw.convert('RGBA')
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.