Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(examples): sync latency outputs and retain deadline reasons
svonavac4a927498aba
diff --git a/examples/agent-stage-latency/README.md b/examples/agent-stage-latency/README.mdindex a4432bbbc..f8281d29d 100644--- a/examples/agent-stage-latency/README.md+++ b/examples/agent-stage-latency/README.md@@ -82,6 +82,10 @@ directory. The example never replaces inputs, packets, journals or reports.The runner creates `trial-1.jsonl.end.json` beside its journal. Preserve bothfiles: the exclusive terminal record binds the full journal bytes to thepacket, including any partial final line left by a deadline or interrupt.+Files are flushed and synced before their publication directories; newly+created parent directories and download renames are synced too. Directory+syncing applies on POSIX filesystems that support it. Storage and filesystem+behavior still govern survival after power loss.## Pilot and disjoint confirmationdiff --git a/examples/agent-stage-latency/fetch.py b/examples/agent-stage-latency/fetch.pyindex a31baf8e4..eb6ea7257 100644--- a/examples/agent-stage-latency/fetch.py+++ b/examples/agent-stage-latency/fetch.py@@ -3,6 +3,7 @@from __future__ import annotationsimport argparse+import errnoimport jsonimport osimport shutil@@ -13,12 +14,43 @@ from typing import Anyfrom protocol import canonical, digest, require, safe_path, sha256, sources+def fsync_directory(path: Path) -> None:+ """Sync directory entries on POSIX filesystems that support directory fsync."""+ if os.name != "posix":+ return+ descriptor = None+ try:+ descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))+ os.fsync(descriptor)+ except OSError as error:+ if error.errno not in (errno.EINVAL, errno.ENOTSUP, errno.EOPNOTSUPP):+ raise+ finally:+ if descriptor is not None:+ os.close(descriptor)+++def mkdir_synced(path: Path, *, exist_ok: bool = True) -> None:+ """Create missing ancestors and sync each new directory and its parent."""+ if path.parent != path and not path.parent.is_dir():+ mkdir_synced(path.parent)+ try:+ path.mkdir()+ except FileExistsError:+ if not exist_ok or not path.is_dir():+ raise+ else:+ fsync_directory(path)+ fsync_directory(path.parent)++def write_exclusive(path: Path, value: Any) -> None:- path.parent.mkdir(parents=True, exist_ok=True)+ mkdir_synced(path.parent)with path.open("xb") as output:output.write(canonical(value) + b"\n")output.flush()os.fsync(output.fileno())+ fsync_directory(path.parent)def verify_inputs(root: Path, catalog: dict[str, Any] | None = None) -> dict[str, bytes]:@@ -59,11 +91,13 @@ def verify_inputs(root: Path, catalog: dict[str, Any] | None = None) -> dict[strdef fetch_inputs(destination: Path, catalog: dict[str, Any] | None = None) -> None:catalog = sources() if catalog is None else catalog- destination.parent.mkdir(parents=True, exist_ok=True)+ mkdir_synced(destination.parent)destination.mkdir() # exclusive reservation, including empty existing directoriesstaging = destination / ".staging"- staging.mkdir()try:+ fsync_directory(destination)+ fsync_directory(destination.parent)+ mkdir_synced(staging, exist_ok=False)for entry in catalog["files"]:name = safe_path(entry["path"])request = urllib.request.Request(entry["url"], headers={"User-Agent": "sie-examples/agent-stage-latency"})@@ -73,19 +107,28 @@ def fetch_inputs(destination: Path, catalog: dict[str, Any] | None = None) -> Nolen(body) == entry["bytes"] and sha256(body) == entry["sha256"], "Downloaded bytes or digest differ")target = staging / name- target.parent.mkdir(parents=True, exist_ok=True)+ mkdir_synced(target.parent)with target.open("xb") as output:output.write(body)+ output.flush()+ os.fsync(output.fileno())+ fsync_directory(target.parent)write_exclusive(staging / "verified.json", {"source_digest": digest(catalog)})verify_inputs(staging, catalog)for child in staging.iterdir():if child.name != "verified.json":child.rename(destination / child.name)+ fsync_directory(staging)+ fsync_directory(destination)(staging / "verified.json").rename(destination / "verified.json")+ fsync_directory(staging)+ fsync_directory(destination)staging.rmdir()+ fsync_directory(destination)except BaseException:# Only this invocation's exclusively reserved directory is removed.shutil.rmtree(destination)+ fsync_directory(destination.parent)raisediff --git a/examples/agent-stage-latency/run.py b/examples/agent-stage-latency/run.pyindex 401afbcc8..5f6fa755e 100644--- a/examples/agent-stage-latency/run.py+++ b/examples/agent-stage-latency/run.py@@ -18,7 +18,7 @@ from pathlib import Pathfrom typing import Anyfrom urllib.parse import urlsplit-from fetch import write_exclusive+from fetch import fsync_directory, mkdir_synced, write_exclusivefrom prepare import load_packetfrom protocol import (MODELS,@@ -171,8 +171,11 @@ class Journal:self.packet = packetself.credentials = credentialsself.lock = threading.Lock()- path.parent.mkdir(parents=True, exist_ok=True)+ mkdir_synced(path.parent)self.output = path.open("xb" if create else "ab")+ self.output.flush()+ os.fsync(self.output.fileno())+ fsync_directory(path.parent)rows = [] if create else [json.loads(line) for line in path.read_bytes().splitlines()]self.sequence = len(rows)self.previous = rows[-1]["entry_digest"] if rows else None@@ -578,6 +581,8 @@ def child_main(connection: Any) -> None:executor.remaining()executor.operation(obs, arm)connection.send("finished")+ except CallFailure as error:+ connection.send("deadline" if error.code == "WALL_DEADLINE" else "child_failure")except BaseException:connection.send("child_failure")finally:diff --git a/examples/agent-stage-latency/tests/test_example.py b/examples/agent-stage-latency/tests/test_example.pyindex c84cb280f..736466f7d 100644--- a/examples/agent-stage-latency/tests/test_example.py+++ b/examples/agent-stage-latency/tests/test_example.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport contextlibimport jsonimport multiprocessing+import osimport randomimport structimport subprocess@@ -380,6 +381,81 @@ def test_fetch_allowlist_verification_and_exclusive_staging(tmp_path: Path) -> Nassert not (tmp_path / "failed").exists()+def inode(path: Path) -> tuple[int, int]:+ status = path.stat()+ return status.st_dev, status.st_ino+++def record_syncs(monkeypatch: pytest.MonkeyPatch) -> list[tuple[int, int]]:+ synced = []+ original = os.fsync++ def record(descriptor: int) -> None:+ original(descriptor)+ status = os.fstat(descriptor)+ synced.append((status.st_dev, status.st_ino))++ monkeypatch.setattr(os, "fsync", record)+ return synced++[email protected](os.name != "posix", reason="Directory fsync is a POSIX persistence step")[email protected]("journal", [False, True])+def test_output_creation_syncs_file_and_new_parent_entries(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, journal: bool+) -> None:+ synced = record_syncs(monkeypatch)+ path = tmp_path / "new-parent" / "leaf" / "output.jsonl"+ if journal:+ output = run.Journal(path, {}, [], create=True)+ output.close()+ else:+ fetch.write_exclusive(path, {"fixture": True})+ if inode(path.parent) not in synced:+ pytest.skip("This filesystem does not support directory fsync")+ file_sync = synced.index(inode(path))+ assert inode(path.parent) in synced[file_sync + 1 :]+ assert all(inode(parent) in synced for parent in (tmp_path, path.parent.parent, path.parent))+ with pytest.raises(FileExistsError):+ if journal:+ run.Journal(path, {}, [], create=True)+ else:+ fetch.write_exclusive(path, {})++[email protected](os.name != "posix", reason="Directory fsync is a POSIX persistence step")+def test_fetch_syncs_data_and_renames_before_publishing_marker(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ _, catalog = tiny_catalog(tmp_path / "source")+ output = tmp_path / "downloaded"+ synced = record_syncs(monkeypatch)+ rename = Path.rename+ last_data_rename = 0+ published = False++ def checked_rename(path: Path, target: Path) -> Path:+ nonlocal last_data_rename, published+ if path.name == "verified.json":+ if inode(output) not in synced:+ pytest.skip("This filesystem does not support directory fsync")+ for entry in catalog["files"]:+ data = output / entry["path"]+ file_sync = synced.index(inode(data))+ assert inode(data.parent) in synced[file_sync + 1 :]+ assert inode(path) in synced+ assert inode(output) in synced[last_data_rename:]+ assert inode(path.parent) in synced[last_data_rename:]+ published = True+ result = rename(path, target)+ if not published:+ last_data_rename = len(synced)+ return result++ monkeypatch.setattr(Path, "rename", checked_rename)+ fetch.fetch_inputs(output, catalog)+ assert published and len(fetch.verify_inputs(output, catalog)) == 9+ assert synced[-1] == inode(output)++@pytest.mark.parametrize("path", ["../escape", "/absolute", "a/../b", "a\\b", "a//b", "a/./b"])def test_unsafe_paths(path: str) -> None:with pytest.raises(ValueError):@@ -681,6 +757,92 @@ def test_wall_deadline_reaps_child_and_preserves_unresolved_intent(tmp_path: Patassert calls["unresolved"] == 1[email protected]("code,expected", [("WALL_DEADLINE", "deadline"), ("CALL_FAILED", "child_failure")])+def test_child_terminal_signal_wins_before_parent_deadline(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, code: str, expected: str+) -> None:+ path, _ = packet_file(tmp_path, stages=["E"], n=1, arms="sie")+ journal = tmp_path / "child-terminal.jsonl"+ checked = []++ class ExpiredExecutor(run.Executor):+ def __init__(self, packet: Any, journal: Any, settings: dict[str, Any]) -> None:+ self.config = settings | {"deadline": time.monotonic() - 1}++ def discover(self) -> None:+ pass++ def remaining(self) -> float:+ checked.append(code)+ if code == "WALL_DEADLINE":+ return super().remaining()+ raise run.CallFailure(code)++ def close(self) -> None:+ pass++ class Connection:+ peer: Connection++ def __init__(self) -> None:+ self.messages: list[Any] = []+ self.received: list[Any] = []++ def recv(self) -> Any:+ message = self.messages.pop(0)+ self.received.append(message)+ return message++ def poll(self) -> bool:+ return bool(self.messages)++ def send(self, message: Any) -> None:+ self.peer.messages.append(message)++ def close(self) -> None:+ pass++ parent, child = Connection(), Connection()+ parent.peer, child.peer = child, parent++ # Complete the real child function during join, before the parent's live+ # budget expires, so terminal classification is independent of scheduling.+ class InlineProcess:+ pid = 1+ exitcode: int | None = None++ def __init__(self, target: Any, args: tuple[Any, ...]) -> None:+ self.target, self.args = target, args++ def start(self) -> None:+ pass++ def join(self, timeout: float | None = None) -> None:+ assert timeout is not None and timeout > 0+ self.target(*self.args)+ self.exitcode = 0++ def is_alive(self) -> bool:+ return self.exitcode is None++ class Context:+ Process = InlineProcess++ @staticmethod+ def Pipe() -> tuple[Connection, Connection]:+ return parent, child++ monkeypatch.setattr(run, "Executor", ExpiredExecutor)+ monkeypatch.setattr(run.multiprocessing, "get_context", lambda _: Context())+ assert run.run_trial(path, journal, "http://127.0.0.1:8000", {}, execute=True) == expected+ assert checked == [code] and parent.received == [expected]+ ending = json.loads(journal.with_name(journal.name + ".end.json").read_bytes())+ assert ending["reason"] == expected and ending["child_exitcode"] == 0+ assert ending["elapsed_s"] < 15+ report = score.score_trial(path, journal)+ assert not report["complete"] and report["stages"]["E"]["accounting"]["sie"]["unattempted"] == 1++def test_interrupt_preserves_intent_and_reaps_child(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:path, _ = packet_file(tmp_path, stages=["E"], n=1, arms="sie")journal = tmp_path / "interrupt.jsonl"