|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
| 3 | +import io |
3 | 4 | import json |
4 | 5 | import os |
5 | 6 | from pathlib import Path |
@@ -60,30 +61,164 @@ def test_limited_rollout_event_load_keeps_only_a_bounded_window( |
60 | 61 | tmp_path: Path, |
61 | 62 | monkeypatch, |
62 | 63 | ) -> None: |
63 | | - class TrackedEvent(dict[str, int]): |
| 64 | + class TrackedEvent(dict[str, object]): |
64 | 65 | alive = 0 |
65 | 66 | peak = 0 |
66 | 67 |
|
67 | | - def __init__(self, index: int) -> None: |
68 | | - super().__init__(index=index) |
| 68 | + def __init__(self, value: dict[str, object]) -> None: |
| 69 | + super().__init__(value) |
69 | 70 | type(self).alive += 1 |
70 | 71 | type(self).peak = max(type(self).peak, type(self).alive) |
71 | 72 |
|
72 | 73 | def __del__(self) -> None: |
73 | 74 | type(self).alive -= 1 |
74 | 75 |
|
75 | | - monkeypatch.setattr( |
76 | | - rollout_event_log, |
77 | | - "iter_rollout_events", |
78 | | - lambda _path: (TrackedEvent(index) for index in range(100)), |
79 | | - ) |
| 76 | + log = tmp_path / "events.jsonl" |
| 77 | + log.write_text("".join(json.dumps({ |
| 78 | + "schema_version": rollout_event_log.ROLLOUT_EVENT_SCHEMA_VERSION, |
| 79 | + "index": index, |
| 80 | + }) + "\n" for index in range(100)), encoding="utf-8") |
| 81 | + original_loads = json.loads |
| 82 | + |
| 83 | + def tracked_loads(value): |
| 84 | + return TrackedEvent(original_loads(value)) |
| 85 | + |
| 86 | + monkeypatch.setattr(rollout_event_log.json, "loads", tracked_loads) |
80 | 87 |
|
81 | | - events = rollout_event_log.load_rollout_events(tmp_path / "unused", limit=3) |
| 88 | + events = rollout_event_log.load_rollout_events(log, limit=3) |
82 | 89 |
|
83 | 90 | assert [event["index"] for event in events] == [97, 98, 99] |
84 | 91 | assert TrackedEvent.peak <= 4 |
85 | 92 |
|
86 | 93 |
|
| 94 | +def test_recent_rollout_read_does_not_scan_unneeded_history( |
| 95 | + tmp_path: Path, monkeypatch, |
| 96 | +) -> None: |
| 97 | + log = tmp_path / "events.jsonl" |
| 98 | + records = [{"schema_version": rollout_event_log.ROLLOUT_EVENT_SCHEMA_VERSION, |
| 99 | + "index": index, "summary": "retained history " * 32} |
| 100 | + for index in range(3000)] |
| 101 | + log.write_text("".join(json.dumps(row) + "\n" for row in records), encoding="utf-8") |
| 102 | + original_open = Path.open |
| 103 | + observed = {"bytes": 0} |
| 104 | + |
| 105 | + class CountedRead: |
| 106 | + def __init__(self, handle): |
| 107 | + self.handle = handle |
| 108 | + |
| 109 | + def __enter__(self): |
| 110 | + return self |
| 111 | + |
| 112 | + def __exit__(self, *args): |
| 113 | + return self.handle.__exit__(*args) |
| 114 | + |
| 115 | + def __getattr__(self, name): |
| 116 | + return getattr(self.handle, name) |
| 117 | + |
| 118 | + def __iter__(self): |
| 119 | + for line in self.handle: |
| 120 | + observed["bytes"] += len(line) |
| 121 | + yield line |
| 122 | + |
| 123 | + def read(self, size=-1): |
| 124 | + value = self.handle.read(size) |
| 125 | + observed["bytes"] += len(value) |
| 126 | + return value |
| 127 | + |
| 128 | + def counted_open(path, mode="r", *args, **kwargs): |
| 129 | + handle = original_open(path, mode, *args, **kwargs) |
| 130 | + return CountedRead(handle) if path == log and mode == "rb" else handle |
| 131 | + |
| 132 | + monkeypatch.setattr(Path, "open", counted_open) |
| 133 | + |
| 134 | + assert load_rollout_events(log, limit=3) == records[-3:] |
| 135 | + assert observed["bytes"] < log.stat().st_size // 4 |
| 136 | + |
| 137 | + |
| 138 | +@pytest.mark.parametrize("limit", [1, 2, 7, 100]) |
| 139 | +@pytest.mark.parametrize("final_newline", [False, True]) |
| 140 | +def test_recent_rollout_read_counts_valid_records_and_preserves_complete_rows( |
| 141 | + tmp_path: Path, limit: int, final_newline: bool, |
| 142 | +) -> None: |
| 143 | + log = tmp_path / "events.jsonl" |
| 144 | + records = [{"schema_version": rollout_event_log.ROLLOUT_EVENT_SCHEMA_VERSION, |
| 145 | + "index": index, "summary": "雪🙂" * (25000 if index == 4 else 3)} |
| 146 | + for index in range(8)] |
| 147 | + invalid = b'\xff\n{"torn":\n[]\nnull\n{"schema_version":"other"}\n\n' |
| 148 | + contents = b"".join(json.dumps(row, ensure_ascii=False).encode("utf-8") |
| 149 | + + b"\n" + invalid for row in records[:-1]) |
| 150 | + contents += json.dumps(records[-1], ensure_ascii=False).encode("utf-8") |
| 151 | + contents += b"\n" if final_newline else b"" |
| 152 | + log.write_bytes(contents) |
| 153 | + |
| 154 | + assert load_rollout_events(log, limit=limit) == records[-limit:] |
| 155 | + assert log.read_bytes() == contents |
| 156 | + |
| 157 | + |
| 158 | +@pytest.mark.parametrize("limit", [None, 0, -1]) |
| 159 | +def test_unlimited_rollout_read_retains_its_complete_history( |
| 160 | + tmp_path: Path, limit: int | None, |
| 161 | +) -> None: |
| 162 | + log = tmp_path / "events.jsonl" |
| 163 | + records = [{"schema_version": rollout_event_log.ROLLOUT_EVENT_SCHEMA_VERSION, |
| 164 | + "index": index} for index in range(5)] |
| 165 | + log.write_text("\n".join(json.dumps(row) for row in records), encoding="utf-8") |
| 166 | + assert load_rollout_events(log, limit=limit) == records |
| 167 | + |
| 168 | + |
| 169 | +def test_recent_rollout_read_reopens_the_current_file(tmp_path: Path) -> None: |
| 170 | + log = tmp_path / "events.jsonl" |
| 171 | + records = [{"schema_version": rollout_event_log.ROLLOUT_EVENT_SCHEMA_VERSION, |
| 172 | + "index": index} for index in range(3)] |
| 173 | + log.write_text(json.dumps(records[0]) + "\n", encoding="utf-8") |
| 174 | + assert load_rollout_events(log, limit=2) == records[:1] |
| 175 | + with log.open("a", encoding="utf-8") as handle: |
| 176 | + handle.write("\n".join(json.dumps(row) for row in records[1:])) |
| 177 | + assert load_rollout_events(log, limit=2) == records[1:] |
| 178 | + |
| 179 | + |
| 180 | +def test_recent_rollout_read_preserves_nonseekable_input( |
| 181 | + tmp_path: Path, monkeypatch, |
| 182 | +) -> None: |
| 183 | + log = tmp_path / "events.jsonl" |
| 184 | + records = [{"schema_version": rollout_event_log.ROLLOUT_EVENT_SCHEMA_VERSION, |
| 185 | + "index": index} for index in range(4)] |
| 186 | + contents = "\n".join(json.dumps(row) for row in records).encode() |
| 187 | + original_open = Path.open |
| 188 | + |
| 189 | + class NonseekableRead(io.BytesIO): |
| 190 | + def seekable(self): |
| 191 | + return False |
| 192 | + |
| 193 | + def seek(self, *args): |
| 194 | + raise io.UnsupportedOperation("not seekable") |
| 195 | + |
| 196 | + def opened(path, mode="r", *args, **kwargs): |
| 197 | + return NonseekableRead(contents) if path == log else original_open(path, mode, *args, **kwargs) |
| 198 | + |
| 199 | + monkeypatch.setattr(Path, "open", opened) |
| 200 | + assert load_rollout_events(log, limit=2) == records[-2:] |
| 201 | + |
| 202 | + |
| 203 | +@pytest.mark.parametrize("limit", [None, 1]) |
| 204 | +def test_rollout_read_keeps_missing_file_behavior(tmp_path: Path, limit: int | None) -> None: |
| 205 | + assert load_rollout_events(tmp_path / "missing.jsonl", limit=limit) == [] |
| 206 | + |
| 207 | + |
| 208 | +@pytest.mark.parametrize("row,message", [ |
| 209 | + ("{", "must contain valid JSON"), |
| 210 | + ("[]", "must contain an object"), |
| 211 | + ('{"schema_version":"other"}', "must use loopx_rollout_event_v0"), |
| 212 | +]) |
| 213 | +def test_strict_rollout_read_still_reports_the_original_line( |
| 214 | + tmp_path: Path, row: str, message: str, |
| 215 | +) -> None: |
| 216 | + log = tmp_path / "events.jsonl" |
| 217 | + log.write_text("\n" + row + "\n", encoding="utf-8") |
| 218 | + with pytest.raises(ValueError, match="rollout event log line 2 " + message): |
| 219 | + list(iter_rollout_events(log, strict=True)) |
| 220 | + |
| 221 | + |
87 | 222 | @pytest.mark.parametrize("idempotent", [False, True]) |
88 | 223 | @pytest.mark.parametrize( |
89 | 224 | "torn_record", |
|
0 commit comments