The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: add assignment-fenced worker constructor and finalization handlers
Tekniumb7de5a8eba9a
diff --git a/agent/runtime_session_lifecycle.py b/agent/runtime_session_lifecycle.pynew file mode 100644index 00000000000..970a04a9c36--- /dev/null+++ b/agent/runtime_session_lifecycle.py@@ -0,0 +1,31 @@+"""Explicit lifecycle methods for the assignment-bound worker store.++The owner reserves identity before construction. Closing the local store remains+separate from ending its session and settling execution (including deferred work).+"""+++class RuntimeSessionLifecycleMixin:+ def create_session(self, session_id, source, *, model=None, model_config=None,+ system_prompt=None, user_id=None, session_key=None, chat_id=None,+ chat_type=None, thread_id=None, parent_session_id=None, cwd=None,+ profile_name=None, git_repo_root=None, origin_json=None, display_name=None):+ self._session(session_id)+ payload = dict(source=source, model=model, model_config=model_config, system_prompt=system_prompt,+ user_id=user_id, session_key=session_key, chat_id=chat_id, chat_type=chat_type,+ thread_id=thread_id, parent_session_id=parent_session_id, cwd=cwd,+ profile_name=profile_name, git_repo_root=git_repo_root,+ origin_json=origin_json, display_name=display_name)+ return self._apply('session.create', payload)['value']++ def end_session(self, session_id, end_reason):+ self._session(session_id)+ self._apply('session.end', {'end_reason': end_reason})++ def session_lifecycle_statuses(self, session_ids):+ ids = [sid for sid in (session_ids or []) if sid]+ for sid in ids:+ self._session(sid)+ if not ids:+ return {}+ return {self.scope['session_id']: self._apply('session.lifecycle', {})['value']}diff --git a/hermes_state_worker_lifecycle.py b/hermes_state_worker_lifecycle.pynew file mode 100644index 00000000000..45a4c742e2d--- /dev/null+++ b/hermes_state_worker_lifecycle.py@@ -0,0 +1,128 @@+"""Closed worker lifecycle handlers, called only inside the receipt transaction."""+import json+import time++from hermes_state_runtime import RuntimeStoreError+++_IDENTITY_FIELDS = frozenset({+ 'user_id', 'session_key', 'chat_id', 'chat_type', 'thread_id',+ 'parent_session_id', 'cwd', 'profile_name', 'git_repo_root', 'origin_json', 'display_name',+})+_CREATE_FIELDS = _IDENTITY_FIELDS | {'source', 'model', 'model_config', 'system_prompt'}+_CONSTRUCTOR_CONFIG = frozenset({'max_iterations', 'max_tokens', 'reasoning_config', 'yolo_mode'})+++def worker_create(db, conn, session_id, payload):+ if set(payload) - _CREATE_FIELDS or 'source' not in payload:+ raise RuntimeStoreError('invalid_params')+ row = conn.execute('SELECT * FROM sessions WHERE id=?', (session_id,)).fetchone()+ # A worker cannot mint a row or supply unreserved routing, lineage or cwd.+ if row is None or payload['source'] != row['source']:+ raise RuntimeStoreError('permission_denied')+ for key in _IDENTITY_FIELDS:+ value = payload.get(key)+ if value is not None and value != row[key]:+ raise RuntimeStoreError('permission_denied')+ for key in _CREATE_FIELDS - {'model_config'}:+ if payload.get(key) is not None and not isinstance(payload[key], str):+ raise RuntimeStoreError('invalid_params')+ config = payload.get('model_config')+ if config is not None and (not isinstance(config, dict) or set(config) - _CONSTRUCTOR_CONFIG):+ raise RuntimeStoreError('invalid_params')+ insert_session_row_in_transaction(db, conn, session_id, **payload)+ return {'value': session_id}+++def worker_end(db, conn, session_id, payload):+ if set(payload) != {'end_reason'} or not isinstance(payload['end_reason'], str) or not payload['end_reason']:+ raise RuntimeStoreError('invalid_params')+ db._end_and_bump(conn,+ 'UPDATE sessions SET ended_at=?,end_reason=? WHERE id=? AND ended_at IS NULL',+ (time.time(), payload['end_reason'], session_id), session_id, payload['end_reason'])+ return {'value': None}+++def worker_lifecycle(db, conn, session_id, payload):+ from hermes_state_sessions import classify_session_status+ if payload:+ raise RuntimeStoreError('invalid_params')+ row = conn.execute("SELECT role,tool_calls IS NOT NULL AS has_tool_calls,finish_reason "+ "FROM messages WHERE session_id=? ORDER BY id DESC LIMIT 1", (session_id,)).fetchone()+ value = classify_session_status(role=row['role'], has_tool_calls=bool(row['has_tool_calls']),+ finish_reason=row['finish_reason']) if row else 'empty'+ return {'value': value}+++WORKER_LIFECYCLE_HANDLERS = {+ 'session.create': worker_create,+ 'session.end': worker_end,+ 'session.lifecycle': worker_lifecycle,+}+++def insert_session_row_in_transaction(+ self, conn, session_id, source, model=None, model_config=None,+ system_prompt=None, user_id=None, session_key=None, chat_id=None,+ chat_type=None, thread_id=None, parent_session_id=None, cwd=None,+ profile_name=None, git_repo_root=None, origin_json=None, display_name=None):+ """Connection-taking body of the keep-existing constructor upsert.++ The ordinary constructor should delegate here too. Worker identity is+ validated before entry; this helper never opens or commits a DB.+ """+ from hermes_state_sessions import _UPSERT_KEEP_EXISTING_SQL+ if not (profile_name or "").strip():+ profile_name = self._own_profile_name()+ system_prompt_hash = self._store_system_prompt(conn, system_prompt)+ conn.execute(+ """INSERT INTO sessions (+ id, source, user_id, session_key, chat_id, chat_type, thread_id,+ model, model_config, system_prompt, system_prompt_hash,+ parent_session_id, cwd, profile_name, git_repo_root,+ origin_json, display_name, started_at+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(id) DO UPDATE SET+ model = COALESCE(sessions.model, excluded.model),+ model_config = CASE+ WHEN excluded.model_config IS NOT NULL+ AND json_type(+ sessions.model_config, '$._reset_from'+ ) IS NOT NULL+ AND json_remove(+ sessions.model_config, '$._reset_from'+ ) = '{}'+ THEN json_set(+ excluded.model_config,+ '$._reset_from',+ json_extract(+ sessions.model_config, '$._reset_from'+ )+ )+ ELSE COALESCE(+ sessions.model_config, excluded.model_config+ )+ END,+ system_prompt_hash = COALESCE(+ sessions.system_prompt_hash,+ excluded.system_prompt_hash+ ),+ system_prompt = CASE+ WHEN sessions.system_prompt_hash IS NULL+ AND excluded.system_prompt_hash IS NOT NULL+ THEN NULL+ ELSE sessions.system_prompt+ END,+""" + _UPSERT_KEEP_EXISTING_SQL,+ (+ session_id, source, user_id, session_key, chat_id, chat_type, thread_id, model,+ json.dumps(model_config) if model_config else None, system_prompt_hash,+ parent_session_id, cwd, profile_name, git_repo_root, origin_json, display_name,+ time.time(),+ ),+ )+ if system_prompt_hash is not None:+ self._delete_unreferenced_system_prompts(conn)+ if parent_session_id:+ self._inherit_parent_session_metadata(conn, session_id)diff --git a/tests/state/test_runtime_worker_lifecycle.py b/tests/state/test_runtime_worker_lifecycle.pynew file mode 100644index 00000000000..e31c45fb378--- /dev/null+++ b/tests/state/test_runtime_worker_lifecycle.py@@ -0,0 +1,85 @@+"""Worker lifecycle parity on reserved rows; compose the documented parent hooks."""+import pytest++from agent.runtime_session_store import RuntimeSessionStore, WorkerPersistenceError+from hermes_state import SessionDB+from hermes_state_runtime import (+ RuntimeStoreError, begin_runtime_epoch, mutate_worker_execution, register_worker_execution,+)+++def setup_store(tmp_path):+ db = SessionDB(tmp_path / 'state.db')+ db.create_session('owned', 'cli', cwd='/reserved', profile_name='fixture')+ db.create_session('foreign', 'cli', system_prompt='private')+ epoch = begin_runtime_epoch(db, instance_id='fixture')+ scope = dict(epoch=epoch, execution_id='worker', session_id='owned', generation=0)+ register_worker_execution(db, **scope, kind='compute', adoption_secret='private')+ store = RuntimeSessionStore(lambda method, **p: mutate_worker_execution(db, **p), scope, tmp_path / 'outbox')+ return db, store, scope+++def test_reserved_constructor_backfill_and_end_are_receipted(tmp_path):+ db, store, scope = setup_store(tmp_path)+ try:+ assert store.create_session('owned', 'cli', model='requested', system_prompt='prefix',+ model_config={'max_iterations': 5}, cwd='/reserved',+ profile_name='fixture') == 'owned'+ assert db.get_session('owned')['model'] == 'requested'+ assert db.get_session('owned')['system_prompt'] == 'prefix'+ store.create_session('owned', 'cli', model='ignored', system_prompt='ignored',+ model_config={'max_iterations': 10})+ assert db.get_session('owned')['model'] == 'requested'+ assert db.get_session_model_config_value('owned', 'max_iterations') == 5+ assert store.session_lifecycle_statuses(['owned']) == {'owned': 'empty'}+ with pytest.raises(WorkerPersistenceError, match='permission_denied'):+ store.create_session('foreign', 'cli')+ for payload in ({'source': 'cli', 'parent_session_id': 'foreign'},+ {'source': 'cli', 'profile_name': 'foreign'},+ {'source': 'cli', 'cwd': '/foreign'},+ {'source': 'cli', 'model_config': {'_delegate_from': 'foreign'}}):+ with pytest.raises(RuntimeStoreError, match='permission_denied|invalid_params'):+ mutate_worker_execution(db, **scope, sequence=store.journal['next_sequence'],+ operation='session.create', payload=payload)+ store.append_messages_batch('owned', [{'role': 'assistant', 'content': 'done', 'finish_reason': 'stop'}])+ assert store.session_lifecycle_statuses(['owned']) == db.session_lifecycle_statuses(['owned'])+ original = store.rpc+ def lost_ack(method, **params):+ original(method, **params)+ raise TimeoutError('lost-ack')+ store.rpc = lost_ack+ with pytest.raises(TimeoutError, match='lost-ack'):+ store.end_session('owned', 'agent_close')+ ended = db.get_session('owned')+ store.rpc = original+ store.retry_pending()+ store.end_session('owned', 'late-reason')+ assert db.get_session('owned')['ended_at'] == ended['ended_at']+ assert db.get_session('owned')['end_reason'] == 'agent_close'+ assert store.finish()['status'] == 'terminal'+ assert db.get_session('foreign')['system_prompt'] == 'private'+ finally:+ store.close()+ db.close()+++def test_late_finalizers_cannot_mutate_successor_or_foreign_rows(tmp_path):+ db, store, scope = setup_store(tmp_path)+ try:+ store.end_session('owned', 'agent_close')+ db.reopen_session('owned')+ db._execute_write(lambda conn: conn.execute(+ 'UPDATE sessions SET runtime_generation=runtime_generation+1 WHERE id=?', ('owned',)))+ # Even replay of a formerly successful receipt must revalidate generation.+ for sequence in (1, 2):+ with pytest.raises(RuntimeStoreError, match='stale_generation'):+ mutate_worker_execution(db, **scope, sequence=sequence,+ operation='session.end', payload={'end_reason': 'agent_close'})+ with pytest.raises(RuntimeStoreError, match='permission_denied'):+ mutate_worker_execution(db, **dict(scope, session_id='foreign'), sequence=2,+ operation='session.end', payload={'end_reason': 'agent_close'})+ assert db.get_session('owned')['ended_at'] is None+ assert db.get_session('foreign')['ended_at'] is None+ finally:+ store.close()+ db.close()