fix(kanban): owner-run workers keep main's worker contract
The spawned worker is the attempt's handle again: the owner's interpreter watches the run row's pid and exits when it dies, so a SIGKILL, timeout or OOM kill ends the attempt and is booked as that run's crash (re-queued once, as a one-shot worker was). Ambiguous owner receipts still hold the card while the bound interpreter may run; once it is dead the crash route reaps. Also: the client writes the [kanban-worker-exit] trailer and the attempt's last output, the review lane loads sdlc-review, heartbeats extend by the dispatcher's claim TTL, and the kanban e2e board turns off the embedded gateway dispatcher so its explicit ticks stay deterministic.
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
"""Trusted dispatcher claims enter the ordinary owner's durable admission queue."""
|
||||
from contextlib import closing
|
||||
from dataclasses import asdict, replace
|
||||
import threading
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
@@ -39,6 +40,10 @@ def build_kanban_policy(connection, params, config):
|
||||
if bound and json.loads(bound[0])['request_id'] != 'kanban:' + json.dumps([board, task.id, task.current_run_id], separators=(',', ':')):
|
||||
raise RuntimeStoreError('stale_kanban_claim')
|
||||
context = kb.build_worker_context(conn, task.id)
|
||||
skills = list(task.skills or ())
|
||||
if kb._retry_status_for_run(conn, task.id, task.current_run_id) == 'review':
|
||||
# Same rule as the dispatcher's review lane: the reviewer always loads sdlc-review.
|
||||
skills = list(dict.fromkeys([*skills, 'sdlc-review']))
|
||||
except (ValueError, OSError, sqlite3.Error) as exc:
|
||||
raise RuntimeStoreError('invalid_kanban_claim') from exc
|
||||
cwd = task.workspace_path
|
||||
@@ -53,7 +58,7 @@ def build_kanban_policy(connection, params, config):
|
||||
policy = replace(policy, model=_resolve_gateway_model(policy.config()))
|
||||
context = dict(params, workspace=cwd, branch=task.branch_name, tenant=task.tenant,
|
||||
profile=task.assignee, workspaces_root=str(kb.workspaces_root(board=board).resolve()),
|
||||
skills=list(task.skills or ()), goal_mode=task.goal_mode, goal_max_turns=task.goal_max_turns,
|
||||
skills=skills, goal_mode=task.goal_mode, goal_max_turns=task.goal_max_turns,
|
||||
goal_text='\n\n'.join(p for p in (task.title, task.body) if p), context=context,
|
||||
max_runtime_seconds=task.max_runtime_seconds, accept_hooks=True)
|
||||
context['db'] = str(path)
|
||||
@@ -149,23 +154,50 @@ def bind_worker_context(frame):
|
||||
if (task is None or task.status != 'running' or task.current_run_id != context['run_id']
|
||||
or task.claim_lock != context['claim_lock']):
|
||||
raise RuntimeStoreError('stale_kanban_claim')
|
||||
# Reclaim/timeout must track the executing interpreter, not its disposable viewer. The
|
||||
# fingerprint moves with the pid: the dispatcher's liveness/kill checks compare the live
|
||||
# process against ``worker_started_at``, so a launcher fingerprint left beside our pid
|
||||
# would read as a recycled PID and reclaim a running worker.
|
||||
# The dispatcher's spawned worker stays the run's pid (reclaim, timeout and operator
|
||||
# kills target it; ``_watch_submitter`` ties this interpreter's life to it). The bound
|
||||
# interpreter is recorded beside it so a sweep can tell when the attempt is truly gone.
|
||||
from hermes_cli.kanban_db_dispatch import UNVERIFIED_WORKER_FINGERPRINT, _process_fingerprint
|
||||
fingerprint = _process_fingerprint(os.getpid()) or UNVERIFIED_WORKER_FINGERPRINT
|
||||
conn.execute('UPDATE tasks SET worker_pid=?, worker_started_at=? WHERE id=?',
|
||||
(os.getpid(), fingerprint, task.id))
|
||||
conn.execute('UPDATE task_runs SET worker_pid=?, worker_started_at=? WHERE id=?',
|
||||
(os.getpid(), fingerprint, context['run_id']))
|
||||
kb._append_event(conn, task.id, 'worker_bound', {'pid': os.getpid(), 'claim_lock': context['claim_lock']}, run_id=context['run_id'])
|
||||
kb._append_event(conn, task.id, 'worker_bound', {'pid': os.getpid(), 'claim_lock': context['claim_lock'],
|
||||
'started_at': fingerprint}, run_id=context['run_id'])
|
||||
claimed = conn.execute("SELECT payload, created_at FROM task_events WHERE task_id=? AND run_id=? AND kind='claimed' ORDER BY id DESC LIMIT 1",
|
||||
(task.id, context['run_id'])).fetchone()
|
||||
# Heartbeats extend the claim by the TTL the dispatcher claimed it with (a spawned worker
|
||||
# inherited it from the dispatcher's environment); this daemon's own default is not that.
|
||||
expires = json.loads(claimed[0]).get('expires') if claimed else None
|
||||
if isinstance(expires, int) and claimed[1]:
|
||||
env['HERMES_KANBAN_CLAIM_TTL_SECONDS'] = str(max(1, expires - int(claimed[1])))
|
||||
_watch_submitter(Path(context['db']), context['run_id'])
|
||||
os.environ.update(env)
|
||||
os.chdir(context['workspace'])
|
||||
from agent.shell_hooks import register_from_config
|
||||
register_from_config(json.loads(frame['policy']['config_json']), accept_hooks=context['accept_hooks'])
|
||||
|
||||
|
||||
_TURNS_DONE = threading.Event()
|
||||
|
||||
|
||||
def _watch_submitter(db, run_id):
|
||||
"""The dispatcher's spawned worker is this attempt's handle: killing it (an operator, a
|
||||
timeout, an OOM kill) must end the attempt, as it did when the worker ran the agent itself.
|
||||
Exiting hard leaves no ``worker_result``, so the dead-worker sweep books this run's crash.
|
||||
The run row is re-read each tick: the dispatcher records the pid only after its spawn returns."""
|
||||
import os
|
||||
from hermes_cli.kanban_db_dispatch import _worker_alive
|
||||
|
||||
def watch():
|
||||
with closing(sqlite3.connect(db.resolve().as_uri() + '?mode=ro', uri=True)) as conn:
|
||||
while not _TURNS_DONE.wait(1.0):
|
||||
try:
|
||||
row = conn.execute('SELECT worker_pid, worker_started_at FROM task_runs WHERE id=?', (run_id,)).fetchone()
|
||||
except sqlite3.Error:
|
||||
continue
|
||||
if row and row[0] and row[0] != os.getpid() and not _worker_alive(row[0], row[1]):
|
||||
os._exit(1)
|
||||
threading.Thread(target=watch, name='kanban-submitter-watch', daemon=True).start()
|
||||
|
||||
|
||||
def run_worker_turns(agent, frame, history):
|
||||
context = json.loads(frame['policy'].get('kanban_json') or 'null')
|
||||
if context is None:
|
||||
@@ -173,32 +205,40 @@ def run_worker_turns(agent, frame, history):
|
||||
return agent.run_conversation(frame['text'], conversation_history=history,
|
||||
**({'turn_author': author} if author is not None else {}))
|
||||
from hermes_cli.kanban_db import KANBAN_RATE_LIMIT_EXIT_CODE
|
||||
code = 1
|
||||
code, last_output = 1, ''
|
||||
try:
|
||||
result = _run_task_turns(agent, frame, history, context)
|
||||
code = KANBAN_RATE_LIMIT_EXIT_CODE if result.get('failed') and result.get('failure_reason') in {'rate_limit', 'billing'} else int(bool(result.get('failed') or result.get('interrupted')))
|
||||
last_output = str(result.get('final_response') or '')[-500:]
|
||||
return result
|
||||
finally:
|
||||
_TURNS_DONE.set()
|
||||
import os
|
||||
from hermes_cli.kanban_db_connect import connect_closing
|
||||
from hermes_cli import kanban_db as kb
|
||||
with connect_closing(Path(context['db'])) as conn, kb.write_txn(conn):
|
||||
row = conn.execute("SELECT payload FROM task_events WHERE task_id=? AND run_id=? AND kind='worker_bound' ORDER BY id DESC LIMIT 1",
|
||||
(context['task_id'], context['run_id'])).fetchone()
|
||||
if row and json.loads(row[0]) == {'pid': os.getpid(), 'claim_lock': context['claim_lock']}:
|
||||
bound = json.loads(row[0]) if row else {}
|
||||
if (bound.get('pid'), bound.get('claim_lock')) == (os.getpid(), context['claim_lock']):
|
||||
# Closing a run clears its claim/PID and replaces metadata; keep the
|
||||
# result in the immutable attempt event stream instead.
|
||||
kb._append_event(conn, context['task_id'], 'worker_result',
|
||||
{'pid': os.getpid(), 'claim_lock': context['claim_lock'], 'exit_code': code}, run_id=context['run_id'])
|
||||
{'pid': os.getpid(), 'claim_lock': context['claim_lock'], 'exit_code': code,
|
||||
'last_output': last_output}, run_id=context['run_id'])
|
||||
|
||||
|
||||
def worker_exit_code(path, params):
|
||||
def worker_result(path, params):
|
||||
"""Read only the dispatcher's exact attempt; never infer success from admission settlement."""
|
||||
with closing(sqlite3.connect(Path(path).resolve().as_uri() + '?mode=ro', uri=True)) as conn:
|
||||
row = conn.execute("SELECT payload FROM task_events WHERE run_id=? AND task_id=? AND kind='worker_result' ORDER BY id DESC LIMIT 1",
|
||||
(params['run_id'], params['task_id'])).fetchone()
|
||||
result = json.loads(row[0]) if row else {}
|
||||
return result.get('exit_code', 1) if result.get('claim_lock') == params['claim_lock'] else 1
|
||||
return result if result.get('claim_lock') == params['claim_lock'] else {}
|
||||
|
||||
|
||||
def worker_exit_code(path, params):
|
||||
return worker_result(path, params).get('exit_code', 1)
|
||||
|
||||
|
||||
def _run_task_turns(agent, frame, history, context):
|
||||
|
||||
@@ -1158,10 +1158,8 @@ def _reclaim_dead_workers(conn: sqlite3.Connection, board: Optional[str] = None)
|
||||
"WHERE status = 'running' AND worker_pid IS NOT NULL"
|
||||
).fetchall()
|
||||
host_prefix = _kb._host_prefix()
|
||||
from hermes_cli.kanban_owner_recovery import owner_reclaim_paused
|
||||
from hermes_cli.kanban_owner_recovery import bound_interpreter_gone, owner_reclaim_paused
|
||||
for row in rows:
|
||||
if owner_reclaim_paused(conn, row["id"]):
|
||||
continue
|
||||
lock = row["claim_lock"] or ""
|
||||
if not lock.startswith(host_prefix):
|
||||
continue
|
||||
@@ -1172,6 +1170,10 @@ def _reclaim_dead_workers(conn: sqlite3.Connection, board: Optional[str] = None)
|
||||
continue
|
||||
if _worker_alive(row["worker_pid"], _kb._row_get(row, "worker_started_at")):
|
||||
continue
|
||||
# An ambiguous owner receipt holds the card while the attempt may still run; once the
|
||||
# interpreter the owner bound to this run is dead nothing can, and it is a crash.
|
||||
if owner_reclaim_paused(conn, row["id"]) and not bound_interpreter_gone(conn, row["id"]):
|
||||
continue
|
||||
|
||||
pid = int(row["worker_pid"])
|
||||
# Managed interpreters are children of the authority, not this dispatcher.
|
||||
|
||||
@@ -29,3 +29,17 @@ def owner_reclaim_paused(conn, task_id):
|
||||
return True
|
||||
except psutil.Error:
|
||||
return True
|
||||
|
||||
|
||||
|
||||
def bound_interpreter_gone(conn, task_id):
|
||||
"""True when the owner bound an interpreter to the task's current run and it is dead."""
|
||||
from hermes_cli.kanban_db_dispatch import _worker_alive
|
||||
row = conn.execute(
|
||||
"SELECT e.payload FROM task_events e JOIN tasks t ON t.current_run_id=e.run_id "
|
||||
"WHERE t.id=? AND e.task_id=t.id AND e.kind='worker_bound' ORDER BY e.id DESC LIMIT 1",
|
||||
(task_id,)).fetchone()
|
||||
if row is None:
|
||||
return False
|
||||
bound = json.loads(row['payload'])
|
||||
return not _worker_alive(bound.get('pid'), bound.get('started_at'))
|
||||
|
||||
@@ -18,11 +18,27 @@ async def run(params, board_db):
|
||||
receipt = await client.rpc('prompt.receipt', session_id=sid, admission_id=receipt['admission_id'])
|
||||
if receipt['status'] == 'unknown':
|
||||
raise GatewayClientError('Kanban execution unknown; retained by owner')
|
||||
from gateway.session_kanban import worker_exit_code
|
||||
return worker_exit_code(board_db, params)
|
||||
from gateway.session_kanban import worker_result
|
||||
result = worker_result(board_db, params)
|
||||
# The attempt's reply ends the log, as a one-shot worker's did: crash diagnostics quote it.
|
||||
if result.get('last_output'):
|
||||
print(result['last_output'])
|
||||
return result.get('exit_code', 1)
|
||||
|
||||
|
||||
def main():
|
||||
# The dead-worker sweep books this process's exit from the trailer in its log (it never
|
||||
# reaps us), so every exit path writes it — the same contract as a quiet one-shot worker.
|
||||
from hermes_cli.quiet_single_query import KANBAN_WORKER_EXIT_TRAILER
|
||||
rc = 1
|
||||
try:
|
||||
rc = _submit()
|
||||
finally:
|
||||
print(f'\n{KANBAN_WORKER_EXIT_TRAILER}{int(rc)}', file=sys.stderr, flush=True)
|
||||
return rc
|
||||
|
||||
|
||||
def _submit():
|
||||
try:
|
||||
params = {'board': os.environ['HERMES_KANBAN_BOARD'], 'task_id': os.environ['HERMES_KANBAN_TASK'],
|
||||
'run_id': int(os.environ['HERMES_KANBAN_RUN_ID']), 'claim_lock': os.environ['HERMES_KANBAN_CLAIM_LOCK']}
|
||||
|
||||
@@ -77,6 +77,9 @@ class Board:
|
||||
" api_max_retries: 1\n"
|
||||
"updates:\n"
|
||||
" check: false\n"
|
||||
# Workers run inside the profile's owner daemon; its embedded dispatcher would race
|
||||
# the explicit ticks these tests count. A test that wants it brings its own block.
|
||||
+ ("" if "kanban:" in self.extra_config else "kanban:\n dispatch_in_gateway: false\n")
|
||||
+ self.extra_config,
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
@@ -104,7 +104,9 @@ def main():
|
||||
if peer.mode == 'timeout':
|
||||
assert peer.blocked.wait(55), 'managed worker did not reach loopback'
|
||||
with closing(connect(board='owned')) as snapshot:
|
||||
receipt['managed_pid'] = kb.get_task(snapshot, tid).worker_pid
|
||||
bound = snapshot.execute("SELECT payload FROM task_events WHERE task_id=? AND kind='worker_bound' "
|
||||
"ORDER BY id DESC LIMIT 1", (tid,)).fetchone()
|
||||
receipt['managed_pid'] = json.loads(bound[0])['pid'] if bound else None
|
||||
return child
|
||||
def wait_for(predicate):
|
||||
deadline = time.monotonic() + 60
|
||||
@@ -126,12 +128,15 @@ def main():
|
||||
active = kb.get_task(conn, tid)
|
||||
receipt.update(client_pid=clients[0].pid, stored_pid=active.worker_pid, run_id=task.current_run_id)
|
||||
if peer.mode == 'timeout':
|
||||
receipt['pid_preserved'] = active.worker_pid == receipt['managed_pid'] != clients[0].pid
|
||||
# The spawned worker stays the run's handle; the owner's interpreter dies with it.
|
||||
receipt['pid_preserved'] = active.worker_pid == clients[0].pid != receipt['managed_pid']
|
||||
# Deterministically elapse this owned attempt; keep real timeout/kill logic.
|
||||
conn.execute('UPDATE task_runs SET started_at=? WHERE id=?', (int(time.time()) - 3601, task.current_run_id))
|
||||
conn.commit()
|
||||
swept = dispatch.dispatch_once(conn, board='owned', max_spawn=0)
|
||||
receipt.update(timed_out=swept.timed_out, managed_dead=not kb._pid_alive(receipt['managed_pid']))
|
||||
receipt['timed_out'] = swept.timed_out
|
||||
wait_for(lambda: not kb._pid_alive(receipt['managed_pid']))
|
||||
receipt['managed_dead'] = True
|
||||
assert receipt['pid_preserved'] and receipt['managed_dead'], receipt
|
||||
elif peer.mode == 'crash':
|
||||
import signal
|
||||
@@ -156,7 +161,8 @@ def main():
|
||||
assert receipt['client_exit'] == ('rate_limited', kb.KANBAN_RATE_LIMIT_EXIT_CODE), receipt
|
||||
assert receipt['cooldown'] == 'rate_limit_cooldown', receipt
|
||||
elif peer.mode == 'crash':
|
||||
assert task.status == 'running' and task.consecutive_failures == 0 and run['outcome'] is None, receipt
|
||||
# Killing the spawned worker ends the attempt: one crash, re-queued, as before the owner.
|
||||
assert task.status == 'ready' and task.consecutive_failures == 1 and run['outcome'] == 'crashed', receipt
|
||||
elif peer.mode == 'timeout':
|
||||
assert task.status == 'ready' and task.consecutive_failures == 1 and run['outcome'] == 'timed_out', receipt
|
||||
finally:
|
||||
|
||||
@@ -117,7 +117,9 @@ def main():
|
||||
if mode == 'restart':
|
||||
proc.kill(); proc.wait(timeout=10)
|
||||
# Model effects are ambiguous: terminate the exact owned executing interpreter.
|
||||
os.kill(active.worker_pid, signal.SIGKILL)
|
||||
bound = conn.execute("SELECT payload FROM task_events WHERE task_id=? AND kind='worker_bound' "
|
||||
"ORDER BY id DESC LIMIT 1", (tid,)).fetchone()
|
||||
os.kill(json.loads(bound[0])['pid'], signal.SIGKILL)
|
||||
dispatch._recent_worker_exits.clear()
|
||||
swept = dispatch.dispatch_once(conn, board='owned', max_spawn=1)
|
||||
assert not swept.spawned and kb.get_task(conn, tid).current_run_id == task.current_run_id
|
||||
@@ -129,37 +131,33 @@ def main():
|
||||
if mode == 'restart':
|
||||
cfg['model']['default'] = 'changed-default'
|
||||
(owner / 'config.yaml').write_text(json.dumps(cfg))
|
||||
for generation in range(2):
|
||||
with daemon(root, owner, env, barrier=False) as (proc, desc):
|
||||
answer = asyncio.run(retry(desc, params))
|
||||
assert answer['receipt']['status'] == 'unknown', answer
|
||||
assert answer['session_id'] == first['target_session_id']
|
||||
with closing(sqlite3.connect((owner / 'state.db').as_uri() + '?mode=ro', uri=True)) as db:
|
||||
frozen = json.loads(db.execute('SELECT value FROM state_meta WHERE key=?',
|
||||
('gateway.local_policy.v1:' + first['target_session_id'],)).fetchone()[0])
|
||||
assert frozen['policy']['model'] == 'frozen-model', frozen
|
||||
private = json.loads(frozen['policy']['kanban_json'])
|
||||
assert private['db'] == str(board_path.resolve()) and private['claim_lock'] == task.claim_lock
|
||||
# Elapse TTL, heartbeat and runtime to exercise every reclaim route.
|
||||
conn.execute('UPDATE tasks SET claim_expires=1,last_heartbeat_at=1,max_runtime_seconds=1 WHERE id=?', (tid,))
|
||||
conn.execute('UPDATE task_runs SET started_at=1 WHERE id=?', (task.current_run_id,))
|
||||
conn.commit()
|
||||
dispatch._recent_worker_exits.clear()
|
||||
swept = dispatch.dispatch_once(conn, board='owned', max_spawn=1, stale_timeout_seconds=1)
|
||||
same = kb.get_task(conn, tid)
|
||||
assert not swept.spawned and same.status == 'running', (swept, same)
|
||||
assert (same.current_run_id, same.claim_lock) == (task.current_run_id, task.claim_lock)
|
||||
assert same.consecutive_failures == 0
|
||||
assert len(peer.requests) == 1, peer.requests
|
||||
if generation == 1:
|
||||
asyncio.run(retry(desc, params, resolve=True))
|
||||
assert admission()['status'] == 'terminal'
|
||||
dispatch.dispatch_once(conn, board='owned', max_spawn=0)
|
||||
assert kb.get_task(conn, tid).status == 'running'
|
||||
# Discarding unknown admission is not permission to rerun the card.
|
||||
kb.block_task(conn, tid, reason='Operator resolves ambiguous attempt', expected_run_id=task.current_run_id)
|
||||
assert kb.get_task(conn, tid).status == 'blocked'
|
||||
receipt['unknown_preserved_two_restarts'] = True
|
||||
with daemon(root, owner, env, barrier=False) as (proc, desc):
|
||||
answer = asyncio.run(retry(desc, params))
|
||||
assert answer['receipt']['status'] == 'unknown', answer
|
||||
assert answer['session_id'] == first['target_session_id']
|
||||
with closing(sqlite3.connect((owner / 'state.db').as_uri() + '?mode=ro', uri=True)) as db:
|
||||
frozen = json.loads(db.execute('SELECT value FROM state_meta WHERE key=?',
|
||||
('gateway.local_policy.v1:' + first['target_session_id'],)).fetchone()[0])
|
||||
assert frozen['policy']['model'] == 'frozen-model', frozen
|
||||
private = json.loads(frozen['policy']['kanban_json'])
|
||||
assert private['db'] == str(board_path.resolve()) and private['claim_lock'] == task.claim_lock
|
||||
# The attempt's interpreter and its spawned worker are both gone: an ordinary crash,
|
||||
# booked once and re-queued once (same as a killed one-shot worker), never duplicated.
|
||||
wait_for(lambda: all(p.poll() is not None for p in clients))
|
||||
assert len(peer.requests) == 1, peer.requests # the restart never replays the lost call
|
||||
conn.execute('UPDATE tasks SET claim_expires=1,last_heartbeat_at=1,max_runtime_seconds=1 WHERE id=?', (tid,))
|
||||
conn.execute('UPDATE task_runs SET started_at=1 WHERE id=?', (task.current_run_id,))
|
||||
conn.commit()
|
||||
dispatch._recent_worker_exits.clear()
|
||||
dispatch.dispatch_once(conn, board='owned', max_spawn=0, stale_timeout_seconds=1)
|
||||
same = kb.get_task(conn, tid)
|
||||
run = conn.execute('SELECT outcome FROM task_runs WHERE id=?', (task.current_run_id,)).fetchone()
|
||||
# 'running' when the owner's own dispatcher already re-queued it onto a fresh run.
|
||||
assert same.status in {'ready', 'running'} and (same.consecutive_failures, run[0]) == (1, 'crashed'), (same, run[0])
|
||||
assert same.current_run_id != task.current_run_id or same.status == 'ready', same
|
||||
dispatch.dispatch_once(conn, board='owned', max_spawn=0, stale_timeout_seconds=1)
|
||||
assert kb.get_task(conn, tid).consecutive_failures == 1
|
||||
receipt['crash_requeued_once'] = True
|
||||
receipt.update(inference_calls=len(peer.requests), frozen_model=peer.requests[0]['model'])
|
||||
assert peer.requests[0]['model'] == 'frozen-model'
|
||||
wait_for(lambda: all(p.poll() is not None for p in clients))
|
||||
|
||||
@@ -65,7 +65,7 @@ def test_real_dispatcher_lifecycle(tmp_path, mode):
|
||||
receipt = json.loads((tmp_path / 'state' / 'receipt.json').read_text())
|
||||
print(json.dumps(receipt))
|
||||
if mode != 'complete':
|
||||
assert receipt['task_status'] == ('running' if mode == 'crash' else 'ready')
|
||||
assert receipt['task_status'] == 'ready'
|
||||
return
|
||||
assert receipt['task_status'] == 'done' and receipt['source'] == 'kanban'
|
||||
assert receipt['tools'] and receipt['task_context'] and receipt['skill_context'] and receipt['hook_effect']
|
||||
|
||||
Reference in New Issue
Block a user