From 606589349446c0f7fe05b159780df2ed9f88a6cf Mon Sep 17 00:00:00 2001 From: Andrew Park Date: Sun, 29 Nov 2026 04:22:30 +0000 Subject: [PATCH 1/3] test: prompt_agent leaves its A2A conversation closed however it ends A step that raises mid-turn leaves the conversation active and pending, a failed agent turn is recorded completed, a closed conversation still takes a new task, and a retried step's reply completes the dead attempt's turn. A conversation closed before the first turn must fail the step without sending anything. A retry after a run killed before its close must cancel the task that run left and complete its own. Two runs racing to create the conversation must share one record, and a close that fails in the step's cleanup must not replace the step's own exception. --- .../test_prompt_agent_conversation_close.py | 276 ++++++++++++++++++ 1 file changed, 276 insertions(+) create mode 100644 tst/unit/task_step/test_prompt_agent_conversation_close.py diff --git a/tst/unit/task_step/test_prompt_agent_conversation_close.py b/tst/unit/task_step/test_prompt_agent_conversation_close.py new file mode 100644 index 000000000..527ea5dc8 --- /dev/null +++ b/tst/unit/task_step/test_prompt_agent_conversation_close.py @@ -0,0 +1,276 @@ +"""A prompt step's A2A conversation record: however the step ends, it is closed and off the pending worklist; a closed +conversation takes no new turn; and each turn records how the agent's reply ended.""" + +import asyncio +from contextlib import nullcontext +from unittest.mock import MagicMock + +import pytest +from a2a.types import TaskState + +from agent_env.a2a_agent import conversation_store +from agent_env.task_step.context import DeployedAgent, TaskStepContext +from agent_env.task_step.task_steps import prompt_agent as pa_mod +from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep + +HUMAN_URL = "http://human-peer" + + +def _reply(state, text): + return {"status": {"state": state, "message": {"parts": [{"kind": "text", "text": text}]}}} + + +@pytest.fixture +def sent(monkeypatch, local_stores): + """Every message the step sends, as (url, text); the store is the real local one.""" + cfg = MagicMock() + cfg.get_model_params.return_value = {} + cfg.get_default_human_a2a_url.return_value = HUMAN_URL + monkeypatch.setattr(pa_mod, "get_config", lambda: cfg) + messages = [] + + async def send(url, parts, message_id, context_id, timeout): + messages.append((url, parts[0].get("text"))) + return f"{url}#{len(messages)}", None + + monkeypatch.setattr(pa_mod.protocol, "send_a2a_message", send) + return messages + + +def _poll(monkeypatch, poll): + monkeypatch.setattr(pa_mod.protocol, "poll_a2a_task", poll) + + +def _context(): + ctx = TaskStepContext(instance_id="ti-1") + ctx.deployed_agents.append( + DeployedAgent(agent_name="solver", api_url="http://solver", a2a_url="http://solver", a2a_card={}) + ) + return ctx + + +def _conversation(ctx): + return conversation_store.get_conversation(ctx.metadata["a2a_conversations"]["solve"]) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("error", [TimeoutError, pytest.param(RuntimeError, id="any-exception")]) +async def test_a_step_that_raises_mid_turn_leaves_its_conversation_closed_and_off_the_worklist( + monkeypatch, sent, error): + async def poll(url, task_id, timeout, interval, **_): + raise error("the agent's turn did not end") + + _poll(monkeypatch, poll) + ctx = _context() + + with pytest.raises(error): + await PromptAgentTaskStep(id="solve", version=None, prompt="hi", agent_name="solver").execute(ctx) + + conversation = _conversation(ctx) + assert (conversation["status"], conversation["pending"]) == ("closed", False) + assert [t["state"] for t in conversation["a2a_tasks"]] == [TaskState.canceled.value] + assert conversation_store.list_pending() == [] + + +@pytest.mark.asyncio +async def test_a_failed_agent_turn_is_recorded_failed_not_completed(monkeypatch, sent): + async def poll(url, task_id, timeout, interval, **_): + return _reply(TaskState.failed, "it broke") + + _poll(monkeypatch, poll) + ctx = _context() + + try: + await PromptAgentTaskStep(id="solve", version=None, prompt="hi", agent_name="solver").execute(ctx) + except Exception: + pass # whether a failed turn fails the step is not this test's concern + + assert [t["state"] for t in _conversation(ctx)["a2a_tasks"]] == [TaskState.failed.value] + + +@pytest.mark.asyncio +async def test_a_conversation_the_human_closes_while_answering_takes_no_further_turn(monkeypatch, sent): + ctx = _context() + + async def poll(url, task_id, timeout, interval, **_): + if url == HUMAN_URL: + conversation_store.mark_closed(ctx.metadata["a2a_conversations"]["solve"]) + return _reply(TaskState.completed, "one more thing") + return _reply(TaskState.completed, "answer") + + _poll(monkeypatch, poll) + + await PromptAgentTaskStep(id="solve", version=None, prompt="hi", agent_name="solver", + max_conversation_turns=2).execute(ctx) + + conversation = _conversation(ctx) + assert [t["state"] for t in conversation["a2a_tasks"]] == [TaskState.completed.value] + assert conversation["pending"] is False + assert sent == [("http://solver", "hi"), (HUMAN_URL, "answer")] + + +def test_a_closed_conversation_refuses_a_new_a2a_task(local_stores): + conversation_store.create_conversation("conv-1", "ti-1", "human_agent", "solver") + conversation_store.mark_closed("conv-1") + + refused = conversation_store.add_a2a_task("conv-1", [{"kind": "text", "text": "late"}], "late-task", "agent") + + conversation = conversation_store.get_conversation("conv-1") + assert refused is None + assert (conversation["a2a_tasks"], conversation["messages"], conversation["pending"]) == ([], [], False) + + +@pytest.mark.asyncio +async def test_a_retried_step_gets_its_own_replies_on_its_own_turns(monkeypatch, sent): + attempts = iter(["times out", "answers"]) + attempt = None + + async def poll(url, task_id, timeout, interval, **_): + if attempt == "times out": + raise TimeoutError("the agent's turn did not end") + if url == HUMAN_URL: + return _reply(TaskState.completed, "and then?") + return _reply(TaskState.completed, "answer") + + _poll(monkeypatch, poll) + ctx = _context() + step = PromptAgentTaskStep(id="solve", version=None, prompt="hi", agent_name="solver", context_id="session", + max_conversation_turns=2) + + attempt = next(attempts) + with pytest.raises(TimeoutError): + await step.execute(ctx) + attempt = next(attempts) + await step.execute(ctx) + + conversation = _conversation(ctx) + assert [t["state"] for t in conversation["a2a_tasks"]] == [ + TaskState.canceled.value, TaskState.completed.value, TaskState.completed.value, + ] + assert conversation["status"] == "closed" + assert [url for url, _ in sent] == ["http://solver", "http://solver", HUMAN_URL, "http://solver"] + + +@pytest.mark.asyncio +async def test_a_conversation_closed_before_the_first_turn_fails_the_step_and_sends_nothing(monkeypatch, sent): + async def poll(url, task_id, timeout, interval, **_): + return _reply(TaskState.completed, "answer") + + _poll(monkeypatch, poll) + create = conversation_store.create_conversation + + def created_then_closed_by_the_peer(conversation_id, **fields): + doc = create(conversation_id=conversation_id, **fields) + conversation_store.mark_closed(conversation_id) + return doc + + monkeypatch.setattr(conversation_store, "create_conversation", created_then_closed_by_the_peer) + ctx = _context() + + with pytest.raises(RuntimeError, match="closed before the first turn"): + await PromptAgentTaskStep(id="solve", version=None, prompt="hi", agent_name="solver").execute(ctx) + + assert sent == [] + assert _conversation(ctx)["a2a_tasks"] == [] + + +@pytest.mark.asyncio +async def test_a_retry_after_a_killed_run_cancels_the_task_it_left_and_completes_its_own(monkeypatch, sent): + attempt = "killed" + + async def poll(url, task_id, timeout, interval, **_): + if attempt == "killed": + raise TimeoutError("the process died mid-turn") + return _reply(TaskState.completed, "answer") + + _poll(monkeypatch, poll) + ctx = _context() + step = PromptAgentTaskStep(id="solve", version=None, prompt="hi", agent_name="solver", context_id="session") + + with monkeypatch.context() as killed_before_its_close: + killed_before_its_close.setattr(conversation_store, "mark_closed", lambda conversation_id: None) + with pytest.raises(TimeoutError): + await step.execute(ctx) + assert [t["state"] for t in _conversation(ctx)["a2a_tasks"]] == [TaskState.working.value] + attempt = "retried" + await step.execute(ctx) + + conversation = _conversation(ctx) + left, own = conversation["a2a_tasks"] + assert (left["state"], left.get("response_message_idx")) == (TaskState.canceled.value, None) + assert own["state"] == TaskState.completed.value + assert conversation["messages"][own["response_message_idx"]]["parts"] == [{"kind": "text", "text": "answer"}] + assert conversation["status"] == "closed" + + +@pytest.mark.asyncio +async def test_two_runs_racing_to_create_the_conversation_share_one_record(monkeypatch, sent): + async def poll(url, task_id, timeout, interval, **_): + return _reply(TaskState.completed, "answer") + + _poll(monkeypatch, poll) + conversation_store.ensure_indexes() + create = conversation_store.create_conversation + + def the_other_run_creates_it_first(**fields): + create(**fields) + return create(**fields) + + monkeypatch.setattr(conversation_store, "create_conversation", the_other_run_creates_it_first) + ctx = _context() + + await PromptAgentTaskStep(id="solve", version=None, prompt="hi", agent_name="solver").execute(ctx) + + conversation = _conversation(ctx) + assert [t["state"] for t in conversation["a2a_tasks"]] == [TaskState.completed.value] + assert conversation["status"] == "closed" + + +@pytest.mark.asyncio +async def test_a_close_that_fails_does_not_hide_why_the_step_failed(monkeypatch, sent): + async def poll(url, task_id, timeout, interval, **_): + raise TimeoutError("the agent's turn did not end") + + def store_unreachable(conversation_id): + raise ConnectionError("the store is down") + + _poll(monkeypatch, poll) + monkeypatch.setattr(conversation_store, "mark_closed", store_unreachable) + + with pytest.raises(TimeoutError): + await PromptAgentTaskStep(id="solve", version=None, prompt="hi", agent_name="solver").execute(_context()) + + +@pytest.mark.asyncio +async def test_a_step_cancelled_while_ending_its_live_trajectory_leaves_its_conversation_closed(monkeypatch, sent): + async def poll(url, task_id, timeout, interval, **_): + return _reply(TaskState.completed, "answer") + + ending = asyncio.Event() + + class SlowToEndLiveTurns: + def __init__(self, *args, **kwargs): + pass + + def following(self, turn_id): + return nullcontext(None) + + async def end(self): + ending.set() + await asyncio.Event().wait() + + _poll(monkeypatch, poll) + monkeypatch.setattr(PromptAgentTaskStep, "_live_trajectory_target", lambda self, *args: ("live", None, "prefix/")) + monkeypatch.setattr(pa_mod, "LiveTurns", SlowToEndLiveTurns) + ctx = _context() + + step = asyncio.create_task( + PromptAgentTaskStep(id="solve", version=None, prompt="hi", agent_name="solver").execute(ctx)) + await asyncio.wait_for(ending.wait(), timeout=5) + step.cancel() + with pytest.raises(asyncio.CancelledError): + await step + + conversation = _conversation(ctx) + assert (conversation["status"], conversation["pending"]) == ("closed", False) + assert conversation_store.list_pending() == [] From 42f828139413a60192b737ee809e549b51ff1419 Mon Sep 17 00:00:00 2001 From: Andrew Park Date: Sun, 29 Nov 2026 04:55:51 +0000 Subject: [PATCH 2/3] fix: prompt_agent closes its A2A conversation however it ends The step closed its conversation only after the loop returned normally, so a timeout, cancellation or any other exception left it active, and pending when the turn was recorded, for list_pending to keep listing. The close now runs in the loop's finally, and the conversation is created just before that try. A store error in that close is logged, so it never replaces the step's own exception. add_a2a_task appended to a closed conversation, so a turn recorded after a peer closed it, or a peer recording a message after the step closed it, left a working task no one would end. It now refuses unless the conversation is active, read under the same rev swap, and returns None. The step then stops without sending the turn. A refusal of the first turn fails the step, since the agent was sent nothing and an empty answer must not pass as one. complete_a2a_task recorded every reply as completed. It takes the state the responder's task ended in, and the step passes the agent's. A re-run of the step under the same instance id (a retry, or a later step continuing the same context_id) found its conversation through create_conversation raising DuplicateKeyError. Only the unique index that conversation_store.ensure_indexes creates raises it, and nothing in this repository calls ensure_indexes, so on a store without the index a re-run inserted a second document with the same conversation_id. The step now calls reopen first, which reactivates the conversation and cancels any task an earlier run left working, and creates it only when reopen finds none. If two runs race to create it, the loser's DuplicateKeyError leads to reopen too. Tests that stub the store return {} from add_a2a_task, a recorded turn, and stub reopen with the other calls. The user-side test that pinned a failed turn as completed now expects failed. --- src/agent_env/a2a_agent/conversation_store.py | 39 +++++++---- .../task_step/task_steps/prompt_agent.py | 64 ++++++++++++------- .../task_step/prompt_agent_file_parts_test.py | 4 +- tst/unit/task_step/prompt_agent_rig.py | 4 +- tst/unit/task_step/test_prompt_agent.py | 4 +- .../test_prompt_agent_builtin_tools.py | 4 +- ...st_prompt_agent_conversation_tool_calls.py | 4 +- .../test_prompt_agent_human_default.py | 4 +- .../test_prompt_agent_max_output_tokens.py | 4 +- .../task_step/test_prompt_agent_snapshots.py | 2 +- .../test_prompt_agent_unreachable.py | 4 +- tst/unit/task_step/test_prompt_agent_usage.py | 4 +- .../task_step/test_prompt_agent_user_side.py | 2 +- tst/unit/task_step/test_recorded_models.py | 4 +- 14 files changed, 92 insertions(+), 55 deletions(-) diff --git a/src/agent_env/a2a_agent/conversation_store.py b/src/agent_env/a2a_agent/conversation_store.py index 8721e4bf4..c0cbada63 100644 --- a/src/agent_env/a2a_agent/conversation_store.py +++ b/src/agent_env/a2a_agent/conversation_store.py @@ -73,7 +73,9 @@ def create_conversation( target="human_agent". Raises `agent_env.store.DuplicateKeyError` if `conversation_id` already - exists — callers should treat that as "use the existing conversation." + exists and the store has the unique index `ensure_indexes` creates. A store + without that index inserts a second document with the same id, so a caller + that may re-run looks for the conversation first (`reopen`). """ now = datetime.now(timezone.utc) doc = { @@ -139,12 +141,15 @@ def add_a2a_task( (never rewritten), so no entry is dropped. Returns the post-update conversation doc, or None if `conversation_id` - doesn't exist. + doesn't exist or is no longer `active`. The status is read under the same + swap, so a close that lands first refuses the append rather than racing it. """ now = datetime.now(timezone.utc) new_message = _message(role, parts, now, env_clock) - def _mutate(doc: dict) -> UpdateSpec: + def _mutate(doc: dict) -> Optional[UpdateSpec]: + if doc.get("status") != "active": + return None idx = len(doc.get("messages", [])) new_a2a_task = { "a2a_task_id": a2a_task_id, @@ -171,8 +176,10 @@ def complete_a2a_task( parts: list[dict], role: str, env_clock: Optional[list[dict]] = None, + state: TaskState = TaskState.completed, ) -> Optional[dict]: - """Append a responder-side message and complete the oldest working a2a_task. + """Append a responder-side message and end the oldest working a2a_task in `state`, + the terminal state the responder's own task reached. Called when the responder replies. The responder's role depends on the conversation direction: @@ -226,7 +233,7 @@ def complete_a2a_task( _REV, rev_precondition(existing, _REV) ) if oldest_working_idx is not None: - spec.set[f"a2a_tasks.{oldest_working_idx}.state"] = TaskState.completed.value + spec.set[f"a2a_tasks.{oldest_working_idx}.state"] = TaskState(state).value spec.set[f"a2a_tasks.{oldest_working_idx}.response_message_idx"] = idx spec.set[f"a2a_tasks.{oldest_working_idx}.ended_at"] = now.isoformat() filter_ = filter_.where( @@ -304,15 +311,14 @@ def cancel_a2a_task( ) -def mark_closed(conversation_id: str) -> Optional[dict]: - """Set `status=closed` and cancel any working a2a_tasks. +def _end_working_tasks(conversation_id: str, status: str) -> Optional[dict]: + """Set `status`, clear `pending` and cancel any working a2a_tasks. Reads the conversation, cancels working a2a_tasks in Python, and writes the transformed array back under a `rev` compare-and-swap so a concurrently appended a2a_task (e.g. a `start_a2a_task` push that lands between the read and the write) is not clobbered by this whole-array write. On a lost swap we - re-read and re-transform; a task that landed mid-close is then canceled too, - which is correct for a terminal close. + re-read and re-transform; a task that landed mid-write is then canceled too. Returns the post-update conversation doc, or None if not found. """ @@ -338,7 +344,7 @@ def mark_closed(conversation_id: str) -> Optional[dict]: ), UpdateSpec( set={ - "status": "closed", + "status": status, "pending": False, "updated_at_utc": now, "a2a_tasks": new_tasks, @@ -349,10 +355,21 @@ def mark_closed(conversation_id: str) -> Optional[dict]: if result is not None: return result raise RuntimeError( - f"mark_closed: rev CAS did not converge for conversation_id={conversation_id}" + f"set status {status}: rev CAS did not converge for conversation_id={conversation_id}" ) +def mark_closed(conversation_id: str) -> Optional[dict]: + """Set `status=closed` and cancel any working a2a_tasks. Returns the post-update doc, or None if not found.""" + return _end_working_tasks(conversation_id, "closed") + + +def reopen(conversation_id: str) -> Optional[dict]: + """Set `status=active` for a re-run of the conversation's owner, canceling any working a2a_tasks an earlier + run left, so the next reply completes the re-run's own task. Returns the post-update doc, or None if not found.""" + return _end_working_tasks(conversation_id, "active") + + def list_pending(limit: int = 50) -> list[dict]: """Return active conversations awaiting a user reply, most-recently-updated first. diff --git a/src/agent_env/task_step/task_steps/prompt_agent.py b/src/agent_env/task_step/task_steps/prompt_agent.py index 82cc1e3b4..2a4a4fc62 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -113,6 +113,10 @@ def _parse_structured_output(text: str) -> Optional[dict]: return last +class _ConversationClosed(Exception): + """The store refused the turn because someone closed the conversation, so the message is not sent.""" + + def _duplicates_prompt_text(parts: list[dict], prompt_text: Optional[str]) -> bool: """True when ``parts`` is exactly the single text part already persisted as ``PromptResponse.prompt_text`` — i.e. the first conversation turn of a @@ -653,22 +657,6 @@ async def _converse( conversation_id = f"{self.context_id}-{run_component}-{len(run_component)}" else: conversation_id = solver_context_id - try: - conversation_store.create_conversation( - conversation_id=conversation_id, - task_instance_id=context.instance_id or "", - source_agent_name=self.user_agent_name, - target_agent_name=self.agent_name, - ) - except DuplicateKeyError: - # reuse a pre-existing conversation on retry/resume (store raises agent_env.store.DuplicateKeyError, not pymongo's) - logger.info(f"Reusing existing conversation {conversation_id} on re-run") - context.metadata.setdefault("a2a_conversations", {})[self.id] = conversation_id - logger.info( - f"Started multi-turn conversation {conversation_id} (max {self.max_conversation_turns} turns) " - f"between {self.user_agent_name} and {self.agent_name}" - ) - current_user_parts = initial_parts clock_envs = [d for d in context.deployed_envs if d.supports(EXT_CLOCK_URI, "state")] # What comes due for the agent's role on these envs (notifications/v1) opens its next message. @@ -715,6 +703,25 @@ async def _converse( # Set by a user's done with a message: the agent answers it, then the conversation ends for this reason. end_after: Optional[str] = None + # A re-run under the same instance id (a retry) takes back the conversation its earlier run closed. + if conversation_store.reopen(conversation_id) is not None: + logger.info(f"Reusing existing conversation {conversation_id} on re-run") + else: + try: + conversation_store.create_conversation( + conversation_id=conversation_id, + task_instance_id=context.instance_id or "", + source_agent_name=self.user_agent_name, + target_agent_name=self.agent_name, + ) + except DuplicateKeyError: # another run created it after our reopen found none + conversation_store.reopen(conversation_id) + context.metadata.setdefault("a2a_conversations", {})[self.id] = conversation_id + logger.info( + f"Started multi-turn conversation {conversation_id} (max {self.max_conversation_turns} turns) " + f"between {self.user_agent_name} and {self.agent_name}" + ) + try: for turn in range(self.max_conversation_turns): # `target_a2a_task_id` is the client A2A message id sent to the target @@ -726,14 +733,16 @@ async def _converse( # The turn records the objects' own URLs, and only once the parts are ready to send, so an # object the agent can't be sent leaves no turn waiting. def record_turn() -> None: - sent_to_target.update(_file_uris(current_user_parts)) - conversation_store.add_a2a_task( + recorded = conversation_store.add_a2a_task( conversation_id=conversation_id, parts=current_user_parts, a2a_task_id=target_a2a_task_id, role="user", **sent_clock, ) + if recorded is None: + raise _ConversationClosed() + sent_to_target.update(_file_uris(current_user_parts)) # Turn 0 of a prompt-mode step re-sends exactly the text already # persisted as PromptResponse.prompt_text; store a None placeholder # instead of a second copy so the doc doesn't carry the prompt twice. @@ -753,6 +762,13 @@ def record_turn() -> None: poll_interval_seconds=self.poll_interval_seconds, before_send=record_turn, on_sent=live_turn.follow if live_turn else None, ) + except _ConversationClosed: + if turn == 0: + raise RuntimeError( + f"conversation {conversation_id} was closed before the first turn; " + "nothing was sent to the agent") from None + logger.info(f"Conversation {conversation_id} was closed before turn {turn+1}; ending multi-turn") + break except (TimeoutError, asyncio.CancelledError): usage.cut_off(ModelRole.SOLVER) raise @@ -769,6 +785,7 @@ def record_turn() -> None: conversation_id=conversation_id, parts=agent_response_parts, role="agent", + state=target_state, **(await self._env_clock(clock_envs)), ) @@ -857,6 +874,13 @@ def record_turn() -> None: atif_copies.cancel() raise finally: + # Before any await, so a cancellation landing in this cleanup can't skip it. + try: + final_conv = conversation_store.get_conversation(conversation_id) + if final_conv and final_conv.get("status") == "active": + conversation_store.mark_closed(conversation_id) + except Exception: + logger.warning(f"Could not close conversation {conversation_id}", exc_info=True) # On failure too, so a reader of the last turn knows no other follows. if live_turns is not None: await live_turns.end() @@ -865,10 +889,6 @@ def record_turn() -> None: await self._persist_env_trigger_state(context) - final_conv = conversation_store.get_conversation(conversation_id) - if final_conv and final_conv.get("status") == "active": - conversation_store.mark_closed(conversation_id) - if trig_ext and triggers_registered: # best-effort firing-log readback (provenance only; never fails the run) try: async with httpx.AsyncClient() as client: diff --git a/tst/unit/task_step/prompt_agent_file_parts_test.py b/tst/unit/task_step/prompt_agent_file_parts_test.py index cb1d196cb..cdccc9da9 100644 --- a/tst/unit/task_step/prompt_agent_file_parts_test.py +++ b/tst/unit/task_step/prompt_agent_file_parts_test.py @@ -29,8 +29,8 @@ def store(tmp_path): def recorded(monkeypatch): """The parts the run records of each turn.""" turns = [] - monkeypatch.setattr(pa.conversation_store, "add_a2a_task", lambda *a, parts, **kw: turns.append(parts)) - for fn in ("create_conversation", "complete_a2a_task", "mark_closed", "get_conversation"): + monkeypatch.setattr(pa.conversation_store, "add_a2a_task", lambda *a, parts, **kw: turns.append(parts) or {}) + for fn in ("reopen", "create_conversation", "complete_a2a_task", "mark_closed", "get_conversation"): monkeypatch.setattr(pa.conversation_store, fn, lambda *a, **kw: None) return turns diff --git a/tst/unit/task_step/prompt_agent_rig.py b/tst/unit/task_step/prompt_agent_rig.py index 1d3602583..466e6f2df 100644 --- a/tst/unit/task_step/prompt_agent_rig.py +++ b/tst/unit/task_step/prompt_agent_rig.py @@ -12,14 +12,14 @@ from agent_env.task_step.task_steps import prompt_agent as pa #: The conversation store calls a prompt step makes, which these tests keep from reaching a store. -CONVERSATION_STORE_CALLS = ("create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", +CONVERSATION_STORE_CALLS = ("reopen", "create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation") AGENT_URL = "http://agent.test" def quiet_conversations(monkeypatch: pytest.MonkeyPatch) -> None: for name in CONVERSATION_STORE_CALLS: - monkeypatch.setattr(pa.conversation_store, name, lambda *args, **kwargs: None) + monkeypatch.setattr(pa.conversation_store, name, lambda *args, **kwargs: {}) def route_clients(monkeypatch: pytest.MonkeyPatch, transport: httpx.AsyncBaseTransport, **options: Any) -> None: diff --git a/tst/unit/task_step/test_prompt_agent.py b/tst/unit/task_step/test_prompt_agent.py index a03948399..3e6928eaf 100644 --- a/tst/unit/task_step/test_prompt_agent.py +++ b/tst/unit/task_step/test_prompt_agent.py @@ -246,9 +246,9 @@ async def _one_turn(monkeypatch, tmp_path, extension: dict, answer: Callable[[di sent and the store it wrote to.""" store = LocalFilesystemObjectStore(str(tmp_path)) configure(object_store=store) - for fn in ("create_conversation", "add_a2a_task", "complete_a2a_task", + for fn in ("reopen", "create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"): - monkeypatch.setattr(pa.conversation_store, fn, lambda *a, **kw: None) + monkeypatch.setattr(pa.conversation_store, fn, lambda *a, **kw: {}) requests: list[dict] = [] def trajectory(request: httpx.Request) -> httpx.Response: diff --git a/tst/unit/task_step/test_prompt_agent_builtin_tools.py b/tst/unit/task_step/test_prompt_agent_builtin_tools.py index f441bb811..3dcefe492 100644 --- a/tst/unit/task_step/test_prompt_agent_builtin_tools.py +++ b/tst/unit/task_step/test_prompt_agent_builtin_tools.py @@ -22,8 +22,8 @@ def posted(monkeypatch): cfg.get_model_params.return_value = {} cfg.get_model_for_role.return_value = None monkeypatch.setattr(pa_mod, "get_config", lambda: cfg) - for fn in ("create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"): - monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: None) + for fn in ("reopen", "create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"): + monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: {}) configs = [] async def post_agent_config(url, fields, headers=None): diff --git a/tst/unit/task_step/test_prompt_agent_conversation_tool_calls.py b/tst/unit/task_step/test_prompt_agent_conversation_tool_calls.py index 2e42a5fb5..07101dc81 100644 --- a/tst/unit/task_step/test_prompt_agent_conversation_tool_calls.py +++ b/tst/unit/task_step/test_prompt_agent_conversation_tool_calls.py @@ -21,8 +21,8 @@ def _wire(monkeypatch, solver_tool_calls: list): cfg.get_model_params.return_value = {} cfg.get_default_human_a2a_url.return_value = "http://hub/a2a/human" monkeypatch.setattr(pa_mod, "get_config", lambda: cfg) - for fn in ("create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"): - monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: None) + for fn in ("reopen", "create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"): + monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: {}) solver_turns = iter(solver_tool_calls) async def post_agent_config(url, fields, headers=None): diff --git a/tst/unit/task_step/test_prompt_agent_human_default.py b/tst/unit/task_step/test_prompt_agent_human_default.py index a31b10721..8bc66d741 100644 --- a/tst/unit/task_step/test_prompt_agent_human_default.py +++ b/tst/unit/task_step/test_prompt_agent_human_default.py @@ -13,9 +13,9 @@ def _wire(monkeypatch, cfg): monkeypatch.setattr(pa_mod, "get_config", lambda: cfg) - for fn in ("create_conversation", "add_a2a_task", "complete_a2a_task", + for fn in ("reopen", "create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"): - monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: None) + monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: {}) async def send(url, parts, message_id, context_id, timeout): return "task-1", None diff --git a/tst/unit/task_step/test_prompt_agent_max_output_tokens.py b/tst/unit/task_step/test_prompt_agent_max_output_tokens.py index 543a3ff29..ae2510800 100644 --- a/tst/unit/task_step/test_prompt_agent_max_output_tokens.py +++ b/tst/unit/task_step/test_prompt_agent_max_output_tokens.py @@ -19,8 +19,8 @@ def posted(monkeypatch): cfg.get_model_params.return_value = {} cfg.get_model_for_role.return_value = None monkeypatch.setattr(pa_mod, "get_config", lambda: cfg) - for fn in ("create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"): - monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: None) + for fn in ("reopen", "create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"): + monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: {}) configs = [] async def post_agent_config(url, fields, headers=None): diff --git a/tst/unit/task_step/test_prompt_agent_snapshots.py b/tst/unit/task_step/test_prompt_agent_snapshots.py index e05c8becf..e17d35efb 100644 --- a/tst/unit/task_step/test_prompt_agent_snapshots.py +++ b/tst/unit/task_step/test_prompt_agent_snapshots.py @@ -1259,7 +1259,7 @@ def __init__(self, monkeypatch, *, user_done_at: int | None = None): self.user_done_at = user_done_at self.user_turns = 0 - for fn in ("create_conversation", "add_a2a_task", "complete_a2a_task", + for fn in ("reopen", "create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed"): # `*a` too: the loop calls some of these positionally. monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: {}) diff --git a/tst/unit/task_step/test_prompt_agent_unreachable.py b/tst/unit/task_step/test_prompt_agent_unreachable.py index 52306fcd7..c62e14693 100644 --- a/tst/unit/task_step/test_prompt_agent_unreachable.py +++ b/tst/unit/task_step/test_prompt_agent_unreachable.py @@ -24,8 +24,8 @@ def _wire(monkeypatch, poll): cfg.get_model_params.return_value = {} cfg.get_default_human_a2a_url.return_value = "http://hub/a2a/human" monkeypatch.setattr(pa_mod, "get_config", lambda: cfg) - for fn in ("create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"): - monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: None) + for fn in ("reopen", "create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"): + monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: {}) async def send(url, parts, message_id, context_id, timeout): return f"{url}#task", None diff --git a/tst/unit/task_step/test_prompt_agent_usage.py b/tst/unit/task_step/test_prompt_agent_usage.py index fbda82701..514a54363 100644 --- a/tst/unit/task_step/test_prompt_agent_usage.py +++ b/tst/unit/task_step/test_prompt_agent_usage.py @@ -28,8 +28,8 @@ def _wire(monkeypatch, solver_usage: list, user_usage=None): cfg = MagicMock() cfg.get_model_params.return_value = {} monkeypatch.setattr(pa_mod, "get_config", lambda: cfg) - for fn in ("create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"): - monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: None) + for fn in ("reopen", "create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"): + monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: {}) solver_turns = iter(solver_usage) async def post_agent_config(url, fields, headers=None): diff --git a/tst/unit/task_step/test_prompt_agent_user_side.py b/tst/unit/task_step/test_prompt_agent_user_side.py index 4cd596fba..85e8c1426 100644 --- a/tst/unit/task_step/test_prompt_agent_user_side.py +++ b/tst/unit/task_step/test_prompt_agent_user_side.py @@ -366,7 +366,7 @@ async def test_an_agent_failure_ends_the_run_without_asking_the_user_and_fails_t "status": "closed", "messages": [{"role": "user", "parts": text("plan my week")}, {"role": "agent", "parts": text("one")}, {"role": "user", "parts": text("again")}, {"role": "agent", "parts": text("boom")}], - "a2a_tasks": [("", "completed", 0, 1), ("", "completed", 2, 3)], + "a2a_tasks": [("", "completed", 0, 1), ("", "failed", 2, 3)], } diff --git a/tst/unit/task_step/test_recorded_models.py b/tst/unit/task_step/test_recorded_models.py index ddb0db813..afadb5787 100644 --- a/tst/unit/task_step/test_recorded_models.py +++ b/tst/unit/task_step/test_recorded_models.py @@ -31,8 +31,8 @@ def posted(monkeypatch): cfg.get_model_params.return_value = {} cfg.resolve_model.side_effect = lambda role, **layers: resolve_model(role, **layers) monkeypatch.setattr(pa_mod, "get_config", lambda: cfg) - for fn in ("create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"): - monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: None) + for fn in ("reopen", "create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"): + monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: {}) configs = {} async def post_agent_config(url, fields, headers=None): From fb1f009421a5f0a85127aa68470f6666e4f2a71c Mon Sep 17 00:00:00 2001 From: Andrew Park Date: Sun, 29 Nov 2026 04:58:01 +0000 Subject: [PATCH 3/3] chore: model-check a prompt step's A2A conversation record in tst/formal tst/formal/a2a_conversation holds a TLA+ model of a prompt_agent step's A2A conversation record, the step that owns it, a retry of the step, a process that dies mid-step, and a human peer's endpoint writing the same store. check.sh runs the fixed code, the code before the fix, six mutants and one known gap against six invariants, with the TLC jar pinned by sha256. AGENTS.md says which code the model covers, when to run it and how to read a failure. The known gap: an earlier run's ask that the peer's endpoint records after a retry reopened the conversation sits ahead of the retry's turn, and the retry's reply ends it, because complete_a2a_task ends the oldest working task. --- tst/formal/a2a_conversation/AGENTS.md | 138 +++++++ .../ConversationLifecycle.tla | 349 ++++++++++++++++++ tst/formal/a2a_conversation/before-fix.cfg | 21 ++ tst/formal/a2a_conversation/check.sh | 76 ++++ tst/formal/a2a_conversation/fixed.cfg | 21 ++ .../known-gap-late-peer-record.cfg | 21 ++ .../mutant-close-after-live-end.cfg | 21 ++ .../a2a_conversation/mutant-no-end-state.cfg | 21 ++ .../a2a_conversation/mutant-no-finally.cfg | 21 ++ .../mutant-no-first-turn-failure.cfg | 21 ++ .../mutant-no-guard-no-peer-close.cfg | 21 ++ .../a2a_conversation/mutant-no-guard.cfg | 21 ++ .../a2a_conversation/mutant-no-reopen.cfg | 21 ++ .../mutant-reopen-keeps-left-tasks.cfg | 21 ++ 14 files changed, 794 insertions(+) create mode 100644 tst/formal/a2a_conversation/AGENTS.md create mode 100644 tst/formal/a2a_conversation/ConversationLifecycle.tla create mode 100644 tst/formal/a2a_conversation/before-fix.cfg create mode 100755 tst/formal/a2a_conversation/check.sh create mode 100644 tst/formal/a2a_conversation/fixed.cfg create mode 100644 tst/formal/a2a_conversation/known-gap-late-peer-record.cfg create mode 100644 tst/formal/a2a_conversation/mutant-close-after-live-end.cfg create mode 100644 tst/formal/a2a_conversation/mutant-no-end-state.cfg create mode 100644 tst/formal/a2a_conversation/mutant-no-finally.cfg create mode 100644 tst/formal/a2a_conversation/mutant-no-first-turn-failure.cfg create mode 100644 tst/formal/a2a_conversation/mutant-no-guard-no-peer-close.cfg create mode 100644 tst/formal/a2a_conversation/mutant-no-guard.cfg create mode 100644 tst/formal/a2a_conversation/mutant-no-reopen.cfg create mode 100644 tst/formal/a2a_conversation/mutant-reopen-keeps-left-tasks.cfg diff --git a/tst/formal/a2a_conversation/AGENTS.md b/tst/formal/a2a_conversation/AGENTS.md new file mode 100644 index 000000000..d81f86348 --- /dev/null +++ b/tst/formal/a2a_conversation/AGENTS.md @@ -0,0 +1,138 @@ +# AGENTS.md: model-checking a prompt step's A2A conversation record + +How to check a change to how `prompt_agent` opens, records and closes its A2A conversation against the TLA+ model in +this directory. The repository-wide rules are in the root `AGENTS.md`. + +`ConversationLifecycle.tla` models one `prompt_agent` step's record in the `agent_env_a2a_conversations` collection, +the step that owns it (`PromptAgentTaskStep._converse`), a scheduler retry of the step under the same instance id, a +process that dies mid-step, and a human peer's A2A endpoint that records its own turns through the same store and may +close the conversation. Each store writer is one action: each loops on a `rev` compare-and-swap that rereads and +recomputes on every attempt, so a lost attempt writes nothing. TLC, the TLA+ model checker, explores every order of +those actors' calls. + +The model covers a step that sets `context_id`. Only that step keeps one conversation id across the runs of an +instance, so only its re-run reopens the conversation a killed run left. A step without `context_id` gets a new id on +each run, and the killed run's record stays active. The companion change in #937 closes that record when the step +runs again; this model does not check it. + +TLC checks six invariants: + +- `EndedStepLeavesConversationClosed`. When the step ends for any reason (it returns, times out, is cancelled or + raises), its conversation is closed. If it is left active and pending, `list_pending` keeps listing a dead run as + waiting for a reply, and its working task never ends. +- `ClosedConversationGainsNoTask`. A closed conversation never gains a task. If it does, the record holds a working + task and `pending=True` that no one will answer. +- `CompletedTaskWasNotAFailedTurn`. A task recorded `completed` was not a turn the agent failed. If it was, a reader + of the record (a `tasks/get` served from it, a grader) sees a failed turn as a success. +- `StepTurnRefusedOnlyAfterOthersClose`. The store refuses the step's turn only when someone other than the step + closed the conversation during this run. If it refuses otherwise, a retry finds the conversation its own earlier run + closed and sends nothing. +- `ReplyEndsItsOwnTask`. The agent's reply ends the step's task for that turn. `complete_a2a_task` ends the oldest + working task, so if an earlier run left one working, the retry's reply is stored against the earlier run's turn and + the retry's own turn stays working. +- `StepThatSentNothingFails`. A run of the step that sent the agent nothing does not end as a success. If it does, the + step records an empty answer and a grader grades nothing. + +## Configs and the expected result + +Every config runs with two runs of the step, two turns each, at most one close by the peer and at most one process +death. `check.sh` runs each config once per invariant. + +| Config | What it models | Breaks | +| --- | --- | --- | +| `before-fix.cfg` | the code before the fix: no close on exceptions, no status check, every reply recorded `completed`, no reopen | the first three invariants and `ReplyEndsItsOwnTask` | +| `fixed.cfg` | the code as it is | nothing (39,211 distinct states) | +| `mutant-no-finally.cfg` | no close in the `finally` | `EndedStepLeavesConversationClosed` | +| `mutant-close-after-live-end.cfg` | the `finally` awaits `live_turns.end()` before it closes | `EndedStepLeavesConversationClosed` (a cancellation during that await skips the close) | +| `mutant-no-guard.cfg` | no status check in `add_a2a_task` | `ClosedConversationGainsNoTask` | +| `mutant-no-guard-no-peer-close.cfg` | the same, with a peer that never closes | `ClosedConversationGainsNoTask` (the peer records the step's message after the step closed) | +| `mutant-no-end-state.cfg` | no `state=` in `complete_a2a_task` | `CompletedTaskWasNotAFailedTurn` | +| `mutant-no-reopen.cfg` | no `reopen` on a re-run | `StepTurnRefusedOnlyAfterOthersClose`, `ReplyEndsItsOwnTask` | +| `mutant-reopen-keeps-left-tasks.cfg` | `reopen` that does not cancel the working tasks a killed run left | `ReplyEndsItsOwnTask` | +| `mutant-no-first-turn-failure.cfg` | a refused first turn ends the loop instead of raising | `StepThatSentNothingFails` | +| `known-gap-late-peer-record.cfg` | the code as it is, where the peer's endpoint may record an earlier run's message after the retry reopened | `ReplyEndsItsOwnTask` | + +The last row is a gap in the code, not in the model. The earlier run asks the peer and dies or raises before the +peer's endpoint records the ask. The retry reopens the conversation, and the endpoint then appends the earlier ask +ahead of the retry's turn. The retry's reply ends that ask, because `complete_a2a_task` ends the oldest working task. +Every other config keeps the endpoint to the current run's messages (`LatePeerRecord = FALSE`). + +## When to run it + +Run the check when a change touches a function in this table. Each action's comment in `ConversationLifecycle.tla` +cites the lines it stands for. The paths are under `src/agent_env/`. + +| Code | Model action | +| --- | --- | +| `a2a_agent/conversation_store.py:add_a2a_task` | `Add`, `AddRefused`, used by `StepRecordsTurn` and `PeerRecordsMessage` | +| `a2a_agent/conversation_store.py:complete_a2a_task` | `Complete`, used by `StepRecordsReply` and `PeerReplies` | +| `a2a_agent/conversation_store.py:mark_closed`, `_end_working_tasks` | `Close` | +| `a2a_agent/conversation_store.py:reopen`, `create_conversation` | `StepOpensConversation` | +| `a2a_agent/conversation_store.py:list_pending` | the worklist `PeerReplies` reads | +| `task_step/task_steps/prompt_agent.py:PromptAgentTaskStep._converse`, from `reopen` to the `finally` that closes | every `Step*` action | +| `task_step/task_steps/prompt_agent.py:_UserSide._send_to_peer` | `StepAsksPeer`, `StepGetsAnswer`, `StepPeerEnds`, and `StepRaises` on a cancellation | +| `task/task.py:_roll_back_span` (a retry re-runs the step under the same instance id) | `StepRetried` | + +The model was last confirmed against the code at the commit that last changed this directory +(`git log -1 -- tst/formal/a2a_conversation`). To list the covered changes since then, run: + +```sh +git log "$(git log -1 --format=%H -- tst/formal/a2a_conversation)"..HEAD -- \ + src/agent_env/a2a_agent/conversation_store.py src/agent_env/task_step/task_steps/prompt_agent.py \ + src/agent_env/task/task.py +``` + +After you confirm that the model still describes a change to the covered code, re-check every line citation in the +spec and touch this guide in the same commit. + +## Run the check + +```sh +tst/formal/a2a_conversation/check.sh +``` + +The script needs Java 11 or later and `tla2tools.jar` v1.7.4 (https://github.com/tlaplus/tlaplus/releases/tag/v1.7.4). +The first run downloads the jar and checks its sha256. `TLA2TOOLS` names a local copy instead, which must match the +same sha256, and `JAVA` names the java binary when it is not on `PATH`. The script exits nonzero when any run differs +from the table above. A passing run prints 66 lines that start with `ok`, the `fixed` lines reading +`holds 39211 distinct states found`, and ends with `TLC 1.7.4; specs, configs and tlc.out in `. + +To run one config with plain TLC from this directory: + +```sh +java -XX:+UseParallelGC -cp tla2tools.jar tlc2.TLC -workers 1 -metadir "$(mktemp -d)" -config fixed.cfg ConversationLifecycle.tla +``` + +It ends with `Model checking completed. No error has been found.` Plain TLC stops at the first invariant that breaks, +so use `check.sh` to see every invariant. + +## How to read a failure + +An `UNEXPECTED` line names the config, the invariant and what TLC found. Its `tlc.out`, in the directory the last line +prints, holds the shortest trace: one state per action, named by the action. Read the trace as calls in the code, using +each action's citation. + +When an invariant breaks on `fixed.cfg`, replay the trace against the real code, as the tests in +`tst/unit/task_step/test_prompt_agent_conversation_close.py` do: they run the step on the local document store and +assert the stored record. If the replay produces the same record, the code has the bug. If it does not, the model has +drifted: find the action whose citation no longer matches the code and fix the model, not the invariant. + +When a mutant config stops breaking its invariant, the model no longer depends on the guard that config removes. Check +that the guard is still in the code and that its action still models it. + +## What the model leaves out + +- Two runs racing to create the conversation. `prompt_agent` catches the `DuplicateKeyError` the unique index raises + and reopens; a store without that index inserts a second document instead. +- A store call that fails inside the `finally`. The step logs it and keeps the original exception, and the + conversation stays active. +- The message arrays and their index pointers (`input_message_idx`, `response_message_idx`). +- User simulators, post-turn hooks and notifications, which reach the store only through the same calls. +- `always_on`, which closes its conversation in its own `finally`. +- A process that dies and is never re-run: nothing closes its conversation, and no sweep or TTL does. +- A step without `context_id` whose process dies: the re-run opens a new conversation and leaves the killed run's + record active (see the scope above). +- Runs that are both alive. The model runs one attempt at a time. `reopen` cancels every working task and + `complete_a2a_task` ends the oldest one, without checking which attempt owns it. A superseded attempt that is still + running, or a sibling step that shares the `context_id` in the same instance, can cancel or end the other's task and + close the conversation under it. This is a known gap in the code: fencing it needs an attempt id on each A2A task. diff --git a/tst/formal/a2a_conversation/ConversationLifecycle.tla b/tst/formal/a2a_conversation/ConversationLifecycle.tla new file mode 100644 index 000000000..57a6dd872 --- /dev/null +++ b/tst/formal/a2a_conversation/ConversationLifecycle.tla @@ -0,0 +1,349 @@ +---- MODULE ConversationLifecycle ---- +\* One prompt_agent step's A2A conversation record (src/agent_env/a2a_agent/conversation_store.py) +\* and the step that owns it (src/agent_env/task_step/task_steps/prompt_agent.py, PromptAgentTaskStep._converse), +\* with a human peer's endpoint that records its own turns through the same store. +\* It covers a step that sets context_id: only that step keeps one conversation id across the runs of an instance +\* (prompt_agent.py:511, 655-657). A step without it gets a new id on each run, so a killed run's record stays active. +\* +\* Each store writer is one action: add_a2a_task, complete_a2a_task, mark_closed and reopen each loop +\* on a `rev` compare-and-swap that rereads and recomputes on every attempt, so a lost attempt writes +\* nothing and the call takes effect at its one successful write. +EXTENDS Naturals, Sequences + +CONSTANTS + Attempts, \* how many times the scheduler may run the step (retry_config) + MaxTurns, \* max_conversation_turns + PeerMayClose, \* how many times the human may close the conversation: 0 or 1 + Kills, \* how many times the process may die mid-step: 0 or 1 + LatePeerRecord, \* the peer's endpoint may record an earlier run's message after a retry reopened + CloseOnAnyEnd, \* fix: the step closes its conversation in a finally + RefuseAddWhenClosed, \* fix: add_a2a_task appends only to an active conversation + RecordEndState, \* fix: complete_a2a_task records the reply's own end state + ReopenOnReuse, \* fix: a re-run that finds its conversation reopens it + ReopenCancelsLeftTasks, \* fix: reopen cancels the working tasks an earlier run left + FailOnFirstTurnRefused, \* fix: a refused first turn raises instead of ending the step with no answer + CloseBeforeLiveEnd \* fix: the finally closes the conversation before it awaits live_turns.end() + +VARIABLES + status, \* the conversation document's status: "none" before it exists + tasks, \* its a2a_tasks array + pending, \* its pending flag + pc, \* where the step is + attempt, \* which run of the step this is + retriesLeft, \* how many more times the scheduler may retry the step + killsLeft, \* how many more times the process may die + turn, \* the step's turn number + agentReply, \* how the agent's last reply ended: "completed" or "failed" + raised, \* this run of the step ended by an exception + recordedThisRun, \* this run of the step recorded a turn + messageToPeer, \* a message the step sent the human peer that its endpoint has not recorded yet + peerClosesLeft, \* how many more times the human may close the conversation + closedByPeer, \* the peer closed the conversation during this run of the step + addedWhileClosed, \* a task was appended to a closed conversation + ownTurnRefused, \* the store refused a turn of the step that nobody else had closed + wrongTaskCompleted \* the step's reply ended a task other than its own turn's + +vars == <> + +NoMessage == [attempt |-> 0, turn |-> 0] + +NewTask(kind, from) == [kind |-> kind, from |-> from, state |-> "working", reply |-> "none"] + +CancelWorking(ts) == + [i \in DOMAIN ts |-> IF ts[i].state = "working" THEN [ts[i] EXCEPT !.state = "canceled"] ELSE ts[i]] + +OldestWorking == + IF \E i \in DOMAIN tasks : tasks[i].state = "working" + THEN CHOOSE i \in DOMAIN tasks : tasks[i].state = "working" /\ \A j \in 1..(i - 1) : tasks[j].state # "working" + ELSE 0 + +\* add_a2a_task (conversation_store.py:122-171). Refused leaves the record as it was. +AddRefused == RefuseAddWhenClosed /\ status # "active" +Add(kind, from) == + /\ tasks' = Append(tasks, NewTask(kind, from)) + /\ pending' = TRUE + /\ addedWhileClosed' = (addedWhileClosed \/ status # "active") + +\* complete_a2a_task (conversation_store.py:174-264): ends the oldest working task, whoever it belongs to. +Complete(replyEnd) == + /\ tasks' = IF OldestWorking = 0 THEN tasks + ELSE [tasks EXCEPT ![OldestWorking].state = IF RecordEndState THEN replyEnd ELSE "completed", + ![OldestWorking].reply = replyEnd] + /\ pending' = FALSE + +\* The oldest working task is not the step's task for this turn. +EndsOtherTask == + /\ OldestWorking # 0 + /\ \/ tasks[OldestWorking].kind # "agent_turn" + \/ tasks[OldestWorking].from # [attempt |-> attempt, turn |-> turn] + +\* mark_closed (conversation_store.py:362-364, through _end_working_tasks at 314-359). +Close == + /\ status' = "closed" + /\ tasks' = CancelWorking(tasks) + /\ pending' = FALSE + +FinallyStart == IF CloseBeforeLiveEnd THEN "closing_read" ELSE "ending_live" + +FinallyExit(hasRaised) == IF hasRaised THEN "ended" ELSE "after_loop" + +Init == + /\ status = "none" + /\ tasks = <<>> + /\ pending = FALSE + /\ pc = "start" + /\ attempt = 1 + /\ retriesLeft = Attempts - 1 + /\ killsLeft = Kills + /\ turn = 1 + /\ agentReply = "none" + /\ raised = FALSE + /\ recordedThisRun = FALSE + /\ messageToPeer = NoMessage + /\ peerClosesLeft = PeerMayClose + /\ closedByPeer = FALSE + /\ addedWhileClosed = FALSE + /\ ownTurnRefused = FALSE + /\ wrongTaskCompleted = FALSE + +\* reopen, else create_conversation (prompt_agent.py:707-718; conversation_store.py:367-370, 60-95). +StepOpensConversation == + /\ pc = "start" + /\ IF status = "none" + THEN /\ status' = "active" /\ tasks' = <<>> /\ pending' = FALSE + ELSE IF ReopenOnReuse + THEN /\ status' = "active" /\ pending' = FALSE + /\ tasks' = IF ReopenCancelsLeftTasks THEN CancelWorking(tasks) ELSE tasks + ELSE UNCHANGED <> + /\ pc' = "turn" + /\ turn' = 1 + /\ raised' = FALSE + /\ recordedThisRun' = FALSE + /\ closedByPeer' = FALSE + /\ UNCHANGED <> + +\* record_turn, run by send_and_wait just before the message goes out; a refusal raises _ConversationClosed, which +\* fails the step on the first turn and ends the loop on a later one (prompt_agent.py:735-754, 758-771). +StepRecordsTurn == + /\ pc = "turn" + /\ IF AddRefused + THEN /\ raised' = (FailOnFirstTurnRefused /\ turn = 1) + /\ pc' = IF CloseOnAnyEnd THEN FinallyStart ELSE IF raised' THEN "ended" ELSE "after_loop" + /\ ownTurnRefused' = (ownTurnRefused \/ ~closedByPeer) + /\ UNCHANGED <> + ELSE /\ Add("agent_turn", [attempt |-> attempt, turn |-> turn]) + /\ pc' = "waiting" + /\ recordedThisRun' = TRUE + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* send_and_wait returns the agent's terminal task (prompt_agent.py:758-777). +AgentReplies(end) == + /\ pc = "waiting" + /\ agentReply' = end + /\ pc' = "replied" + /\ UNCHANGED <> + +LoopExit == IF CloseOnAnyEnd THEN FinallyStart ELSE "after_loop" + +\* complete_a2a_task for the agent's reply, then the failed / last-turn breaks (prompt_agent.py:784-790, 823-831). +StepRecordsReply == + /\ pc = "replied" + /\ Complete(agentReply) + /\ wrongTaskCompleted' = (wrongTaskCompleted \/ EndsOtherTask) + /\ pc' = IF agentReply = "failed" THEN "close_now" + ELSE IF turn = MaxTurns THEN LoopExit + ELSE "check" + /\ UNCHANGED <> + +\* mark_closed where the loop ends the conversation itself (prompt_agent.py:824, 860, 871). +StepEndsConversation == + /\ pc = "close_now" + /\ Close + /\ pc' = LoopExit + /\ UNCHANGED <> + +\* get_conversation: someone else may have closed it (prompt_agent.py:833-836). +StepChecksActive == + /\ pc = "check" + /\ pc' = IF status # "active" THEN LoopExit ELSE "asking" + /\ UNCHANGED <> + +\* _UserSide._send_to_peer: message/send to the human peer (prompt_agent.py:854, 1422-1440). +StepAsksPeer == + /\ pc = "asking" + /\ messageToPeer' = [attempt |-> attempt, turn |-> turn] + /\ pc' = "awaiting_peer" + /\ UNCHANGED <> + +\* The peer's task is the step's open ask; its state reaches the step through the peer's tasks/get. +PeerTaskEnded(end) == + \E i \in DOMAIN tasks : /\ tasks[i].kind = "peer_turn" /\ tasks[i].state = end + /\ tasks[i].from = [attempt |-> attempt, turn |-> turn] + +\* The peer answered: the conversation goes on (prompt_agent.py:1459-1460, 867). +StepGetsAnswer == + /\ pc = "awaiting_peer" + /\ PeerTaskEnded("completed") + /\ turn' = turn + 1 + /\ pc' = "turn" + /\ UNCHANGED <> + +\* The peer's task ended otherwise, or the step's wait for it ran out: {"end": ...} +\* (prompt_agent.py:1444-1457, 855-861). +StepPeerEnds == + /\ pc = "awaiting_peer" + /\ pc' = "close_now" + /\ UNCHANGED <> + +\* Anything in the step raises: a TimeoutError or AgentUnreachableError from the agent's poll, a cancellation, +\* a failed trajectory join or trigger-state write (prompt_agent.py:772-774, 1441-1443, 887-890). +StepRaises == + /\ pc \in {"turn", "waiting", "replied", "check", "asking", "awaiting_peer", "after_loop"} + /\ raised' = TRUE + /\ pc' = IF CloseOnAnyEnd /\ pc # "after_loop" THEN FinallyStart ELSE "ended" + /\ UNCHANGED <> + +\* The process dies mid-step, so no finally runs, and a later run under the same instance id runs the step again +\* and reopens the same conversation, which holds only for a step that sets context_id. +\* reopen's docstring names this case (conversation_store.py:368-369). +StepKilled == + /\ pc \in {"turn", "waiting", "replied", "close_now", "check", "asking", "awaiting_peer", "after_loop", + "closing_read", "closing_write", "ending_live"} + /\ killsLeft > 0 + /\ killsLeft' = killsLeft - 1 + /\ attempt' = attempt + 1 + /\ pc' = "start" + /\ UNCHANGED <> + +\* Joining the trajectory copies and saving trigger state, after the loop (prompt_agent.py:887-890). +StepFinishesLoop == + /\ pc = "after_loop" + /\ pc' = IF CloseOnAnyEnd THEN "ended" ELSE "closing_read" + /\ UNCHANGED <> + +CloseDone == + IF ~CloseOnAnyEnd THEN "ended" ELSE IF CloseBeforeLiveEnd THEN "ending_live" ELSE FinallyExit(raised) + +\* get_conversation, then mark_closed if still active (prompt_agent.py:878-881). +StepReadsForClose == + /\ pc = "closing_read" + /\ pc' = IF status = "active" THEN "closing_write" + ELSE CloseDone + /\ UNCHANGED <> + +StepClosesAtEnd == + /\ pc = "closing_write" + /\ Close + /\ pc' = CloseDone + /\ UNCHANGED <> + +\* await live_turns.end() (prompt_agent.py:885-886), which ends or is cancelled; a cancellation leaves the finally +\* there and skips whatever of it comes after. +StepEndsLiveTurns == + /\ pc = "ending_live" + /\ pc' = IF CloseBeforeLiveEnd THEN FinallyExit(raised) ELSE "closing_read" + /\ UNCHANGED <> + +StepCancelledEndingLiveTurns == + /\ pc = "ending_live" + /\ raised' = TRUE + /\ pc' = "ended" + /\ UNCHANGED <> + +\* A failed step with retries left is run again under the same instance id (task.py:_roll_back_span). +StepRetried == + /\ pc = "ended" + /\ raised + /\ retriesLeft > 0 + /\ retriesLeft' = retriesLeft - 1 + /\ attempt' = attempt + 1 + /\ pc' = "start" + /\ UNCHANGED <> + +StepFinished == + /\ pc = "ended" + /\ ~(raised /\ retriesLeft > 0) + /\ pc' = "done" + /\ UNCHANGED <> + +\* The peer's endpoint records the step's message as its own task, possibly after the step stopped waiting. +PeerRecordsMessage == + /\ messageToPeer # NoMessage + /\ LatePeerRecord \/ messageToPeer.attempt = attempt + /\ messageToPeer' = NoMessage + /\ IF AddRefused + THEN UNCHANGED <> + ELSE Add("peer_turn", messageToPeer) + /\ UNCHANGED <> + +\* The human answers a conversation the worklist (list_pending, conversation_store.py:373-383) shows. +PeerReplies == + /\ status = "active" + /\ pending + /\ \E i \in DOMAIN tasks : tasks[i].kind = "peer_turn" /\ tasks[i].state = "working" + /\ Complete("completed") + /\ UNCHANGED <> + +PeerCloses == + /\ status = "active" + /\ peerClosesLeft > 0 + /\ Close + /\ peerClosesLeft' = peerClosesLeft - 1 + /\ closedByPeer' = TRUE + /\ UNCHANGED <> + +Done == pc = "done" /\ UNCHANGED vars + +Next == + \/ StepOpensConversation \/ StepRecordsTurn \/ AgentReplies("completed") \/ AgentReplies("failed") + \/ StepRecordsReply \/ StepEndsConversation \/ StepChecksActive \/ StepAsksPeer \/ StepGetsAnswer + \/ StepPeerEnds \/ StepRaises \/ StepKilled \/ StepFinishesLoop \/ StepReadsForClose \/ StepClosesAtEnd + \/ StepEndsLiveTurns \/ StepCancelledEndingLiveTurns \/ StepRetried \/ StepFinished + \/ PeerRecordsMessage \/ PeerReplies \/ PeerCloses + \/ Done + +Spec == Init /\ [][Next]_vars + +\* When the step ends for any reason, its conversation is closed, so no worklist shows it as waiting. +EndedStepLeavesConversationClosed == pc \in {"ended", "done"} => status = "closed" + +\* A closed conversation never gains a task. +ClosedConversationGainsNoTask == ~addedWhileClosed + +\* A task recorded completed was not a failed turn. +CompletedTaskWasNotAFailedTurn == + \A i \in DOMAIN tasks : tasks[i].state = "completed" => tasks[i].reply # "failed" + +\* The store refuses the step's turn only when someone else closed the conversation in this run. +StepTurnRefusedOnlyAfterOthersClose == ~ownTurnRefused + +\* The agent's reply ends the step's task for that turn, not one an earlier run left. +ReplyEndsItsOwnTask == ~wrongTaskCompleted + +\* A run of the step that sent the agent nothing does not end as a success. +StepThatSentNothingFails == (pc \in {"ended", "done"} /\ ~raised) => recordedThisRun + +==== diff --git a/tst/formal/a2a_conversation/before-fix.cfg b/tst/formal/a2a_conversation/before-fix.cfg new file mode 100644 index 000000000..26356919c --- /dev/null +++ b/tst/formal/a2a_conversation/before-fix.cfg @@ -0,0 +1,21 @@ +SPECIFICATION Spec +CONSTANTS + Attempts = 2 + MaxTurns = 2 + PeerMayClose = 1 + Kills = 1 + LatePeerRecord = FALSE + CloseOnAnyEnd = FALSE + RefuseAddWhenClosed = FALSE + RecordEndState = FALSE + ReopenOnReuse = FALSE + ReopenCancelsLeftTasks = FALSE + CloseBeforeLiveEnd = FALSE + FailOnFirstTurnRefused = FALSE +INVARIANTS + EndedStepLeavesConversationClosed + ClosedConversationGainsNoTask + CompletedTaskWasNotAFailedTurn + StepTurnRefusedOnlyAfterOthersClose + ReplyEndsItsOwnTask + StepThatSentNothingFails diff --git a/tst/formal/a2a_conversation/check.sh b/tst/formal/a2a_conversation/check.sh new file mode 100755 index 000000000..0cbc9b37f --- /dev/null +++ b/tst/formal/a2a_conversation/check.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +# Check every config of ConversationLifecycle.tla against every rule, one rule per TLC run, and compare with EXPECTED. +# +# tst/formal/a2a_conversation/check.sh +# +# Exits nonzero when any result differs. Needs Java 11+ and, on the first run, the network to fetch tla2tools.jar +# v1.7.4, unless TLA2TOOLS names a copy; either jar must match the pinned sha256. JAVA names the java binary when it +# is not on PATH. +set -euo pipefail + +here=$(cd "$(dirname "$0")" && pwd) +TLA_VERSION=1.7.4 +TLA_SHA256=936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88 +TLA_URL=https://github.com/tlaplus/tlaplus/releases/download/v$TLA_VERSION/tla2tools.jar +java=${JAVA:-java} +out=${OUT:-$(mktemp -d "${TMPDIR:-/tmp}/conversation-lifecycle-tlc.XXXXXX")} + +RULES=(EndedStepLeavesConversationClosed ClosedConversationGainsNoTask CompletedTaskWasNotAFailedTurn + StepTurnRefusedOnlyAfterOthersClose ReplyEndsItsOwnTask StepThatSentNothingFails) +# config: the rules it must break; every other rule must hold. +EXPECTED=( + "before-fix: EndedStepLeavesConversationClosed ClosedConversationGainsNoTask CompletedTaskWasNotAFailedTurn ReplyEndsItsOwnTask" + "fixed:" + "mutant-no-finally: EndedStepLeavesConversationClosed" + "mutant-close-after-live-end: EndedStepLeavesConversationClosed" + "mutant-no-guard: ClosedConversationGainsNoTask" + "mutant-no-guard-no-peer-close: ClosedConversationGainsNoTask" + "mutant-no-end-state: CompletedTaskWasNotAFailedTurn" + "mutant-no-reopen: StepTurnRefusedOnlyAfterOthersClose ReplyEndsItsOwnTask" + "mutant-reopen-keeps-left-tasks: ReplyEndsItsOwnTask" + "mutant-no-first-turn-failure: StepThatSentNothingFails" + "known-gap-late-peer-record: ReplyEndsItsOwnTask" +) + +sha256() { if command -v sha256sum >/dev/null; then sha256sum "$1"; else shasum -a 256 "$1"; fi | cut -d' ' -f1; } + +jar=${TLA2TOOLS:-} +if [[ -z $jar ]]; then + cache=${XDG_CACHE_HOME:-$HOME/.cache}/agentenv-formal + jar=$cache/tla2tools-$TLA_VERSION.jar + if [[ ! -f $jar || $(sha256 "$jar") != "$TLA_SHA256" ]]; then + mkdir -p "$cache" + part=$(mktemp "$cache/tla2tools.XXXXXX") + curl -fsSL -o "$part" "$TLA_URL" || { rm -f "$part"; exit 2; } + [[ $(sha256 "$part") == "$TLA_SHA256" ]] || { rm -f "$part"; echo "tla2tools.jar sha256 mismatch" >&2; exit 2; } + mv -f "$part" "$jar" + fi +elif [[ $(sha256 "$jar") != "$TLA_SHA256" ]]; then + echo "TLA2TOOLS=$jar is not tla2tools.jar v$TLA_VERSION (sha256 $TLA_SHA256)" >&2 + exit 2 +fi +jar=$(cd "$(dirname "$jar")" && pwd)/$(basename "$jar") + +status=0 +for line in "${EXPECTED[@]}"; do + config=${line%%:*} + breaks=" ${line#*:} " + for rule in "${RULES[@]}"; do + dir=$out/$config-$rule + mkdir -p "$dir" + cp "$here/ConversationLifecycle.tla" "$dir/" + sed -e '/^INVARIANTS/,$d' "$here/$config.cfg" > "$dir/run.cfg" + printf 'INVARIANT %s\n' "$rule" >> "$dir/run.cfg" + (cd "$dir" && "$java" -XX:+UseParallelGC -cp "$jar" tlc2.TLC -workers 1 -metadir meta -config run.cfg \ + ConversationLifecycle.tla > tlc.out 2>&1) || true + if grep -q "Invariant $rule is violated" "$dir/tlc.out"; then got=breaks + elif grep -q 'Model checking completed. No error has been found.' "$dir/tlc.out"; then got=holds + else got=error; fi + [[ $breaks == *" $rule "* ]] && want=breaks || want=holds + states=$(grep -Eo '[0-9,]+ distinct states found' "$dir/tlc.out" | tail -1 || true) + if [[ $got == "$want" ]]; then mark=ok; else mark=UNEXPECTED; status=1; fi + printf '%-11s %-30s %-36s %-7s %s\n' "$mark" "$config" "$rule" "$got" "$states" + done +done +echo "TLC $TLA_VERSION; specs, configs and tlc.out in $out" +exit $status diff --git a/tst/formal/a2a_conversation/fixed.cfg b/tst/formal/a2a_conversation/fixed.cfg new file mode 100644 index 000000000..eb05a4edd --- /dev/null +++ b/tst/formal/a2a_conversation/fixed.cfg @@ -0,0 +1,21 @@ +SPECIFICATION Spec +CONSTANTS + Attempts = 2 + MaxTurns = 2 + PeerMayClose = 1 + Kills = 1 + LatePeerRecord = FALSE + CloseOnAnyEnd = TRUE + RefuseAddWhenClosed = TRUE + RecordEndState = TRUE + ReopenOnReuse = TRUE + ReopenCancelsLeftTasks = TRUE + CloseBeforeLiveEnd = TRUE + FailOnFirstTurnRefused = TRUE +INVARIANTS + EndedStepLeavesConversationClosed + ClosedConversationGainsNoTask + CompletedTaskWasNotAFailedTurn + StepTurnRefusedOnlyAfterOthersClose + ReplyEndsItsOwnTask + StepThatSentNothingFails diff --git a/tst/formal/a2a_conversation/known-gap-late-peer-record.cfg b/tst/formal/a2a_conversation/known-gap-late-peer-record.cfg new file mode 100644 index 000000000..bf9dc3f2a --- /dev/null +++ b/tst/formal/a2a_conversation/known-gap-late-peer-record.cfg @@ -0,0 +1,21 @@ +SPECIFICATION Spec +CONSTANTS + Attempts = 2 + MaxTurns = 2 + PeerMayClose = 1 + Kills = 1 + LatePeerRecord = TRUE + CloseOnAnyEnd = TRUE + RefuseAddWhenClosed = TRUE + RecordEndState = TRUE + ReopenOnReuse = TRUE + ReopenCancelsLeftTasks = TRUE + CloseBeforeLiveEnd = TRUE + FailOnFirstTurnRefused = TRUE +INVARIANTS + EndedStepLeavesConversationClosed + ClosedConversationGainsNoTask + CompletedTaskWasNotAFailedTurn + StepTurnRefusedOnlyAfterOthersClose + ReplyEndsItsOwnTask + StepThatSentNothingFails diff --git a/tst/formal/a2a_conversation/mutant-close-after-live-end.cfg b/tst/formal/a2a_conversation/mutant-close-after-live-end.cfg new file mode 100644 index 000000000..f47de7076 --- /dev/null +++ b/tst/formal/a2a_conversation/mutant-close-after-live-end.cfg @@ -0,0 +1,21 @@ +SPECIFICATION Spec +CONSTANTS + Attempts = 2 + MaxTurns = 2 + PeerMayClose = 1 + Kills = 1 + LatePeerRecord = FALSE + CloseOnAnyEnd = TRUE + RefuseAddWhenClosed = TRUE + RecordEndState = TRUE + ReopenOnReuse = TRUE + ReopenCancelsLeftTasks = TRUE + CloseBeforeLiveEnd = FALSE + FailOnFirstTurnRefused = TRUE +INVARIANTS + EndedStepLeavesConversationClosed + ClosedConversationGainsNoTask + CompletedTaskWasNotAFailedTurn + StepTurnRefusedOnlyAfterOthersClose + ReplyEndsItsOwnTask + StepThatSentNothingFails diff --git a/tst/formal/a2a_conversation/mutant-no-end-state.cfg b/tst/formal/a2a_conversation/mutant-no-end-state.cfg new file mode 100644 index 000000000..e2de2011a --- /dev/null +++ b/tst/formal/a2a_conversation/mutant-no-end-state.cfg @@ -0,0 +1,21 @@ +SPECIFICATION Spec +CONSTANTS + Attempts = 2 + MaxTurns = 2 + PeerMayClose = 1 + Kills = 1 + LatePeerRecord = FALSE + CloseOnAnyEnd = TRUE + RefuseAddWhenClosed = TRUE + RecordEndState = FALSE + ReopenOnReuse = TRUE + ReopenCancelsLeftTasks = TRUE + CloseBeforeLiveEnd = TRUE + FailOnFirstTurnRefused = TRUE +INVARIANTS + EndedStepLeavesConversationClosed + ClosedConversationGainsNoTask + CompletedTaskWasNotAFailedTurn + StepTurnRefusedOnlyAfterOthersClose + ReplyEndsItsOwnTask + StepThatSentNothingFails diff --git a/tst/formal/a2a_conversation/mutant-no-finally.cfg b/tst/formal/a2a_conversation/mutant-no-finally.cfg new file mode 100644 index 000000000..d84af95e5 --- /dev/null +++ b/tst/formal/a2a_conversation/mutant-no-finally.cfg @@ -0,0 +1,21 @@ +SPECIFICATION Spec +CONSTANTS + Attempts = 2 + MaxTurns = 2 + PeerMayClose = 1 + Kills = 1 + LatePeerRecord = FALSE + CloseOnAnyEnd = FALSE + RefuseAddWhenClosed = TRUE + RecordEndState = TRUE + ReopenOnReuse = TRUE + ReopenCancelsLeftTasks = TRUE + CloseBeforeLiveEnd = TRUE + FailOnFirstTurnRefused = TRUE +INVARIANTS + EndedStepLeavesConversationClosed + ClosedConversationGainsNoTask + CompletedTaskWasNotAFailedTurn + StepTurnRefusedOnlyAfterOthersClose + ReplyEndsItsOwnTask + StepThatSentNothingFails diff --git a/tst/formal/a2a_conversation/mutant-no-first-turn-failure.cfg b/tst/formal/a2a_conversation/mutant-no-first-turn-failure.cfg new file mode 100644 index 000000000..3a7c549b4 --- /dev/null +++ b/tst/formal/a2a_conversation/mutant-no-first-turn-failure.cfg @@ -0,0 +1,21 @@ +SPECIFICATION Spec +CONSTANTS + Attempts = 2 + MaxTurns = 2 + PeerMayClose = 1 + Kills = 1 + LatePeerRecord = FALSE + CloseOnAnyEnd = TRUE + RefuseAddWhenClosed = TRUE + RecordEndState = TRUE + ReopenOnReuse = TRUE + ReopenCancelsLeftTasks = TRUE + CloseBeforeLiveEnd = TRUE + FailOnFirstTurnRefused = FALSE +INVARIANTS + EndedStepLeavesConversationClosed + ClosedConversationGainsNoTask + CompletedTaskWasNotAFailedTurn + StepTurnRefusedOnlyAfterOthersClose + ReplyEndsItsOwnTask + StepThatSentNothingFails diff --git a/tst/formal/a2a_conversation/mutant-no-guard-no-peer-close.cfg b/tst/formal/a2a_conversation/mutant-no-guard-no-peer-close.cfg new file mode 100644 index 000000000..77317ced1 --- /dev/null +++ b/tst/formal/a2a_conversation/mutant-no-guard-no-peer-close.cfg @@ -0,0 +1,21 @@ +SPECIFICATION Spec +CONSTANTS + Attempts = 2 + MaxTurns = 2 + PeerMayClose = 0 + Kills = 1 + LatePeerRecord = FALSE + CloseOnAnyEnd = TRUE + RefuseAddWhenClosed = FALSE + RecordEndState = TRUE + ReopenOnReuse = TRUE + ReopenCancelsLeftTasks = TRUE + CloseBeforeLiveEnd = TRUE + FailOnFirstTurnRefused = TRUE +INVARIANTS + EndedStepLeavesConversationClosed + ClosedConversationGainsNoTask + CompletedTaskWasNotAFailedTurn + StepTurnRefusedOnlyAfterOthersClose + ReplyEndsItsOwnTask + StepThatSentNothingFails diff --git a/tst/formal/a2a_conversation/mutant-no-guard.cfg b/tst/formal/a2a_conversation/mutant-no-guard.cfg new file mode 100644 index 000000000..076733f03 --- /dev/null +++ b/tst/formal/a2a_conversation/mutant-no-guard.cfg @@ -0,0 +1,21 @@ +SPECIFICATION Spec +CONSTANTS + Attempts = 2 + MaxTurns = 2 + PeerMayClose = 1 + Kills = 1 + LatePeerRecord = FALSE + CloseOnAnyEnd = TRUE + RefuseAddWhenClosed = FALSE + RecordEndState = TRUE + ReopenOnReuse = TRUE + ReopenCancelsLeftTasks = TRUE + CloseBeforeLiveEnd = TRUE + FailOnFirstTurnRefused = TRUE +INVARIANTS + EndedStepLeavesConversationClosed + ClosedConversationGainsNoTask + CompletedTaskWasNotAFailedTurn + StepTurnRefusedOnlyAfterOthersClose + ReplyEndsItsOwnTask + StepThatSentNothingFails diff --git a/tst/formal/a2a_conversation/mutant-no-reopen.cfg b/tst/formal/a2a_conversation/mutant-no-reopen.cfg new file mode 100644 index 000000000..06266eeba --- /dev/null +++ b/tst/formal/a2a_conversation/mutant-no-reopen.cfg @@ -0,0 +1,21 @@ +SPECIFICATION Spec +CONSTANTS + Attempts = 2 + MaxTurns = 2 + PeerMayClose = 1 + Kills = 1 + LatePeerRecord = FALSE + CloseOnAnyEnd = TRUE + RefuseAddWhenClosed = TRUE + RecordEndState = TRUE + ReopenOnReuse = FALSE + ReopenCancelsLeftTasks = TRUE + CloseBeforeLiveEnd = TRUE + FailOnFirstTurnRefused = TRUE +INVARIANTS + EndedStepLeavesConversationClosed + ClosedConversationGainsNoTask + CompletedTaskWasNotAFailedTurn + StepTurnRefusedOnlyAfterOthersClose + ReplyEndsItsOwnTask + StepThatSentNothingFails diff --git a/tst/formal/a2a_conversation/mutant-reopen-keeps-left-tasks.cfg b/tst/formal/a2a_conversation/mutant-reopen-keeps-left-tasks.cfg new file mode 100644 index 000000000..cfd9b0b50 --- /dev/null +++ b/tst/formal/a2a_conversation/mutant-reopen-keeps-left-tasks.cfg @@ -0,0 +1,21 @@ +SPECIFICATION Spec +CONSTANTS + Attempts = 2 + MaxTurns = 2 + PeerMayClose = 1 + Kills = 1 + LatePeerRecord = FALSE + CloseOnAnyEnd = TRUE + RefuseAddWhenClosed = TRUE + RecordEndState = TRUE + ReopenOnReuse = TRUE + ReopenCancelsLeftTasks = FALSE + CloseBeforeLiveEnd = TRUE + FailOnFirstTurnRefused = TRUE +INVARIANTS + EndedStepLeavesConversationClosed + ClosedConversationGainsNoTask + CompletedTaskWasNotAFailedTurn + StepTurnRefusedOnlyAfterOthersClose + ReplyEndsItsOwnTask + StepThatSentNothingFails