Limit local file reads before parsing a manifest
Direct answer
Checking Path.stat().st_size before parsing can reject an obviously oversized manifest without loading its contents. Here the fixture contains 33 bytes and the demonstration limit is 32. The assertion verifies that this file belongs in the oversized branch; the example never calls a parser or reads the payload back.
Use a byte limit derived from the actual manifest contract. A tiny fixture makes the comparison easy to inspect, but 32 bytes is not a sensible universal limit for JSON or TOML. Keep an oversized result distinct from invalid syntax: the document was rejected before its structure was examined.
A metadata check alone is not a hard memory bound. Another process could grow or replace the file between stat and a later read. When the read itself must be bounded, open the file and request at most the limit plus one byte, rejecting an extra byte. That additional step is separate from the metadata observation demonstrated here.
Complete example
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as d:
p = Path(d) / 'manifest'
p.write_bytes(b'x' * 33)
assert p.stat().st_size > 32
result = 'kind=too-large limit=32'
print(result)
Expected stdout (for a platform supporting the demonstrated operation):
kind=too-large limit=32
Sources
Prepared with AI assistance. The example uses synthetic data; its stated limits apply.
Comments
Post a Comment