"""Observe Linux seek classification on new, private regular files only.""" import argparse import datetime import errno import hashlib import json import os from pathlib import Path import platform import subprocess import tempfile SIZE = 16384 BLOCK = 4096 def query(fd, offset, mode, seek=os.lseek): try: return {"offset": seek(fd, offset, mode)} except OSError as error: return {"errno": error.errno, "error": errno.errorcode.get(error.errno, "UNKNOWN")} def scan(fd, size, seek=os.lseek): """Requires a stable regular file; errors other than no remaining data propagate.""" if not isinstance(size, int) or isinstance(size, bool) or size < 0: raise ValueError("size must be a nonnegative integer") ranges = [] cursor = 0 while cursor < size: try: data = seek(fd, cursor, os.SEEK_DATA) except OSError as error: if error.errno != errno.ENXIO: raise ranges.append({"kind": "hole", "start": cursor, "end": size}) break if not cursor <= data < size: raise ValueError("data offset outside remaining file") if data > cursor: ranges.append({"kind": "hole", "start": cursor, "end": data}) hole = seek(fd, data, os.SEEK_HOLE) if not data < hole <= size: raise ValueError("hole offset must advance within file bounds") ranges.append({"kind": "data", "start": data, "end": hole}) cursor = hole return ranges def read_exact(fd, start, length, read=os.pread): parts = [] done = 0 while done < length: part = read(fd, length - done, start + done) if not part: raise RuntimeError("source shortened during read") parts.append(part) done += len(part) return b"".join(parts) def write_exact(fd, payload, offset): done = 0 while done < len(payload): count = os.pwrite(fd, payload[done:], offset + done) if count <= 0: raise RuntimeError("write made no progress") done += count def prepare(path, kind): fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o600) try: size = 0 if kind == "empty" else SIZE os.ftruncate(fd, size) if kind == "written-zeros": write_exact(fd, bytes(SIZE), 0) elif kind == "mixed": write_exact(fd, b"X" * BLOCK, BLOCK) os.fsync(fd) return fd except BaseException: os.close(fd) raise def observe_case(folder, kind): path = Path(folder) / kind fd = prepare(path, kind) try: initial = os.fstat(fd) size = initial.st_size # Query before readback: reading can itself affect later seek classification. ranges = scan(fd, size) endpoints = { str(offset): { name: query(fd, offset, mode) for name, mode in [("data", os.SEEK_DATA), ("hole", os.SEEK_HOLE)] } for offset in sorted({0, max(0, size - 1), size, size + 1}) } cursor = None if kind == "mixed": alias = os.dup(fd) independent = os.open(path, os.O_RDONLY) try: os.lseek(fd, 17, os.SEEK_SET) found = os.lseek(alias, BLOCK, os.SEEK_HOLE) shared = os.lseek(fd, 0, os.SEEK_CUR) independent_cursor = os.lseek(independent, 0, os.SEEK_CUR) payload = read_exact(fd, BLOCK, BLOCK) after_pread = os.lseek(fd, 0, os.SEEK_CUR) cursor = { "before_seek": 17, "seek_hole_result": found, "original_after_dup_seek": shared, "separately_opened_cursor": independent_cursor, "original_after_pread": after_pread, "pread_matches_pattern": payload == b"X" * BLOCK, } finally: os.close(alias) os.close(independent) payload = read_exact(fd, 0, size) expected = bytes(size) if kind != "mixed" else ( bytes(BLOCK) + b"X" * BLOCK + bytes(SIZE - 2 * BLOCK) ) if payload != expected: raise RuntimeError("file content differs from preparation oracle") if any(any(payload[r["start"]:r["end"]]) for r in ranges if r["kind"] == "hole"): raise RuntimeError("reported hole contains nonzero bytes") final = os.fstat(fd) if (initial.st_size, initial.st_mtime_ns) != (final.st_size, final.st_mtime_ns): raise RuntimeError("file changed during observation") return { "case": kind, "size_bytes": size, "st_blocks_512": initial.st_blocks, "ranges": ranges, "endpoints": endpoints, "cursor": cursor, "readback_sha256": hashlib.sha256(payload).hexdigest(), "readback_matches_preparation": True, "reported_holes_read_zero": True, } finally: os.close(fd) def capture(parent): with tempfile.TemporaryDirectory(prefix="hesela-seek-", dir=parent) as folder: fs = subprocess.run(["findmnt", "-n", "-o", "FSTYPE", "-T", folder], check=True, text=True, capture_output=True).stdout.strip() cases = [observe_case(folder, name) for name in ["empty", "unwritten-zeros", "written-zeros", "mixed"]] return { "schema_version": 1, "generated_at": datetime.datetime.now(datetime.timezone.utc).isoformat(), "environment": { "system": platform.system(), "kernel": platform.release(), "python": platform.python_version(), "libc": list(platform.libc_ver()), "filesystem": fs, }, "method": "Four new private regular files; ftruncate, optional pwrite, fsync, seek scan and endpoint queries, then complete pread verification.", "scope": "Single-host API observation; no concurrent writers, crash, physical-capacity measurement or universal hole-map claim.", "probe_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "cases": cases, } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--parent", default=None, help="Existing scratch directory on the filesystem to test") parser.add_argument("--output", type=Path, required=True, help="New JSON receipt; existing files are not overwritten") args = parser.parse_args() if platform.system() != "Linux" or not all(hasattr(os, x) for x in ["SEEK_DATA", "SEEK_HOLE"]): parser.error("this probe requires Linux and SEEK_DATA / SEEK_HOLE") result = capture(args.parent) with args.output.open("x", encoding="utf-8") as stream: json.dump(result, stream, indent=2) stream.write("\n") if __name__ == "__main__": main()