Skip to content

API Reference parrot.tools.optimizations.reader

github-actions[bot] edited this page Nov 5, 2026 · 4 revisions

parrot.tools.optimizations.reader

View source

Bounded, streaming source reading for Claude Code / Codex (FEAT-543).

:class:BoundedSourceToolkit replaces "read the whole file into the context window" with an explicitly bounded read. A file above 350 logical lines or 64,000 on-disk bytes (either threshold, both configurable) requires an explicit inclusive 1-based range; every result carries the file's SHA-256 revision and a continuation cursor so the caller can page through it safely.

The reader never holds a whole file in memory and never returns a partial line. ReadOnlyRepoToolkit.read_file is deliberately not reused: it reads the entire file and then slices it (repo/toolkit.py:227-243). That API is preserved untouched; this is a separate toolkit.

The helpers above the toolkit class are pure, synchronous and stdlib-only so they can be reused for reference slices (TASK-3083) and host-side threshold detection (TASK-3088) without dragging in toolkit state.

Class BoundedSourceToolkit

Read source files under explicit line, byte and revision bounds.

Parameter Type Default Description
**kwargs Any {} Forwarded to :class:~parrot.tools.optimizations.base.OptimizationToolkitBase (repo_root is required).

Attributes:

Attribute Type Description
arg_models dict[str, type[BaseModel]]

Method BoundedSourceToolkit.source_info

Report a file's size, revision and whether a read needs a range.

No file content is ever returned by this tool.

source_info(path: str) -> SourceInfo | OperationResult

Parameter Type Default Description
path str A repository-relative file path.

Returns: SourceInfo | OperationResult — The file's bounded metadata, or an error result.

Method BoundedSourceToolkit.source_read

Read a small file whole, or an explicit inclusive line range.

Files above either configured threshold require both range ends. Only complete lines are returned; continue with next_line and expected_sha256 to page through a file safely.

source_read(path: str, start_line: Optional[int] = None, end_line: Optional[int] = None, expected_sha256: Optional[str] = None) -> SourceResult | OperationResult

Parameter Type Default Description
path str A repository-relative file path.
start_line Optional[int] None First line to read, 1-based inclusive.
end_line Optional[int] None Last line to read, 1-based inclusive.
expected_sha256 Optional[str] None The revision the caller expects; the read is refused when the file has changed since.

Returns: SourceResult | OperationResult — The bounded slice, or an error result.

Method BoundedSourceToolkit.source_inspect_batch

Inspect independent read-only operations with bounded concurrency.

Up to 8 read-only operations (read/info/search/files/git_status/ git_diff_names) run under a shared, instance-wide admission limit of 4 concurrent items; the whole batch is bounded to 20 seconds and each item to 10 seconds. One item failing, timing out, or being cut off by the batch deadline never removes another item's identity from the response — see :class:~parrot.tools.optimizations.inspection.InspectionRunner.

source_inspect_batch(requests: list[dict[str, object]], concurrency: int = 4, max_output_bytes: int = 24576) -> OperationResult

Parameter Type Default Description
requests list[dict[str, object]] Raw per-item request dicts, discriminated by kind.
concurrency int 4 Concurrent items for this batch, between 1 and 4.
max_output_bytes int 24576 The serialized response byte budget.

Returns: OperationResult — A bounded :class:OperationResult wrapping the batch, or an invalid_arguments error result when validation fails.

Class ConcurrentModificationError

Raised when the file changed identity while it was being scanned.

Class FileIdentity

A file's identity for concurrent-modification detection.

Attributes:

Attribute Type Description
inode int The inode number.
size int The on-disk size in bytes.
mtime_ns int The modification time in nanoseconds.

Class HashTimeoutError

Raised when hashing a very large file exceeded its deadline.

Class InvalidEncodingError

Raised when a line is not valid UTF-8 (decoding is strict).

Parameter Type Default Description
line_no int The 1-based line number that failed to decode.

Class LineTooLargeError

Raised when one line alone exceeds the caller's byte bound.

Parameter Type Default Description
line_no int The 1-based line number.
at_least_bytes int A lower bound on the line's size in bytes.

Class NotRegularFileError

Raised for a device, FIFO, socket or directory.

Class RangeOutOfBoundsError

Raised when the requested start line is past the end of the file.

Parameter Type Default Description
start_line int The requested start line.
total_lines int The number of lines the file actually has.

Class RangeRead

The outcome of reading an inclusive line range.

Attributes:

Attribute Type Description
lines list[str] The complete lines read, with their line endings preserved.
actual_end int The last line number actually returned.
eof bool True when the file ended at or before the requested end.

Class ReaderError

Base class for bounded-reader failures.

Function check_identity_unchanged

Verify the file has not changed identity since before was taken.

check_identity_unchanged(before: FileIdentity, path: Path) -> None

Parameter Type Default Description
before FileIdentity The identity captured before the scan.
path Path The file to re-stat.

Raises:

  • ConcurrentModificationError — The file changed while being scanned.

Function count_lines_bounded

Count logical lines, stopping early once the bound is exceeded.

A final line without a trailing newline still counts as a line.

count_lines_bounded(path: Path, stop_after: int) -> tuple[int, bool]

Parameter Type Default Description
path Path The file to count.
stop_after int The threshold to compare against.

Returns: tuple[int, bool] — A (count, exceeded) tuple. When exceeded is True the exact count is unknown and count is stop_after + 1.

Function read_line_range

Read an inclusive 1-based line range without loading the whole file.

Memory is bounded by max_line_bytes plus the buffer size, never by the file's length: an oversized line is reported by number and size rather than being read into memory or silently cut.

read_line_range(path: Path, start_line: int, end_line: int, *, max_line_bytes: int) -> RangeRead

Parameter Type Default Description
path Path The file to read.
start_line int First line to return, 1-based inclusive.
end_line int Last line to return, 1-based inclusive.
max_line_bytes int The largest single line that may be materialized.

Returns: RangeRead — The lines read, the last line number returned, and whether the file ended at or before end_line.

Raises:

  • LineTooLargeError — A line exceeds max_line_bytes.
  • InvalidEncodingError — A line is not valid UTF-8.
  • RangeOutOfBoundsError — start_line is past the last line.

Function sha256_stream

Hash a file's bytes in bounded memory, under a wall-clock deadline.

sha256_stream(path: Path, *, deadline_seconds: float) -> str

Parameter Type Default Description
path Path The file to hash.
deadline_seconds float Maximum time to spend hashing.

Returns: str — The lowercase hex SHA-256 digest.

Raises:

  • HashTimeoutError — Hashing exceeded the deadline.

Function sniff_binary

Detect a binary file by looking for a NUL byte in its first bytes.

sniff_binary(path: Path, probe: int = 8192) -> bool

Parameter Type Default Description
path Path The file to sniff.
probe int 8192 How many leading bytes to inspect.

Returns: bool — True when the probe contains a NUL byte.

Function stat_regular

Stat path, rejecting symlinks and anything but a regular file.

os.lstat is used so a symlink is detected rather than followed.

stat_regular(path: Path) -> FileIdentity

Parameter Type Default Description
path Path The file to stat.

Returns: FileIdentity — The file's identity.

Raises:

  • FileNotFoundError — The path does not exist.
  • SymlinkRejectedError — The path is a symlink.
  • NotRegularFileError — The path is a device, FIFO, socket or directory.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally