fix(idle): a dead owner's run claim is taken over at once
The idle-job run claim (curator and plugin idle tasks) recorded only the owner's pid and was reclaimed only after an hour, so a gateway that crashed or was killed mid-run kept the task suppressed for an hour after restart. The claim now records the owner's pid, process start time and machine (boot id + PID 1 start). A claim whose owner is gone, or whose pid now belongs to a process with another start time, is taken over at the next poll; a live owner's claim is never taken, however old. A claim whose owner cannot be checked (a bare pid from an older Hermes, another machine, no readable start time) keeps the hour rule. Takeovers and releases unlink the lock under a cross-process guard file, so two claimants of a dead claim never both win and a release never removes a claim another process took.
This commit is contained in:
committed by
Teknium
parent
aaf648e835
commit
d2fa5dcbc6
@@ -5,6 +5,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
@@ -46,29 +47,100 @@ def interval_due(
|
||||
return (now - last) >= timedelta(hours=interval_hours)
|
||||
|
||||
|
||||
def _machine() -> str:
|
||||
"""This container's or VM's instantiation (boot id + PID 1 start; ``""`` without ``/proc``): a
|
||||
pid names the same process only on the machine that recorded it."""
|
||||
from gateway.drain_control import current_instantiation_epoch
|
||||
|
||||
return current_instantiation_epoch()
|
||||
|
||||
|
||||
def _owner_record() -> dict[str, Any]:
|
||||
from gateway.status import get_process_start_time
|
||||
|
||||
pid = os.getpid()
|
||||
return {"pid": pid, "start": get_process_start_time(pid), "machine": _machine() or None}
|
||||
|
||||
|
||||
def _read_owner(lock: Path) -> Optional[dict[str, Any]]:
|
||||
"""The claim's owner record; ``None`` when unreadable or a bare pid (a claim of an older Hermes)."""
|
||||
try:
|
||||
data = json.loads(lock.read_text(encoding="utf-8-sig"))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
return data if isinstance(data, dict) else None
|
||||
|
||||
|
||||
def _owner_alive(owner: Optional[dict[str, Any]]) -> Optional[bool]:
|
||||
"""Whether the claim's owner still runs; ``None`` when that cannot be proven either way: no
|
||||
record, another machine, or no start time to tell the owner from a process that reused its pid."""
|
||||
pid, start, machine = (owner or {}).get("pid"), (owner or {}).get("start"), (owner or {}).get("machine")
|
||||
if type(pid) is not int or pid <= 0 or type(start) is not int or not machine or machine != _machine():
|
||||
return None
|
||||
from gateway.status import _pid_exists, get_process_start_time
|
||||
|
||||
live_start = get_process_start_time(pid)
|
||||
if live_start is not None and live_start != start:
|
||||
return False # the pid now belongs to another process
|
||||
if not _pid_exists(pid): # gone, or a zombie
|
||||
return False
|
||||
return True if live_start is not None else None
|
||||
|
||||
|
||||
def _abandoned(lock: Path, stale_seconds: float) -> bool:
|
||||
"""A claim is taken over when its owner is provably dead; a live owner's claim never is. When
|
||||
the owner cannot be proven either way, a claim older than ``stale_seconds`` counts as crashed."""
|
||||
alive = _owner_alive(_read_owner(lock))
|
||||
if alive is not None:
|
||||
return not alive
|
||||
return time.time() - lock.stat().st_mtime > stale_seconds
|
||||
|
||||
|
||||
def _create(lock: Path) -> bool:
|
||||
try:
|
||||
fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
||||
except FileExistsError:
|
||||
return False
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
||||
fh.write(json.dumps(_owner_record()))
|
||||
return True
|
||||
|
||||
|
||||
def _unlink_guard(lock: Path):
|
||||
"""Every unlink of ``lock`` (a takeover or a release) happens under this cross-process file
|
||||
lock, so the claim a takeover judged abandoned is the one it removes: two claimants never both
|
||||
win, and a release never removes a claim another process has since taken."""
|
||||
from tools.skill_usage import skill_file_lock
|
||||
|
||||
return skill_file_lock(lock.with_name(lock.name + ".guard"))
|
||||
|
||||
|
||||
def claim_run(lock: Path, stale_seconds: float = CLAIM_STALE_SECONDS) -> bool:
|
||||
"""One run at a time across processes: the O_EXCL create of ``lock`` wins the claim; a claim
|
||||
older than ``stale_seconds`` is a crashed holder and is taken over. When the lock dir cannot be
|
||||
created, run anyway."""
|
||||
"""One run at a time across processes: the O_EXCL create of ``lock`` wins the claim. The claim
|
||||
records its owner (pid, process start, machine); a claim whose owner is provably dead is taken
|
||||
over at once, one whose owner cannot be checked (another machine, an older Hermes's bare pid)
|
||||
once it is older than ``stale_seconds``. When the lock dir cannot be created, run anyway."""
|
||||
try:
|
||||
lock.parent.mkdir(parents=True, exist_ok=True)
|
||||
except OSError:
|
||||
return True
|
||||
if _create(lock):
|
||||
return True
|
||||
try:
|
||||
fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
||||
except FileExistsError:
|
||||
try:
|
||||
if time.time() - lock.stat().st_mtime > stale_seconds:
|
||||
lock.unlink()
|
||||
return claim_run(lock, stale_seconds)
|
||||
except OSError:
|
||||
pass
|
||||
with _unlink_guard(lock):
|
||||
if _create(lock): # released meanwhile
|
||||
return True
|
||||
if not _abandoned(lock, stale_seconds):
|
||||
return False
|
||||
lock.unlink()
|
||||
return _create(lock)
|
||||
except OSError:
|
||||
return False
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
||||
fh.write(str(os.getpid()))
|
||||
return True
|
||||
|
||||
|
||||
def release_run(lock: Path) -> None:
|
||||
with contextlib.suppress(OSError):
|
||||
lock.unlink()
|
||||
"""Drop this process's claim; a claim another process took over (as abandoned) stays."""
|
||||
with contextlib.suppress(OSError), _unlink_guard(lock):
|
||||
owner = _read_owner(lock)
|
||||
if owner is None or owner.get("pid") == os.getpid():
|
||||
lock.unlink()
|
||||
|
||||
138
tests/agent/test_idle_schedule_claim_owner.py
Normal file
138
tests/agent/test_idle_schedule_claim_owner.py
Normal file
@@ -0,0 +1,138 @@
|
||||
"""The idle-job run claim is taken over as soon as its owner is provably dead, never from a live owner.
|
||||
|
||||
The curator and every plugin idle task hold this claim for one run at a time across processes. A
|
||||
gateway that crashed (or was SIGKILLed) mid-run used to keep its claim for an hour, so the task
|
||||
stayed suppressed after the restart. The claim records its owner's pid, process start and machine:
|
||||
a dead owner, or a pid that now names another process, loses the claim at once; an owner that
|
||||
cannot be checked (a bare pid written by an older Hermes) keeps the old hour-old rule.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from agent.idle_schedule import CLAIM_STALE_SECONDS, claim_run, release_run
|
||||
|
||||
pytestmark = pytest.mark.platforms("linux") # pid start + machine identity come from /proc
|
||||
|
||||
_ROOT = Path(__file__).resolve().parents[2]
|
||||
_HOLDER = """
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from agent.idle_schedule import claim_run
|
||||
print(claim_run(Path(sys.argv[1])), flush=True)
|
||||
sys.stdin.read() # hold the claim until the test closes stdin
|
||||
"""
|
||||
|
||||
|
||||
def _holder(lock: Path) -> subprocess.Popen:
|
||||
env = {**os.environ, "PYTHONPATH": str(_ROOT)}
|
||||
return subprocess.Popen([sys.executable, "-c", _HOLDER, str(lock)], stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE, text=True, env=env, cwd=_ROOT)
|
||||
|
||||
|
||||
def _claimed(proc: subprocess.Popen) -> bool:
|
||||
return proc.stdout.readline().strip() == "True"
|
||||
|
||||
|
||||
def _age(lock: Path, seconds: float) -> None:
|
||||
old = time.time() - seconds
|
||||
os.utime(lock, (old, old))
|
||||
|
||||
|
||||
def _end(proc: subprocess.Popen) -> None:
|
||||
proc.kill()
|
||||
proc.wait(10)
|
||||
|
||||
|
||||
def test_a_claim_of_a_killed_owner_is_taken_over_at_once(tmp_path):
|
||||
lock = tmp_path / ".task.lock"
|
||||
owner = _holder(lock)
|
||||
try:
|
||||
assert _claimed(owner)
|
||||
assert claim_run(lock) is False # the owner is alive
|
||||
finally:
|
||||
_end(owner) # SIGKILL: no release ran
|
||||
assert lock.exists()
|
||||
assert claim_run(lock) is True
|
||||
assert json.loads(lock.read_text())["pid"] == os.getpid()
|
||||
release_run(lock)
|
||||
assert not lock.exists()
|
||||
|
||||
|
||||
def test_a_killed_owners_claim_rewritten_with_a_bom_is_still_taken_over_at_once(tmp_path):
|
||||
lock = tmp_path / ".task.lock"
|
||||
owner = _holder(lock)
|
||||
try:
|
||||
assert _claimed(owner)
|
||||
finally:
|
||||
_end(owner)
|
||||
lock.write_bytes(b"\xef\xbb\xbf" + lock.read_bytes()) # Windows tooling BOMs files it touches
|
||||
assert claim_run(lock) is True
|
||||
|
||||
|
||||
def test_a_live_owner_keeps_its_claim_however_old_it_is(tmp_path):
|
||||
lock = tmp_path / ".task.lock"
|
||||
owner = _holder(lock)
|
||||
try:
|
||||
assert _claimed(owner)
|
||||
_age(lock, CLAIM_STALE_SECONDS + 60)
|
||||
assert claim_run(lock) is False
|
||||
release_run(lock) # not this process's claim
|
||||
assert lock.exists()
|
||||
finally:
|
||||
_end(owner)
|
||||
|
||||
|
||||
def test_a_pid_reused_by_another_process_does_not_keep_the_claim(tmp_path):
|
||||
lock = tmp_path / ".task.lock"
|
||||
other = _holder(tmp_path / ".other.lock") # a live process now holding the recorded pid
|
||||
try:
|
||||
assert _claimed(other)
|
||||
record = json.loads((tmp_path / ".other.lock").read_text())
|
||||
record["start"] -= 1 # the owner that wrote this claim started earlier: it was another process
|
||||
lock.write_text(json.dumps(record))
|
||||
assert claim_run(lock) is True
|
||||
finally:
|
||||
_end(other)
|
||||
|
||||
|
||||
def test_a_bare_pid_claim_keeps_the_hour_rule(tmp_path):
|
||||
lock = tmp_path / ".task.lock"
|
||||
gone = subprocess.Popen([sys.executable, "-c", "pass"])
|
||||
gone.wait(10)
|
||||
lock.write_text(str(gone.pid)) # an older Hermes's claim: no start time to check the owner by
|
||||
assert claim_run(lock) is False
|
||||
_age(lock, CLAIM_STALE_SECONDS + 1)
|
||||
assert claim_run(lock) is True
|
||||
|
||||
|
||||
def test_a_claim_from_another_machine_keeps_the_hour_rule(tmp_path):
|
||||
lock = tmp_path / ".task.lock"
|
||||
gone = subprocess.Popen([sys.executable, "-c", "pass"])
|
||||
gone.wait(10)
|
||||
lock.write_text(json.dumps({"pid": gone.pid, "start": 1, "machine": "another-boot:1"}))
|
||||
assert claim_run(lock) is False # its pid says nothing about the other machine's processes
|
||||
_age(lock, CLAIM_STALE_SECONDS + 1)
|
||||
assert claim_run(lock) is True
|
||||
|
||||
|
||||
def test_racing_claimants_of_a_dead_owners_claim_have_one_winner(tmp_path):
|
||||
lock = tmp_path / ".task.lock"
|
||||
owner = _holder(lock)
|
||||
assert _claimed(owner)
|
||||
_end(owner)
|
||||
racers = [_holder(lock) for _ in range(6)]
|
||||
try:
|
||||
results = [_claimed(r) for r in racers] # each keeps running, so a winner stays a live owner
|
||||
finally:
|
||||
for r in racers:
|
||||
_end(r)
|
||||
assert results.count(True) == 1, results
|
||||
@@ -901,8 +901,9 @@ The contract a task's `fn` is written against:
|
||||
plugin's data so the next run picks up where this one stopped.
|
||||
* Keep a run idempotent: a run cut off by a restart leaves no record and runs again later from the
|
||||
start, so running the same batch twice must do no harm.
|
||||
* No second run of a task starts while one is in flight (a claim another process has held for
|
||||
over an hour counts as abandoned). An exception is caught, logged and recorded as
|
||||
* No second run of a task starts while one is in flight. A claim whose process has died (a crash
|
||||
or a kill) is taken over at the next poll; a claim whose owner cannot be checked (one written on
|
||||
another machine) counts as abandoned after an hour. An exception is caught, logged and recorded as
|
||||
`last_status: error`; it never reaches the host.
|
||||
* Model calls from `fn` go through `ctx.llm` and its trust gate. `fn` has no turn, so it gets no
|
||||
`side_question_token` and cannot fork the session.
|
||||
|
||||
Reference in New Issue
Block a user