#!/usr/bin/env python3 """Compare Linux process-owned record locks and flock after a second close.""" # SPDX-License-Identifier: MIT import argparse from datetime import datetime, timezone import errno import fcntl import hashlib import json import os from pathlib import Path import platform import subprocess import sys import tempfile SOURCE = Path(__file__).resolve() KINDS = ("process-record", "flock") CLOSE_CASES = ("separate-open", "hard-link-open", "duplicate") def identity(fd): info = os.fstat(fd) return [info.st_dev, info.st_ino] def lock(fd, kind): if kind == "process-record": fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB, 0, 0, os.SEEK_SET) elif kind == "flock": fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) else: raise ValueError("Unknown lock kind") def probe(path, kind): fd = os.open(path, os.O_RDWR) try: result = {"identity": identity(fd)} try: lock(fd, kind) result["acquired"] = True except OSError as error: if error.errno not in (errno.EAGAIN, errno.EACCES): raise result["acquired"] = False return result finally: os.close(fd) def peer(path, kind, holder_identity): result = subprocess.run( [sys.executable, str(SOURCE), "--probe", str(path), "--kind", kind], check=True, capture_output=True, text=True, timeout=10, close_fds=True, ) row = json.loads(result.stdout) row["sameFileAsHolder"] = row["identity"] == holder_identity return row def run_case(root, kind, close_case): root.mkdir() path = root / "data" path.write_bytes(b"data\n") holder = os.open(path, os.O_RDWR) secondary = None try: if close_case == "duplicate": secondary = os.dup(holder) elif close_case in ("separate-open", "hard-link-open"): other_name = path if close_case == "hard-link-open": other_name = root / "alias" os.link(path, other_name) secondary = os.open(other_name, os.O_RDONLY) else: raise ValueError("Unknown close case") holder_identity = identity(holder) secondary_identity = identity(secondary) lock(holder, kind) before = peer(path, kind, holder_identity) # Closing a different inode is a negative control in the holder process. other = os.open(root / "unrelated", os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o600) other_identity = identity(other) os.close(other) control = peer(path, kind, holder_identity) os.close(secondary) secondary = None after_second = peer(path, kind, holder_identity) holder_valid = identity(holder) == holder_identity contents = os.pread(holder, 5, 0).decode("ascii") finally: if secondary is not None: os.close(secondary) os.close(holder) return { "kind": kind, "closedDescriptor": close_case, "holderIdentity": holder_identity, "secondaryIdentity": secondary_identity, "controlIdentity": other_identity, "beforeClose": before, "afterDifferentFileClose": control, "afterSecondaryClose": after_second, "holderStillOpen": holder_valid, "holderContent": contents, "afterHolderClose": peer(path, kind, holder_identity), } def observe(): if platform.system() != "Linux": raise RuntimeError("This demonstration is scoped to Linux") with tempfile.TemporaryDirectory(prefix="hesela-lock-close-") as temporary: root = Path(temporary) fs_type = subprocess.run( ["stat", "-f", "-c", "%T", str(root)], check=True, capture_output=True, text=True, timeout=10, ).stdout.strip() if fs_type in {"nfs", "nfs4", "cifs", "smb2", "smb3", "9p"}: raise RuntimeError("Use a disposable local filesystem") rows = [run_case(root / (kind + "-" + case), kind, case) for kind in KINDS for case in CLOSE_CASES] return { "schemaVersion": 1, "generatedAt": datetime.now(timezone.utc).isoformat(), "method": "Ordered fresh-process nonblocking probes; one lock API per case", "environment": {"python": platform.python_version(), "kernelRelease": platform.release(), "temporaryFilesystem": fs_type}, "sourceSha256": hashlib.sha256(SOURCE.read_bytes()).hexdigest(), "rows": rows, "limitations": [ "A local Linux API observation, not a crash or SQLite corruption experiment.", "No F_OFD_* operation, network lock, mixed-API contention or thread race tested.", "No writes occur while locks are held; no fsync or power loss is tested.", "Device/inode pairs identify concurrently live files, not durable object IDs.", "The filesystem label is not a full mount configuration.", ], } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, help="Create a new JSON file; never overwrite") parser.add_argument("--probe", type=Path, help=argparse.SUPPRESS) parser.add_argument("--kind", choices=KINDS, help=argparse.SUPPRESS) args = parser.parse_args() if args.probe: if args.kind is None: parser.error("--probe requires --kind") print(json.dumps(probe(args.probe, args.kind))) return payload = json.dumps(observe(), indent=2) + "\n" if args.output: with args.output.open("x", encoding="utf-8") as output: output.write(payload) else: print(payload, end="") if __name__ == "__main__": main()