Gzip loop-claude's archive and the review folders 30 days after each file was last written, and read gzipped files by their plain name
CI / tests (pull_request) Failing after 2m59s

This commit is contained in:
2026-11-17 02:00:32 +01:00
parent 7b0e4d013e
commit b9876c17fe
23 changed files with 467 additions and 18 deletions
+62
View File
@@ -0,0 +1,62 @@
"""A file kept plain, or gzipped beside its plain name as <name>.gz: reading it by its plain name, and compressing it.
Why gzip and when a file is compressed: docs/decisions.md → `archives: loop-claude's archive and the review folders keep every file, and gzip each one 30 days after it was last written`.
"""
import errno
import gzip
import os
import pathlib
import zlib
from failure import Failure
from text_files.file_writes import replace_file
SUFFIX = ".gz"
def stored(path: pathlib.Path) -> pathlib.Path | None:
"""Where the file named path is kept: path itself, else its gzip; None where neither is."""
# A plain file beside its gzip was written after it was compressed, so it holds the newer bytes. Whatever else stands at path, such as a folder, is read as path, so the read names it.
return next((kept for kept in (path, gzipped(path)) if kept.exists()), None)
def read_stored(path: pathlib.Path) -> bytes:
"""The bytes of the file named path, read from its gzip where it is kept that way. Raises OSError, FileNotFoundError where neither is kept."""
kept = stored(path)
if kept is None:
raise FileNotFoundError(2, "No such file or directory", str(path))
if kept == path:
return path.read_bytes()
try:
return gzip.decompress(kept.read_bytes())
except (EOFError, zlib.error) as failure:
raise OSError(errno.EIO, f"not a whole gzip: {failure}", str(kept)) from failure
def stored_glob(folder: pathlib.Path, pattern: str) -> list[pathlib.Path]:
"""The plain name of each file in folder that pattern matches, whether kept plain or gzipped, sorted."""
return sorted({*folder.glob(pattern), *(path.with_name(path.name.removesuffix(SUFFIX)) for path in folder.glob(pattern + SUFFIX))})
def compress(path: pathlib.Path) -> Failure | None:
"""Replaces path with its gzip, which keeps path's times: writes the gzip, reads it back, and removes path only once it reads back path's bytes. A failure keeps path."""
packed = gzipped(path)
try:
before = path.stat()
data = path.read_bytes()
if unwritten := replace_file(packed, gzip.compress(data, mtime=0)):
return Failure(f"could not compress {path}: {unwritten.reason}")
if gzip.decompress(packed.read_bytes()) != data:
return Failure(f"could not compress {path}: {packed} reads back other bytes")
os.utime(packed, ns=(before.st_atime_ns, before.st_mtime_ns))
after = path.stat()
# Written while it compressed: the plain file keeps the newer bytes, which readers prefer, and a later run compresses them.
if (after.st_size, after.st_mtime_ns) == (before.st_size, before.st_mtime_ns):
path.unlink()
except (OSError, EOFError, zlib.error) as failure:
return Failure(f"could not compress {path}: {failure}")
return None
def gzipped(path: pathlib.Path) -> pathlib.Path:
return path.with_name(path.name + SUFFIX)
+87
View File
@@ -0,0 +1,87 @@
import gzip
import os
import pathlib
import sys
import tempfile
import unittest
from unittest import mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from failure import Failure
from text_files import compressed
class Compress(unittest.TestCase):
def test_replaces_the_file_with_a_gzip_of_the_same_bytes_and_times(self):
with tempfile.TemporaryDirectory() as root:
plain = pathlib.Path(root, "t.jsonl")
plain.write_bytes(b'{"a": 1}\n')
os.utime(plain, (1000, 2000))
self.assertIsNone(compressed.compress(plain))
self.assertFalse(plain.exists())
packed = pathlib.Path(root, "t.jsonl.gz")
self.assertEqual(gzip.decompress(packed.read_bytes()), b'{"a": 1}\n')
self.assertEqual(packed.stat().st_mtime, 2000)
def test_a_copy_that_reads_back_other_bytes_keeps_the_original_and_fails(self):
with tempfile.TemporaryDirectory() as root:
plain = pathlib.Path(root, "t.jsonl")
plain.write_bytes(b"kept\n")
with mock.patch.object(compressed.gzip, "compress", return_value=gzip.compress(b"other\n")):
failed = compressed.compress(plain)
self.assertIsInstance(failed, Failure)
self.assertIn(str(plain), failed.reason)
self.assertEqual(plain.read_bytes(), b"kept\n")
def test_a_file_written_while_it_compressed_stays_plain(self):
with tempfile.TemporaryDirectory() as root:
plain = pathlib.Path(root, "t.jsonl")
plain.write_bytes(b"one\n")
packing = compressed.gzip.compress
def grow_meanwhile(data, **kwargs):
with open(plain, "ab") as handle:
handle.write(b"two\n")
return packing(data, **kwargs)
with mock.patch.object(compressed.gzip, "compress", grow_meanwhile):
self.assertIsNone(compressed.compress(plain))
self.assertEqual(plain.read_bytes(), b"one\ntwo\n")
self.assertEqual(compressed.read_stored(plain), b"one\ntwo\n")
class Read(unittest.TestCase):
def test_reads_a_file_kept_plain_or_gzipped_by_its_plain_name(self):
with tempfile.TemporaryDirectory() as root:
plain = pathlib.Path(root, "a.jsonl")
plain.write_bytes(b"a\n")
pathlib.Path(root, "b.jsonl.gz").write_bytes(gzip.compress(b"b\n"))
self.assertEqual(compressed.read_stored(plain), b"a\n")
self.assertEqual(compressed.read_stored(pathlib.Path(root, "b.jsonl")), b"b\n")
self.assertEqual(compressed.stored(pathlib.Path(root, "b.jsonl")), pathlib.Path(root, "b.jsonl.gz"))
self.assertIsNone(compressed.stored(pathlib.Path(root, "c.jsonl")))
with self.assertRaises(FileNotFoundError):
compressed.read_stored(pathlib.Path(root, "c.jsonl"))
def test_the_plain_file_wins_over_an_older_gzip_beside_it(self):
with tempfile.TemporaryDirectory() as root:
pathlib.Path(root, "a.jsonl").write_bytes(b"a\nmore\n")
pathlib.Path(root, "a.jsonl.gz").write_bytes(gzip.compress(b"a\n"))
self.assertEqual(compressed.read_stored(pathlib.Path(root, "a.jsonl")), b"a\nmore\n")
def test_a_truncated_gzip_fails_as_an_os_error(self):
with tempfile.TemporaryDirectory() as root:
pathlib.Path(root, "a.jsonl.gz").write_bytes(gzip.compress(b"a\n" * 100)[:20])
with self.assertRaises(OSError):
compressed.read_stored(pathlib.Path(root, "a.jsonl"))
def test_globs_each_file_once_by_its_plain_name(self):
with tempfile.TemporaryDirectory() as root:
for name in ("a.jsonl", "b.jsonl.gz", "c.jsonl", "c.jsonl.gz", "d.md"):
pathlib.Path(root, name).write_bytes(b"")
self.assertEqual(compressed.stored_glob(pathlib.Path(root), "*.jsonl"), [pathlib.Path(root, name) for name in ("a.jsonl", "b.jsonl", "c.jsonl")])
if __name__ == "__main__":
unittest.main()