Skip to content

Commit 7466230

Browse files
hhyykkhuangruiteng
authored andcommitted
perf(runtime): capture source type and revision in one metadata read
Signed-off-by: aihop <4408344+hhyykk@users.noreply.github.com>
1 parent 3c63bf8 commit 7466230

3 files changed

Lines changed: 92 additions & 36 deletions

File tree

‎loopx/control_plane/effect_runtime.py‎

Lines changed: 22 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import os
66
import secrets
77
import socket
8+
import stat
89
import subprocess
910
import sys
1011
import tempfile
@@ -280,42 +281,38 @@ def _control_plane_root() -> Path:
280281
return Path(__file__).resolve().parent
281282

282283

283-
def _scan_runtime_source_files(root: Path) -> tuple[str, ...]:
284-
files: list[str] = []
284+
def _scan_runtime_source_snapshot(root: Path) -> _RuntimeSourceSnapshot:
285+
snapshot: list[tuple[str, int, int, int]] = []
285286
for directory, child_directories, filenames in os.walk(root):
286287
child_directories.sort()
287288
relative_directory = os.path.relpath(directory, root)
288289
if relative_directory == ".":
289290
relative_directory = ""
290-
files.extend(
291-
Path(relative_directory, filename).as_posix()
292-
for filename in sorted(filenames)
293-
if Path(filename).suffix in _RUNTIME_SOURCE_SUFFIXES
294-
and Path(directory, filename).is_file()
295-
)
296-
return tuple(sorted(files))
297-
298-
299-
def _runtime_file_snapshot(
300-
root: Path,
301-
files: tuple[str, ...],
302-
) -> _RuntimeSourceSnapshot:
303-
return tuple(
304-
(
305-
relative,
306-
(metadata := (root / relative).stat()).st_mtime_ns,
307-
metadata.st_ctime_ns,
308-
metadata.st_size,
309-
)
310-
for relative in files
311-
)
291+
for filename in sorted(filenames):
292+
dot = filename.rfind(".")
293+
if dot <= 0 or filename[dot:] not in _RUNTIME_SOURCE_SUFFIXES:
294+
continue
295+
source = Path(directory, filename)
296+
try:
297+
metadata = source.stat()
298+
except OSError:
299+
# Preserve pathlib's missing-file and platform-specific error policy.
300+
if not source.is_file():
301+
continue
302+
raise
303+
except ValueError:
304+
continue
305+
if stat.S_ISREG(metadata.st_mode):
306+
snapshot.append((Path(relative_directory, filename).as_posix(),
307+
metadata.st_mtime_ns, metadata.st_ctime_ns, metadata.st_size))
308+
return tuple(sorted(snapshot))
312309

313310

314311
def _runtime_source_snapshot(root: Path | None = None) -> _RuntimeSourceSnapshot:
315312
"""Return cheap metadata that invalidates the packaged-source hash."""
316313

317314
source_root = (root or _control_plane_root()).resolve()
318-
return _runtime_file_snapshot(source_root, _scan_runtime_source_files(source_root))
315+
return _scan_runtime_source_snapshot(source_root)
319316

320317

321318
def _runtime_source_files(root: Path | None = None) -> tuple[str, ...]:

‎tests/control_plane/test_status_rollout_event_snapshot.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -372,16 +372,16 @@ def test_collect_status_scans_effect_runtime_sources_once_per_request(
372372
monkeypatch: pytest.MonkeyPatch,
373373
) -> None:
374374
registry_path, runtime_root, _goal = _write_fixture(tmp_path)
375-
original_scan = effect_runtime._scan_runtime_source_files
375+
original_scan = effect_runtime._scan_runtime_source_snapshot
376376
scanned_roots: list[Path] = []
377377

378-
def counted_scan(root: Path) -> tuple[str, ...]:
378+
def counted_scan(root: Path) -> effect_runtime._RuntimeSourceSnapshot:
379379
scanned_roots.append(root)
380380
return original_scan(root)
381381

382382
monkeypatch.setattr(
383383
effect_runtime,
384-
"_scan_runtime_source_files",
384+
"_scan_runtime_source_snapshot",
385385
counted_scan,
386386
)
387387

‎tests/control_plane/test_turn_journal_runtime_readiness.py‎

Lines changed: 67 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22

3+
import os
34
from pathlib import Path
45
from threading import Event
56
from typing import Any
@@ -17,6 +18,64 @@ def __init__(self, *, stdout: str, returncode: int = 0) -> None:
1718
self.returncode = returncode
1819

1920

21+
def test_source_snapshot_observes_each_selected_file_metadata_once(tmp_path, monkeypatch):
22+
names = ["first.ts", "nested/data.json", "....json", "folder.ts/child.ts"]
23+
for name in [*names, ".json", ".ts", "ignored.py", "UPPER.TS"]:
24+
path = tmp_path / name
25+
path.parent.mkdir(parents=True, exist_ok=True)
26+
path.write_text("{}", encoding="utf-8")
27+
for name in names:
28+
os.utime(tmp_path / name, ns=(1_000_000_000, 1_000_000_000))
29+
selected = {tmp_path / name for name in names}
30+
expected = []
31+
for name in sorted(names):
32+
metadata = (tmp_path / name).stat()
33+
expected.append((name, metadata.st_mtime_ns, metadata.st_ctime_ns, metadata.st_size))
34+
observed: list[Path] = []
35+
original_stat = Path.stat
36+
37+
def observe_stat(path, *args, **kwargs):
38+
if path in selected:
39+
observed.append(path)
40+
return original_stat(path, *args, **kwargs)
41+
42+
monkeypatch.setattr(Path, "stat", observe_stat)
43+
assert effect_runtime._runtime_source_snapshot(tmp_path) == tuple(expected)
44+
assert sorted(observed) == sorted(selected)
45+
46+
47+
@pytest.mark.skipif(os.name == "nt", reason="requires filesystem symlinks")
48+
def test_source_snapshot_follows_file_links_and_ignores_directory_or_broken_links(tmp_path):
49+
root = tmp_path / "package"
50+
root.mkdir()
51+
outside = tmp_path / "outside"
52+
outside.mkdir()
53+
target = outside / "actual.ts"
54+
target.write_text("export {};", encoding="utf-8")
55+
(root / "alias.ts").symlink_to(target)
56+
(root / "directory").symlink_to(outside, target_is_directory=True)
57+
(root / "missing.ts").symlink_to(outside / "missing.ts")
58+
(root / "loop.ts").symlink_to(root / "loop.ts")
59+
metadata = target.stat()
60+
assert effect_runtime._runtime_source_snapshot(root) == (
61+
("alias.ts", metadata.st_mtime_ns, metadata.st_ctime_ns, metadata.st_size),
62+
)
63+
64+
65+
def test_source_snapshot_keeps_pathlib_policy_for_nonencodable_entries(tmp_path, monkeypatch):
66+
source = tmp_path / "source.ts"
67+
source.write_text("export {};", encoding="utf-8")
68+
original_stat = Path.stat
69+
70+
def nonencodable_stat(path, *args, **kwargs):
71+
if path == source:
72+
raise ValueError("non-encodable path")
73+
return original_stat(path, *args, **kwargs)
74+
75+
monkeypatch.setattr(Path, "stat", nonencodable_stat)
76+
assert effect_runtime._runtime_source_snapshot(tmp_path) == ()
77+
78+
2079
def test_runtime_fingerprint_rotates_when_any_owned_source_changes(
2180
tmp_path: Path,
2281
monkeypatch: pytest.MonkeyPatch,
@@ -91,17 +150,17 @@ def test_runtime_fingerprint_rescans_when_a_discovered_file_disappears(
91150
removed = tmp_path / "removed.ts"
92151
kept.write_text("export const kept = true;\n", encoding="utf-8")
93152
removed.write_text("export const removed = true;\n", encoding="utf-8")
94-
original_scan = effect_runtime._scan_runtime_source_files
153+
original_scan = effect_runtime._scan_runtime_source_snapshot
95154
scans: list[tuple[str, ...]] = []
96155

97-
def scan_then_remove(root: Path) -> tuple[str, ...]:
156+
def scan_then_remove(root: Path) -> effect_runtime._RuntimeSourceSnapshot:
98157
files = original_scan(root)
99-
scans.append(files)
158+
scans.append(tuple(row[0] for row in files))
100159
if len(scans) == 1:
101160
removed.unlink()
102161
return files
103162

104-
monkeypatch.setattr(effect_runtime, "_scan_runtime_source_files", scan_then_remove)
163+
monkeypatch.setattr(effect_runtime, "_scan_runtime_source_snapshot", scan_then_remove)
105164

106165
monkeypatch.setattr(effect_runtime, "_control_plane_root", lambda: tmp_path)
107166

@@ -152,15 +211,15 @@ def _install_persistent_stat_read_churn(
152211
later = tmp_path / "later.ts"
153212
first.write_text("export const first = true;\n", encoding="utf-8")
154213
later.write_text("export const later = true;\n", encoding="utf-8")
155-
original_scan = effect_runtime._scan_runtime_source_files
214+
original_scan = effect_runtime._scan_runtime_source_snapshot
156215
original_read_bytes = Path.read_bytes
157216
scans: list[tuple[str, ...]] = []
158217
first_read = Event()
159218
later_reads = 0
160219

161-
def record_scan(root: Path) -> tuple[str, ...]:
220+
def record_scan(root: Path) -> effect_runtime._RuntimeSourceSnapshot:
162221
files = original_scan(root)
163-
scans.append(files)
222+
scans.append(tuple(row[0] for row in files))
164223
return files
165224

166225
def churn_after_each_later_read(path: Path) -> bytes:
@@ -178,7 +237,7 @@ def churn_after_each_later_read(path: Path) -> bytes:
178237
return content
179238

180239
monkeypatch.setattr(effect_runtime, "_control_plane_root", lambda: tmp_path)
181-
monkeypatch.setattr(effect_runtime, "_scan_runtime_source_files", record_scan)
240+
monkeypatch.setattr(effect_runtime, "_scan_runtime_source_snapshot", record_scan)
182241
monkeypatch.setattr(Path, "read_bytes", churn_after_each_later_read)
183242
return scans
184243

0 commit comments

Comments
 (0)