Skip to content

The agent that grows with you

fix(agent): lock save_trajectory() appends so concurrent processes cannot corrupt the JSONL

shafdevbd70d7387a4b
diff --git a/agent/trajectory.py b/agent/trajectory.py
index 50d004d588e..aa4dacf54f1 100644
--- a/agent/trajectory.py
+++ b/agent/trajectory.py
@@ -2,6 +2,7 @@
import json
import logging
+import os
from datetime import datetime
from typing import Any, Dict, List
@@ -20,14 +21,36 @@ def has_incomplete_scratchpad(content: str) -> bool:
return bool(content) and "<REASONING_SCRATCHPAD>" in content and "</REASONING_SCRATCHPAD>" not in content
+def _lock_append_handle(f, acquire: bool) -> None:
+ """Exclusive whole-file lock on an append handle: ``flock`` on POSIX, a 1-byte
+ ``msvcrt.locking`` range at offset 0 on Windows (append position is restored by the OS)."""
+ if os.name == "nt":
+ import msvcrt
+ f.seek(0)
+ msvcrt.locking(f.fileno(), msvcrt.LK_LOCK if acquire else msvcrt.LK_UNLCK, 1)
+ f.seek(0, os.SEEK_END)
+ else:
+ import fcntl
+ fcntl.flock(f.fileno(), fcntl.LOCK_EX if acquire else fcntl.LOCK_UN)
+
+
def save_trajectory(trajectory: List[Dict[str, Any]], model: str, completed: bool, filename: str = None):
"""Append a ShareGPT-format entry to a JSONL file (default trajectory_samples.jsonl / failed_trajectories.jsonl by ``completed``)."""
if filename is None:
filename = "trajectory_samples.jsonl" if completed else "failed_trajectories.jsonl"
entry = {"conversations": trajectory, "timestamp": datetime.now().isoformat(), "model": model, "completed": completed}
+ line = json.dumps(entry, ensure_ascii=False) + "\n"
try:
with open(filename, "a", encoding="utf-8") as f:
- f.write(json.dumps(entry, ensure_ascii=False) + "\n")
+ # Gateway sessions and batch workers append to the SAME default file; without an
+ # exclusive lock around write+flush, entries larger than one write() interleave and the
+ # JSONL stops parsing (#12684).
+ _lock_append_handle(f, True)
+ try:
+ f.write(line)
+ f.flush()
+ finally:
+ _lock_append_handle(f, False)
logger.info("Trajectory saved to %s", filename)
except Exception as e:
logger.warning("Failed to save trajectory: %s", e)
diff --git a/tests/agent/test_trajectory_file_locking.py b/tests/agent/test_trajectory_file_locking.py
new file mode 100644
index 00000000000..0b397456b3a
--- /dev/null
+++ b/tests/agent/test_trajectory_file_locking.py
@@ -0,0 +1,61 @@
+"""``save_trajectory()`` appends must be serialized across processes (#12684)."""
+import json
+import subprocess
+import sys
+import textwrap
+import time
+from pathlib import Path
+
+from agent.trajectory import save_trajectory
+
+_REPO_ROOT = str(Path(__file__).resolve().parents[2])
+
+
+def test_concurrent_process_appends_stay_parseable(tmp_path):
+ """Payloads far larger than one atomic write() from several processes: every line parses."""
+ target = tmp_path / "trajectory_samples.jsonl"
+ script = textwrap.dedent(f"""
+ import sys; sys.path.insert(0, {_REPO_ROOT!r})
+ from agent.trajectory import save_trajectory
+ big = "x" * 300_000
+ for i in range(5):
+ save_trajectory([{{"from": "human", "value": f"P{{sys.argv[1]}}-{{i}} " + big}}],
+ model="m", completed=True, filename={str(target)!r})
+ """)
+ procs = [subprocess.Popen([sys.executable, "-c", script, str(n)], stdin=subprocess.DEVNULL) for n in range(6)]
+ for p in procs:
+ assert p.wait(timeout=120) == 0
+
+ lines = target.read_text(encoding="utf-8").splitlines()
+ assert len(lines) == 30
+ tags = {json.loads(ln)["conversations"][0]["value"].split(" ", 1)[0] for ln in lines}
+ assert tags == {f"P{n}-{i}" for n in range(6) for i in range(5)}
+
+
+def test_append_honours_a_foreign_exclusive_lock(tmp_path):
+ """While another process holds the file lock, save_trajectory() blocks instead of writing through."""
+ target = tmp_path / "failed_trajectories.jsonl"
+ target.write_text("", encoding="utf-8")
+ holder = subprocess.Popen(
+ [sys.executable, "-c", textwrap.dedent(f"""
+ import os, sys, time
+ f = open({str(target)!r}, "a")
+ if os.name == "nt":
+ import msvcrt; f.write(" "); f.flush(); f.seek(0); msvcrt.locking(f.fileno(), msvcrt.LK_LOCK, 1)
+ else:
+ import fcntl; fcntl.flock(f.fileno(), fcntl.LOCK_EX)
+ print("locked", flush=True)
+ time.sleep(1.5)
+ """)],
+ stdout=subprocess.PIPE, stdin=subprocess.DEVNULL, text=True,
+ )
+ try:
+ assert holder.stdout.readline().strip() == "locked" # type: ignore[union-attr]
+ started = time.monotonic()
+ save_trajectory([{"from": "human", "value": "hi"}], model="m", completed=False, filename=str(target))
+ waited = time.monotonic() - started
+ finally:
+ holder.kill()
+ holder.wait()
+ assert waited >= 1.0, f"append went through a held lock after {waited:.2f}s"
+ assert json.loads(target.read_text(encoding="utf-8").strip().splitlines()[-1])["completed"] is False