mirror of
https://github.com/rcourtman/Pulse.git
synced 2026-12-03 18:43:38 +01:00
Batch exact browser receipt content reads
Reduce Git process startup per verified frontend file while retaining byte-exact hashes, missing-file semantics, index freshness and malformed-batch fallback. Contract-Neutral: Validation content-read batching only; browser evidence requirements, receipt binding and admission rules are unchanged. Change-source: pulse-maintainer
This commit is contained in:
@@ -60,6 +60,57 @@ def git_blob_bytes(object_name: str, *, repo_root: Path = REPO_ROOT) -> bytes |
|
||||
return result.stdout if result.returncode == 0 else None
|
||||
|
||||
|
||||
def git_blob_bytes_many(
|
||||
object_names: Sequence[str], *, repo_root: Path = REPO_ROOT
|
||||
) -> list[bytes | None]:
|
||||
"""Read exact blobs with bounded Git batches, retaining show semantics.
|
||||
|
||||
Batch input is line-delimited, but blob output is size-delimited: source
|
||||
can contain arbitrary bytes, including apparent headers. Unusual object
|
||||
names and non-blob objects retain the individual reader. No results are
|
||||
cached across calls (in particular, the staged index can change).
|
||||
"""
|
||||
contents: list[bytes | None] = []
|
||||
for start in range(0, len(object_names), 32):
|
||||
chunk = object_names[start : start + 32]
|
||||
if any("\n" in name or "\r" in name for name in chunk):
|
||||
contents.extend(git_blob_bytes(name, repo_root=repo_root) for name in chunk)
|
||||
continue
|
||||
result = subprocess.run(
|
||||
["git", "cat-file", "--batch"], cwd=repo_root, check=False,
|
||||
capture_output=True, input=("\n".join(chunk) + "\n").encode("utf-8"),
|
||||
)
|
||||
offset = 0
|
||||
batch: list[bytes | None] = []
|
||||
try:
|
||||
if result.returncode:
|
||||
raise ValueError("batch read failed")
|
||||
for name in chunk:
|
||||
end = result.stdout.index(b"\n", offset)
|
||||
header = result.stdout[offset:end]
|
||||
offset = end + 1
|
||||
if header == name.encode("utf-8") + b" missing":
|
||||
batch.append(None)
|
||||
continue
|
||||
fields = header.split()
|
||||
if len(fields) != 3 or not re.fullmatch(b"[0-9a-f]{40}|[0-9a-f]{64}", fields[0]):
|
||||
raise ValueError("invalid batch header")
|
||||
size = int(fields[2])
|
||||
if size < 0 or result.stdout[offset + size : offset + size + 1] != b"\n":
|
||||
raise ValueError("incomplete batch content")
|
||||
content = result.stdout[offset : offset + size]
|
||||
offset += size + 1
|
||||
batch.append(content if fields[1] == b"blob" else git_blob_bytes(name, repo_root=repo_root))
|
||||
if offset != len(result.stdout):
|
||||
raise ValueError("unexpected batch content")
|
||||
except ValueError:
|
||||
# A partial/unsupported batch must never shift a later file's
|
||||
# bytes onto the wrong path. Discard it and use the old reader.
|
||||
batch = [git_blob_bytes(name, repo_root=repo_root) for name in chunk]
|
||||
contents.extend(batch)
|
||||
return contents
|
||||
|
||||
|
||||
def staged_files(*, repo_root: Path = REPO_ROOT) -> list[str]:
|
||||
output = run_git(
|
||||
["diff", "--cached", "--name-only", "--diff-filter=ACMRD"],
|
||||
@@ -200,9 +251,8 @@ def content_sha256(
|
||||
repo_root: Path = REPO_ROOT,
|
||||
) -> dict[str, str]:
|
||||
digests: dict[str, str] = {}
|
||||
for path in paths:
|
||||
object_name = f"{commit}:{path}" if commit else f":{path}"
|
||||
content = git_blob_bytes(object_name, repo_root=repo_root)
|
||||
object_names = [f"{commit}:{path}" if commit else f":{path}" for path in paths]
|
||||
for path, content in zip(paths, git_blob_bytes_many(object_names, repo_root=repo_root)):
|
||||
digests[path] = "deleted" if content is None else hashlib.sha256(content).hexdigest()
|
||||
return digests
|
||||
|
||||
|
||||
@@ -16,8 +16,11 @@ from unittest.mock import patch
|
||||
from browser_verification_guard import (
|
||||
LEGACY_RECEIPT_PATH,
|
||||
RECEIPT_DIR,
|
||||
content_sha256,
|
||||
formatting_only_paths,
|
||||
frontend_runtime_paths,
|
||||
git_blob_bytes,
|
||||
git_blob_bytes_many,
|
||||
is_receipt_path,
|
||||
main,
|
||||
receipt_path_for,
|
||||
@@ -352,6 +355,75 @@ class GuardRepoTestCase(unittest.TestCase):
|
||||
return [line for line in listing.splitlines() if line]
|
||||
|
||||
|
||||
class BatchBlobReadTest(GuardRepoTestCase):
|
||||
def read_many(self, names: list[str]) -> list[bytes | None]:
|
||||
with patch.dict("os.environ", self.env, clear=True):
|
||||
return git_blob_bytes_many(names, repo_root=self.repo_root)
|
||||
|
||||
def test_batches_exact_bytes_and_missing_files_without_one_process_per_path(self) -> None:
|
||||
paths = [f"frontend-modern/src/file {number}.tsx" for number in range(65)]
|
||||
for number, path in enumerate(paths):
|
||||
target = self.repo_root / path
|
||||
target.write_bytes(b"\x00\xff\n" + b"a" * 40 + b" blob 3\n" + str(number).encode())
|
||||
self.git("add", "-A")
|
||||
names = [f":{path}" for path in paths] + [":missing", f"{self.base}:{CHANGED_PATH}"]
|
||||
with patch.dict("os.environ", self.env, clear=True):
|
||||
expected = [git_blob_bytes(name, repo_root=self.repo_root) for name in names]
|
||||
with patch("browser_verification_guard.subprocess.run", wraps=subprocess.run) as calls:
|
||||
self.assertEqual(git_blob_bytes_many(names, repo_root=self.repo_root), expected)
|
||||
self.assertEqual(calls.call_count, 3)
|
||||
self.assertTrue(all(call.args[0] == ["git", "cat-file", "--batch"] for call in calls.call_args_list))
|
||||
|
||||
def test_unusual_names_empty_blobs_and_tree_objects_retain_show_semantics(self) -> None:
|
||||
paths = ["frontend-modern/src/empty.ts", "frontend-modern/src/with\nnewline.ts",
|
||||
"frontend-modern/src/with\rcarriage.ts", "frontend-modern/src/tab\t雪.ts"]
|
||||
for path in paths:
|
||||
self.write(path, "")
|
||||
revision = self.commit("unusual filenames")
|
||||
names = [f"{revision}:{path}" for path in paths] + [f"{revision}:frontend-modern/src"]
|
||||
with patch.dict("os.environ", self.env, clear=True):
|
||||
expected = [git_blob_bytes(name, repo_root=self.repo_root) for name in names]
|
||||
self.assertEqual(self.read_many(names), expected)
|
||||
# Also exercise the non-blob batch response without a newline fallback.
|
||||
self.assertEqual(self.read_many([names[-1]]), expected[-1:])
|
||||
|
||||
def test_staged_digest_changes_are_not_cached_and_missing_remains_deleted(self) -> None:
|
||||
paths = [CHANGED_PATH, "missing"]
|
||||
with patch.dict("os.environ", self.env, clear=True):
|
||||
before = content_sha256(paths, commit=None, repo_root=self.repo_root)
|
||||
self.write(CHANGED_PATH, "changed")
|
||||
self.git("add", CHANGED_PATH)
|
||||
after = content_sha256(paths, commit=None, repo_root=self.repo_root)
|
||||
committed = content_sha256(paths, commit=self.base, repo_root=self.repo_root)
|
||||
self.assertEqual(before, committed)
|
||||
self.assertNotEqual(before[CHANGED_PATH], after[CHANGED_PATH])
|
||||
self.assertEqual(after[CHANGED_PATH], hashlib.sha256(b"changed").hexdigest())
|
||||
self.assertEqual(before["missing"], "deleted")
|
||||
self.assertEqual(after["missing"], "deleted")
|
||||
|
||||
def test_partial_or_failed_batch_is_discarded_not_misattributed(self) -> None:
|
||||
names = [f"{self.base}:{CHANGED_PATH}", f"{self.base}:{OTHER_PATH}"]
|
||||
original_run = subprocess.run
|
||||
with patch.dict("os.environ", self.env, clear=True):
|
||||
expected = [git_blob_bytes(name, repo_root=self.repo_root) for name in names]
|
||||
for code, output in [(1, b""), (0, b"bad\n"),
|
||||
(0, b"a" * 40 + b" blob 100\nshort\n"),
|
||||
(0, b"a" * 40 + b" blob -1\n"),
|
||||
(0, b"a" * 40 + b" blob 0\n\nextra\n")]:
|
||||
with self.subTest(code=code, output=output):
|
||||
def run(command, **kwargs):
|
||||
if command == ["git", "cat-file", "--batch"]:
|
||||
return subprocess.CompletedProcess(command, code, output, b"")
|
||||
return original_run(command, **kwargs)
|
||||
with patch("browser_verification_guard.subprocess.run", side_effect=run):
|
||||
self.assertEqual(self.read_many(names), expected)
|
||||
|
||||
def test_empty_request_starts_no_git_process(self) -> None:
|
||||
with patch("browser_verification_guard.subprocess.run") as calls:
|
||||
self.assertEqual(self.read_many([]), [])
|
||||
calls.assert_not_called()
|
||||
|
||||
|
||||
class StagedIndexTest(GuardRepoTestCase):
|
||||
"""The pre-commit form: one commit owes exactly one receipt of its own."""
|
||||
|
||||
|
||||
Reference in New Issue
Block a user