File size: 4,555 Bytes
966b234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
"""History polling keeps one current projection and streams large file reads."""

import hashlib
import json
import os
from pathlib import Path

import pytest

from bench_builder import builder_progress as progress


def _row(number: int) -> bytes:
    return json.dumps({"snapshot_id": f"s{number:06d}", "summary": "中文😀"}, ensure_ascii=False).encode()


@pytest.fixture(autouse=True)
def clear_history_cache():
    progress._HISTORY_CACHE.clear()
    yield
    progress._HISTORY_CACHE.clear()


@pytest.mark.parametrize("suffix", [b"", _row(2), _row(2) + b"\r", _row(2) + b"\r" + _row(3) + b"\n"])
@pytest.mark.parametrize("ending", [b"\n", b"\r\n"])
def test_history_keeps_exact_committed_prefix(tmp_path: Path, suffix: bytes, ending: bytes) -> None:
    path = tmp_path / "history.jsonl"
    first = _row(1) + ending
    path.write_bytes(first + suffix)
    rows, valid_end = progress._read_history(str(path))
    assert rows == [json.loads(_row(1))]
    assert valid_end == len(first)


@pytest.mark.parametrize("invalid", [b"not-json\n", b"[]\n", _row(3) + b"\n", b'"\xff"\n'])
def test_history_still_rejects_invalid_committed_records(tmp_path: Path, invalid: bytes) -> None:
    path = tmp_path / "history.jsonl"
    path.write_bytes(_row(1) + b"\n" + invalid)
    with pytest.raises(progress.BuilderProgressError, match="invalid committed record"):
        progress._read_history(str(path))
    assert str(path) not in progress._HISTORY_CACHE


def test_append_replaces_cached_version_without_mutating_prior_result(tmp_path: Path, monkeypatch) -> None:
    path = tmp_path / "history.jsonl"
    path.write_bytes(_row(1) + b"\n")
    first = progress._read_history(str(path))
    loads = progress.json.loads
    calls = []

    def tracked_loads(value):
        calls.append(value)
        return loads(value)

    monkeypatch.setattr(progress.json, "loads", tracked_loads)
    assert progress._read_history(str(path)) is first
    assert calls == []
    for number in range(2, 20):
        with path.open("ab") as stream:
            stream.write(_row(number) + b"\n")
        current = progress._read_history(str(path))
        assert len(current[0]) == number
        assert len(progress._HISTORY_CACHE) == 1
    assert len(first[0]) == 1


def test_replaced_file_with_same_size_and_mtime_is_reloaded(tmp_path: Path) -> None:
    path = tmp_path / "history.jsonl"
    path.write_bytes(b'{"snapshot_id":"s000001","value":"old"}\n')
    first = progress._read_history(str(path))
    original = path.stat()
    replacement = tmp_path / "replacement"
    replacement.write_bytes(b'{"snapshot_id":"s000001","value":"new"}\n')
    os.utime(replacement, ns=(original.st_atime_ns, original.st_mtime_ns))
    replacement.replace(path)
    assert progress._read_history(str(path))[0][0]["value"] == "new"
    assert first[0][0]["value"] == "old"


def test_history_cache_bounds_distinct_files(tmp_path: Path) -> None:
    for number in range(20):
        path = tmp_path / str(number)
        path.write_bytes(_row(1) + b"\n")
        progress._read_history(str(path))
    assert len(progress._HISTORY_CACHE) == 16
    assert str(tmp_path / "0") not in progress._HISTORY_CACHE


def test_history_changed_during_read_is_not_cached(tmp_path: Path, monkeypatch) -> None:
    path = tmp_path / "history.jsonl"
    path.write_bytes(_row(1) + b"\n")
    loads = progress.json.loads
    appended = False

    def append_during_parse(value):
        nonlocal appended
        if not appended:
            appended = True
            with path.open("ab") as stream:
                stream.write(_row(2) + b"\n")
        return loads(value)

    monkeypatch.setattr(progress.json, "loads", append_during_parse)
    progress._read_history(str(path))
    assert str(path) not in progress._HISTORY_CACHE
    assert len(progress._read_history(str(path))[0]) == 2


def test_progress_hash_and_history_do_not_materialize_whole_files(tmp_path: Path, monkeypatch) -> None:
    binary = tmp_path / "asset.bin"
    binary.write_bytes(bytes(range(256)) * 20_000)
    expected = hashlib.sha256(binary.read_bytes()).hexdigest()
    history = tmp_path / "history.jsonl"
    history.write_bytes(_row(1) + b"\n")

    def no_read_bytes(*args):
        raise AssertionError("Progress must stream file reads")

    monkeypatch.setattr(Path, "read_bytes", no_read_bytes)
    stat = binary.stat()
    assert progress._file_hash(str(binary), stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns) == expected
    assert progress._read_history(str(history))[0] == [json.loads(_row(1))]