# Bounded binary file reads

- Task: `task_006_utils_threshold_or`
- Status: rejected
- Module: src/click/utils.py
- Behaviour axis: threshold_or_limit
- Interaction partner: src/click/exceptions.py
- Files changed: src/click/exceptions.py, src/click/utils.py
- Repairs: 1

**Stopped at Harbor official checks:** Official Harbor check failed: Harbor nop reward=None, expected 0.0

## Gates

| Gate | Result |
| --- | --- |
| Patch precheck | passed |
| Shape precheck | passed |
| Test hygiene precheck | passed |
| Interface precheck | passed |
| G1 Applies cleanly | passed |
| Base fail ratio | passed |
| G5 Every requirement tested | passed |
| G2 Fail-to-pass | passed |
| G3 No regressions | passed |
| G4 Same result every time | passed |
| G6 Mutation testing | passed |
| Harbor official checks | failed |
| N1 Not already in Click | not run |
| G7 Blind solve | not run |

Mutation testing (G6): 12 of 12 mutants caught.

Harbor: nop reward none (must be 0.0), oracle reward none (must be 1.0).

## requirements.md

Rejected tasks are never packaged, so there is no instruction.md.

# Bounded binary file reads

## Problem Description

Extend `click.open_file` with an optional cumulative byte limit for binary read streams. The limit must apply across successive read operations, including line-oriented access, and report violations through `click.exceptions.FileError`.

The feature must work with regular files, lazy opening, and `"-"` input while preserving existing stream ownership and context-manager behavior. Omitting the limit must preserve existing behavior.

## Acceptance Criteria

- **AC1**: When `max_read_bytes` is `None`, `open_file` behaves as before, including its existing modes, return behavior, lazy opening, atomic writes, and standard-stream handling.
- **AC2**: A nonnegative limit is accepted only for binary read-only mode. Invalid limits or modes are rejected before opening or accessing the requested file or standard stream.
- **AC3**: For a limited stream, bytes returned by `read`, `readline`, and `readinto` share one cumulative count. If an operation would deliver more than the remaining allowance, it raises `FileError` instead of returning partial data. A failing `readinto` leaves its destination unchanged.
- **AC4**: Exactly the limit may be delivered. A subsequent read that reaches EOF succeeds with the normal empty result; a zero-byte operation also succeeds unless a violation has already occurred. This includes a limit of zero.
- **AC5**: After a limit violation, every subsequent read operation on that stream raises the same `FileError`, including zero-byte operations. Seeking does not reset the cumulative count or clear a violation.
- **AC6**: Iteration and `readlines` enforce the same cumulative limit. Where the underlying stream supports `read1` or `readinto1`, those operations also enforce it. No failing operation returns partial data.
- **AC7**: The limit works with both eager and lazy opening and with `"-"` binary input. Leaving a context manager for `"-"`, including after an exception, does not close the underlying standard input.
- **AC8**: Preserve existing behavior for opening errors, stream capabilities, and ownership apart from the specified limit behavior. Document the new argument and its interaction with lazy opening and standard input.

## Interface

### Symbols

- `open_file`
- `FileError`

### Contract Details

- The public signature of `click.open_file` and `click.utils.open_file` is:

  `open_file(filename: str | os.PathLike[str], mode: str = "r", encoding: str | None = None, errors: str | None = "strict", lazy: bool = False, atomic: bool = False, *, max_read_bytes: int | None = None) -> t.IO[t.Any]`

  `max_read_bytes` is keyword-only. Existing positional arguments retain their meanings.

- A supplied limit must be an `int`, excluding `bool`, and must be nonnegative:
  - Any other non-`None` value raises `TypeError` with the exact message `max_read_bytes must be an integer or None`.
  - A negative integer raises `ValueError` with the exact message `max_read_bytes must be nonnegative`.
  - A valid non-`None` limit with a mode other than `"rb"` or `"br"` raises `ValueError` with the exact message `max_read_bytes requires binary read-only mode`.

  Validate in the order listed above. Other argument combinations, including `atomic=True`, retain their existing validation and behavior.

- A limited stream supports the following read interfaces, with the normal parameter names, defaults, and return types of binary file objects:
  - `read(size: int = -1) -> bytes`
  - `readline(size: int = -1) -> bytes`
  - `readinto(buffer: writable bytes-like object) -> int`
  - `readlines(hint: int = -1) -> list[bytes]`
  - `read1(size: int = -1) -> bytes` and `readinto1(buffer: writable bytes-like object) -> int`, where supported by the underlying stream.
  - Iteration yields binary lines and counts their bytes.

  Each operation counts the bytes it would return or place in the destination, not the requested size. `readlines` fails without returning a partial list if its result would exceed the remaining allowance. Normal size, hint, and EOF semantics otherwise apply. Unsupported underlying operations remain unsupported.

- A limit violation raises `click.exceptions.FileError` with the filename represented by `os.fspath(filename)` and the exact hint `Read limit of N bytes exceeded`, where `N` is the decimal limit. Its default-English message is `Could not open file {filename!r}: Read limit of N bytes exceeded`, where `filename` is the result of Click's existing filename formatting. Existing Click exception display and localization behavior remain unchanged; no new CLI output format is introduced.

- After a violation, subsequent read operations raise `FileError` with the same filename and hint, even after seeking or closing the stream. The underlying position after a failing operation is unspecified.

- Context management and explicit closing retain the existing ownership rules. In particular, context exit does not close borrowed standard input; explicit `close()` retains its existing meaning. For lazy regular files, existing early access checks and deferred opening behavior remain intact.

## Compatibility & Out of Scope

- The limit applies to reads through the returned stream's specified interfaces. Direct access through an independently obtained file descriptor or underlying stream is out of scope.
- Do not extend `click.File` or add a CLI option. Text reads, write limits, and read/write modes are out of scope.
- Preserve Click's startup import constraints; do not add eager top-level standard-library imports that increase the module's import footprint.
- The entire existing repository test suite must continue to pass with zero regressions.

## Mutants

| Mutant | Change | Caught |
| --- | --- | --- |
| M01_is_not_none_flip | src/click/utils.py: if self._error is not None: -> if self._error is None: | yes |
| M02_raise_remove | src/click/utils.py: raise self._error -> pass | yes |
| M03_gt_to_le | src/click/utils.py: if count > self._limit - self._count: -> if count <= self._limit - self._count: | yes |
| M04_raise_remove | src/click/utils.py: raise self._error -> pass | yes |
| M05_eq_to_neq | src/click/utils.py: if name == "read1": -> if name != "read1": | yes |
| M06_return_val_none | src/click/utils.py: return data -> return None | yes |
| M07_return_val_none | src/click/utils.py: return read1 -> return None | yes |
| M08_eq_to_neq | src/click/utils.py: if name == "readinto1": -> if name != "readinto1": | yes |
| M09_return_val_none | src/click/utils.py: return self._readinto(method, buffer) -> return None | yes |
| M10_return_val_none | src/click/utils.py: return readinto1 -> return None | yes |
| M11_return_val_none | src/click/utils.py: return getattr(self._file, name) -> return None | yes |
| M12_return_val_none | src/click/utils.py: return data -> return None | yes |

## Reference patch

````diff
diff --git a/src/click/exceptions.py b/src/click/exceptions.py
index 6272c38..a9e567f 100644
--- a/src/click/exceptions.py
+++ b/src/click/exceptions.py
@@ -340,7 +340,7 @@ class NoArgsIsHelpError(UsageError):
 
 
 class FileError(ClickException):
-    """Raised if a file cannot be opened."""
+    """Raised if a file cannot be opened or a configured read limit is exceeded."""
 
     ui_filename: t.Final[str]
     filename: t.Final[str]
diff --git a/src/click/utils.py b/src/click/utils.py
index 617ff5e..0420189 100644
--- a/src/click/utils.py
+++ b/src/click/utils.py
@@ -237,6 +237,116 @@ class _KeepOpenFile:
         return iter(self._file)
 
 
+class _LimitedReadFile:
+    """Count bytes delivered through the binary read interfaces."""
+
+    def __init__(
+        self, file: t.IO[t.Any], filename: str | os.PathLike[str], limit: int
+    ) -> None:
+        self._file = file
+        self._filename = os.fspath(filename)
+        self._limit = limit
+        self._count = 0
+        self._error: Exception | None = None
+
+    def _check_error(self) -> None:
+        if self._error is not None:
+            raise self._error
+
+    def _count_bytes(self, count: int) -> None:
+        if count > self._limit - self._count:
+            from .exceptions import FileError
+
+            self._error = FileError(
+                self._filename, hint=f"Read limit of {self._limit} bytes exceeded"
+            )
+            raise self._error
+
+        self._count += count
+
+    def __getattr__(self, name: str) -> t.Any:
+        if name == "read1":
+            method = getattr(self._file, name)
+
+            def read1(size: int = -1) -> bytes:
+                self._check_error()
+                data = method(size)
+                self._count_bytes(len(data))
+                return data
+
+            return read1
+
+        if name == "readinto1":
+            method = getattr(self._file, name)
+
+            def readinto1(buffer: t.Any) -> int:
+                return self._readinto(method, buffer)
+
+            return readinto1
+
+        return getattr(self._file, name)
+
+    def read(self, size: int = -1) -> bytes:
+        self._check_error()
+        data = self._file.read(size)
+        self._count_bytes(len(data))
+        return data
+
+    def readline(self, size: int = -1) -> bytes:
+        self._check_error()
+        data = self._file.readline(size)
+        self._count_bytes(len(data))
+        return data
+
+    def _readinto(self, method: t.Callable[..., int], buffer: t.Any) -> int:
+        self._check_error()
+        view = memoryview(buffer)
+
+        if view.readonly:
+            raise TypeError("readinto() argument must be read-write bytes-like object")
+
+        view = view.cast("B")
+        temporary = bytearray(view.nbytes)
+        count = method(temporary)
+        self._count_bytes(count)
+        view[:count] = temporary[:count]
+        return count
+
+    def readinto(self, buffer: t.Any) -> int:
+        self._check_error()
+        return self._readinto(self._file.readinto, buffer)
+
+    def readlines(self, hint: int = -1) -> list[bytes]:
+        self._check_error()
+        lines = self._file.readlines(hint)
+        self._count_bytes(sum(map(len, lines)))
+        return lines
+
+    def __iter__(self) -> _LimitedReadFile:
+        return self
+
+    def __next__(self) -> bytes:
+        line = self.readline()
+        if not line:
+            raise StopIteration
+        return line
+
+    def __enter__(self) -> _LimitedReadFile:
+        self._file.__enter__()
+        return self
+
+    def __exit__(
+        self,
+        exc_type: type[BaseException] | None,
+        exc_value: BaseException | None,
+        tb: TracebackType | None,
+    ) -> t.Any:
+        return self._file.__exit__(exc_type, exc_value, tb)
+
+    def __repr__(self) -> str:
+        return repr(self._file)
+
+
 def echo(
     message: object = None,
     file: t.IO[t.Any] | None = None,
@@ -385,6 +495,8 @@ def open_file(
     errors: str | None = "strict",
     lazy: bool = False,
     atomic: bool = False,
+    *,
+    max_read_bytes: int | None = None,
 ) -> t.IO[t.Any]:
     """Open a file, with extra behavior to handle ``'-'`` to indicate
     a standard stream, lazy open on write, and atomic write. Similar to
@@ -411,18 +523,35 @@ def open_file(
         early, then closed until it is read again.
     :param atomic: Write to a temporary file and replace the given file
         on close.
+    :param max_read_bytes: Maximum cumulative bytes returned by binary
+        read operations, or ``None`` for no limit. Only binary read-only
+        modes are supported. Exceeding the limit raises
+        :exc:`~click.FileError`. Lazy reads retain their early access check
+        and deferred opening. For ``'-'``, context exit still leaves
+        standard input open.
 
     .. versionadded:: 3.0
     """
+    if max_read_bytes is not None:
+        if isinstance(max_read_bytes, bool) or not isinstance(max_read_bytes, int):
+            raise TypeError("max_read_bytes must be an integer or None")
+        if max_read_bytes < 0:
+            raise ValueError("max_read_bytes must be nonnegative")
+        if mode not in {"rb", "br"}:
+            raise ValueError("max_read_bytes requires binary read-only mode")
+
     if lazy:
-        return t.cast(
+        f = t.cast(
             "t.IO[t.Any]", _LazyFile(filename, mode, encoding, errors, atomic=atomic)
         )
+    else:
+        f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)
 
-    f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)
+        if not should_close:
+            f = t.cast("t.IO[t.Any]", _KeepOpenFile(f))
 
-    if not should_close:
-        f = t.cast("t.IO[t.Any]", _KeepOpenFile(f))
+    if max_read_bytes is not None:
+        f = t.cast("t.IO[t.Any]", _LimitedReadFile(f, filename, max_read_bytes))
 
     return f
````
