From bc458e382cdbc0683643f0d21ac41d90d9e7e6af Mon Sep 17 00:00:00 2001 From: VascoSch92 Date: Wed, 8 Jul 2026 13:33:44 +0200 Subject: [PATCH 1/6] fix(agent-server): persist LLM/profile switch to meta.json so it survives restart MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit switch_llm / switch_profile updated only the live ConversationState (base_state.json). On resume, EventService.start() rebuilds the agent from meta.json and ConversationState.create() overwrites base_state.json with it, so the switch — including the LLM timeout — reverted to the conversation's creation-time config on every agent-server restart. Re-switching the profile fixed it live but the fix was lost on the next restart. Mirror the switched agent into meta.json (+ save_meta), matching the existing switch_acp_model precedent, by routing both endpoints through new EventService.switch_llm / switch_profile methods. --- .../agent_server/conversation_router.py | 6 +- .../openhands/agent_server/event_service.py | 30 ++++++ .../agent_server/test_conversation_router.py | 35 +++---- .../agent_server/test_conversation_service.py | 43 +++++++++ tests/agent_server/test_event_service.py | 95 +++++++++++++++++++ 5 files changed, 182 insertions(+), 27 deletions(-) diff --git a/openhands-agent-server/openhands/agent_server/conversation_router.py b/openhands-agent-server/openhands/agent_server/conversation_router.py index 381e4da8dd4..07d36c6d5c8 100644 --- a/openhands-agent-server/openhands/agent_server/conversation_router.py +++ b/openhands-agent-server/openhands/agent_server/conversation_router.py @@ -465,9 +465,8 @@ async def switch_conversation_profile( event_service = await conversation_service.get_event_service(conversation_id) if event_service is None: raise HTTPException(status.HTTP_404_NOT_FOUND) - conversation = event_service.get_conversation() try: - conversation.switch_profile(profile_name) + await event_service.switch_profile(profile_name) except FileNotFoundError: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, @@ -499,11 +498,10 @@ async def switch_conversation_llm( event_service = await conversation_service.get_event_service(conversation_id) if event_service is None: raise HTTPException(status.HTTP_404_NOT_FOUND) - conversation = event_service.get_conversation() cipher = get_cipher(request) if cipher is not None: llm = decrypt_incoming_llm_secrets(llm, cipher) - conversation.switch_llm(llm) + await event_service.switch_llm(llm) return Success() diff --git a/openhands-agent-server/openhands/agent_server/event_service.py b/openhands-agent-server/openhands/agent_server/event_service.py index e50d82f2edc..a883661ba69 100644 --- a/openhands-agent-server/openhands/agent_server/event_service.py +++ b/openhands-agent-server/openhands/agent_server/event_service.py @@ -1415,6 +1415,36 @@ async def switch_acp_model(self, model: str) -> None: ) await self.save_meta() + async def switch_llm(self, llm: LLM) -> None: + """Swap the conversation's LLM, mirroring it into ``meta.json``. + + Like :meth:`switch_acp_model`, the new agent must be written back to + ``meta.json`` (``self.stored.agent``): ``start()`` rebuilds the runtime + agent from there and ``ConversationState.create()`` copies it over the + persisted ``base_state.json`` on resume. A switch that only updated the + live conversation would be silently reverted — reinstating the + conversation's creation-time LLM (and its ``timeout``) — on the next + agent-server restart. + """ + if self._conversation is None: + raise ValueError("inactive_service") + loop = asyncio.get_running_loop() + await loop.run_in_executor(None, self._conversation.switch_llm, llm) + self.stored = self.stored.model_copy(update={"agent": self._conversation.agent}) + await self.save_meta() + + async def switch_profile(self, profile_name: str) -> None: + """Switch the conversation's LLM to a stored profile, mirroring it into + ``meta.json`` so it survives a restart (see :meth:`switch_llm`).""" + if self._conversation is None: + raise ValueError("inactive_service") + loop = asyncio.get_running_loop() + await loop.run_in_executor( + None, self._conversation.switch_profile, profile_name + ) + self.stored = self.stored.model_copy(update={"agent": self._conversation.agent}) + await self.save_meta() + async def close(self): self._closing = True self._explicit_interrupt_generation += 1 diff --git a/tests/agent_server/test_conversation_router.py b/tests/agent_server/test_conversation_router.py index 7805dd85581..ab8a490e8c6 100644 --- a/tests/agent_server/test_conversation_router.py +++ b/tests/agent_server/test_conversation_router.py @@ -1,6 +1,6 @@ """Tests for conversation_router.py endpoints.""" -from unittest.mock import AsyncMock, MagicMock +from unittest.mock import AsyncMock from uuid import uuid4 import pytest @@ -2075,9 +2075,7 @@ def test_switch_conversation_profile_success( client, mock_conversation_service, mock_event_service, sample_conversation_id ): """Test switch_conversation_profile endpoint with a valid profile.""" - mock_conversation = MagicMock() mock_conversation_service.get_event_service.return_value = mock_event_service - mock_event_service.get_conversation.return_value = mock_conversation client.app.dependency_overrides[get_conversation_service] = lambda: ( mock_conversation_service @@ -2095,8 +2093,9 @@ def test_switch_conversation_profile_success( mock_conversation_service.get_event_service.assert_called_once_with( sample_conversation_id ) - mock_event_service.get_conversation.assert_called_once() - mock_conversation.switch_profile.assert_called_once_with("gpt") + # The router persists the switch through EventService (which mirrors it + # into meta.json) rather than mutating the live conversation directly. + mock_event_service.switch_profile.assert_awaited_once_with("gpt") finally: client.app.dependency_overrides.clear() @@ -2129,12 +2128,10 @@ def test_switch_conversation_profile_nonexistent_profile( client, mock_conversation_service, mock_event_service, sample_conversation_id ): """Test switch_conversation_profile when the profile does not exist on disk.""" - mock_conversation = MagicMock() - mock_conversation.switch_profile.side_effect = FileNotFoundError( + mock_event_service.switch_profile.side_effect = FileNotFoundError( "Profile 'missing' not found" ) mock_conversation_service.get_event_service.return_value = mock_event_service - mock_event_service.get_conversation.return_value = mock_conversation client.app.dependency_overrides[get_conversation_service] = lambda: ( mock_conversation_service @@ -2148,7 +2145,7 @@ def test_switch_conversation_profile_nonexistent_profile( assert response.status_code == 404 assert "missing" in response.json()["detail"] - mock_conversation.switch_profile.assert_called_once_with("missing") + mock_event_service.switch_profile.assert_awaited_once_with("missing") finally: client.app.dependency_overrides.clear() @@ -2157,10 +2154,8 @@ def test_switch_conversation_profile_corrupted_profile( client, mock_conversation_service, mock_event_service, sample_conversation_id ): """Test switch_conversation_profile when the profile is corrupted or invalid.""" - mock_conversation = MagicMock() - mock_conversation.switch_profile.side_effect = ValueError("Invalid profile format") + mock_event_service.switch_profile.side_effect = ValueError("Invalid profile format") mock_conversation_service.get_event_service.return_value = mock_event_service - mock_event_service.get_conversation.return_value = mock_conversation client.app.dependency_overrides[get_conversation_service] = lambda: ( mock_conversation_service @@ -2174,7 +2169,7 @@ def test_switch_conversation_profile_corrupted_profile( assert response.status_code == 400 assert "Invalid profile format" in response.json()["detail"] - mock_conversation.switch_profile.assert_called_once_with("corrupted") + mock_event_service.switch_profile.assert_awaited_once_with("corrupted") finally: client.app.dependency_overrides.clear() @@ -2338,9 +2333,7 @@ def test_switch_conversation_llm_success( """The /switch_llm endpoint forwards the inline LLM to switch_llm, bypassing the profile store (#3017). """ - mock_conversation = MagicMock() mock_conversation_service.get_event_service.return_value = mock_event_service - mock_event_service.get_conversation.return_value = mock_conversation client.app.dependency_overrides[get_conversation_service] = lambda: ( mock_conversation_service @@ -2359,8 +2352,8 @@ def test_switch_conversation_llm_success( ) assert response.status_code == 200 - mock_conversation.switch_llm.assert_called_once() - forwarded_llm = mock_conversation.switch_llm.call_args.args[0] + mock_event_service.switch_llm.assert_awaited_once() + forwarded_llm = mock_event_service.switch_llm.call_args.args[0] assert isinstance(forwarded_llm, LLM) assert forwarded_llm.model == "openai/gpt-4o" assert forwarded_llm.usage_id == "caller-supplied-id" @@ -2392,9 +2385,7 @@ def test_switch_conversation_llm_decrypts_encrypted_api_key( secret_key=SecretStr(secret_key), ) - mock_conversation = MagicMock() mock_conversation_service.get_event_service.return_value = mock_event_service - mock_event_service.get_conversation.return_value = mock_conversation client.app.dependency_overrides[get_conversation_service] = lambda: ( mock_conversation_service @@ -2413,7 +2404,7 @@ def test_switch_conversation_llm_decrypts_encrypted_api_key( ) assert response.status_code == 200 - forwarded_llm = mock_conversation.switch_llm.call_args.args[0] + forwarded_llm = mock_event_service.switch_llm.call_args.args[0] assert isinstance(forwarded_llm, LLM) assert isinstance(forwarded_llm.api_key, SecretStr) assert forwarded_llm.api_key.get_secret_value() == "plaintext-api-key" @@ -2438,9 +2429,7 @@ def test_switch_conversation_llm_plaintext_with_cipher_passes_through( secret_key=SecretStr(secret_key), ) - mock_conversation = MagicMock() mock_conversation_service.get_event_service.return_value = mock_event_service - mock_event_service.get_conversation.return_value = mock_conversation client.app.dependency_overrides[get_conversation_service] = lambda: ( mock_conversation_service @@ -2459,7 +2448,7 @@ def test_switch_conversation_llm_plaintext_with_cipher_passes_through( ) assert response.status_code == 200 - forwarded_llm = mock_conversation.switch_llm.call_args.args[0] + forwarded_llm = mock_event_service.switch_llm.call_args.args[0] assert isinstance(forwarded_llm.api_key, SecretStr) assert forwarded_llm.api_key.get_secret_value() == "sk-plaintext" finally: diff --git a/tests/agent_server/test_conversation_service.py b/tests/agent_server/test_conversation_service.py index 38b2b62a220..ddcfd4f08a3 100644 --- a/tests/agent_server/test_conversation_service.py +++ b/tests/agent_server/test_conversation_service.py @@ -539,6 +539,49 @@ async def test_restart_resumes_conversations_after_non_graceful_shutdown(tmp_pat ) +@pytest.mark.asyncio +async def test_switch_llm_survives_restart(tmp_path): + """A switched LLM (and its timeout) must persist across a restart. + + Reproduces the reported bug: a conversation is created with a placeholder + LLM and then switched to the real one (the #3017 app-server flow). Because + resume rebuilds the agent from meta.json and ConversationState.create() + overrides base_state.json with it, the switch has to be mirrored into + meta.json — otherwise the agent-server reinstates the creation-time timeout + on every restart, and only a manual re-switch temporarily fixes it. + """ + conversations_dir = tmp_path / "conversations" + workspace_dir = tmp_path / "workspace" + workspace_dir.mkdir() + + request = StartConversationRequest( + agent=Agent( + llm=LLM(model="gpt-4o", usage_id="creation", timeout=300), tools=[] + ), + workspace=LocalWorkspace(working_dir=str(workspace_dir)), + confirmation_policy=NeverConfirm(), + ) + + async with ConversationService(conversations_dir=conversations_dir) as primary: + info, _ = await primary.start_conversation(request) + conversation_id = info.id + event_service = await primary.get_event_service(conversation_id) + assert event_service is not None + + await event_service.switch_llm( + LLM(model="gpt-4o", usage_id="switched", timeout=600) + ) + # The live conversation reflects the switch immediately. + assert event_service.get_conversation().agent.llm.timeout == 600 + + # Restart: a fresh service resumes from disk and must keep the switched LLM. + async with ConversationService(conversations_dir=conversations_dir) as restarted: + assert restarted._event_services is not None + resumed = restarted._event_services.get(conversation_id) + assert resumed is not None + assert resumed.get_conversation().agent.llm.timeout == 600 + + class TestConversationServiceSearchConversations: """Test cases for ConversationService.search_conversations method.""" diff --git a/tests/agent_server/test_event_service.py b/tests/agent_server/test_event_service.py index 76cb9f7ac1c..d95f4bc462f 100644 --- a/tests/agent_server/test_event_service.py +++ b/tests/agent_server/test_event_service.py @@ -1844,6 +1844,101 @@ async def test_switch_acp_model_inactive_service_raises_value_error(self, tmp_pa with pytest.raises(ValueError, match="inactive_service"): await service.switch_acp_model("new-model") + @pytest.mark.asyncio + async def test_switch_llm_persists_to_meta(self, tmp_path): + """switch_llm mirrors the switched agent into meta.json. + + start() rebuilds the runtime agent from meta.json (self.stored.agent) + and ConversationState.create() copies that agent over the persisted + base_state.json on resume. A switch that only touched the live + conversation would therefore be silently reverted to the + creation-time LLM (and its timeout) on the next agent-server restart. + """ + stored = StoredConversation( + id=uuid4(), + agent=Agent( + llm=LLM(model="gpt-4o", usage_id="creation", timeout=300), tools=[] + ), + workspace=LocalWorkspace(working_dir=str(tmp_path)), + confirmation_policy=NeverConfirm(), + initial_message=None, + metrics=None, + ) + service = EventService(stored=stored, conversations_dir=tmp_path) + conv_dir = tmp_path / stored.id.hex + conv_dir.mkdir(parents=True, exist_ok=True) + + new_llm = LLM(model="gpt-4o", usage_id="switched", timeout=600) + # Stand in for a live conversation whose switch_llm installed new_llm. + service._conversation = MagicMock() + service._conversation.agent = stored.agent.model_copy(update={"llm": new_llm}) + + await service.switch_llm(new_llm) + + # Live switch was delegated to the conversation... + service._conversation.switch_llm.assert_called_once_with(new_llm) + # ...the in-memory stored agent carries the new LLM... + assert service.stored.agent.llm.timeout == 600 + # ...and it was persisted to meta.json so it survives a restart. + loaded = StoredConversation.model_validate_json( + (conv_dir / "meta.json").read_text() + ) + assert loaded.agent.llm.timeout == 600 + + @pytest.mark.asyncio + async def test_switch_profile_persists_to_meta(self, tmp_path): + """switch_profile mirrors the switched agent into meta.json. + + Same restart-safety contract as :meth:`test_switch_llm_persists_to_meta`; + the profile path must persist the loaded profile's LLM too. + """ + stored = StoredConversation( + id=uuid4(), + agent=Agent( + llm=LLM(model="gpt-4o", usage_id="creation", timeout=300), tools=[] + ), + workspace=LocalWorkspace(working_dir=str(tmp_path)), + confirmation_policy=NeverConfirm(), + initial_message=None, + metrics=None, + ) + service = EventService(stored=stored, conversations_dir=tmp_path) + conv_dir = tmp_path / stored.id.hex + conv_dir.mkdir(parents=True, exist_ok=True) + + profile_llm = LLM(model="gpt-4o", usage_id="profile:fast", timeout=600) + service._conversation = MagicMock() + service._conversation.agent = stored.agent.model_copy( + update={"llm": profile_llm} + ) + + await service.switch_profile("fast") + + service._conversation.switch_profile.assert_called_once_with("fast") + assert service.stored.agent.llm.timeout == 600 + loaded = StoredConversation.model_validate_json( + (conv_dir / "meta.json").read_text() + ) + assert loaded.agent.llm.timeout == 600 + + @pytest.mark.asyncio + async def test_switch_llm_inactive_service_raises_value_error(self, tmp_path): + """An inactive service (no live conversation) raises ``inactive_service`` + so the conversation router maps it to 400, matching switch_acp_model.""" + stored = StoredConversation( + id=uuid4(), + agent=Agent(llm=LLM(model="gpt-4o", usage_id="creation"), tools=[]), + workspace=LocalWorkspace(working_dir=str(tmp_path)), + confirmation_policy=NeverConfirm(), + initial_message=None, + metrics=None, + ) + service = EventService(stored=stored, conversations_dir=tmp_path) + assert service._conversation is None + + with pytest.raises(ValueError, match="inactive_service"): + await service.switch_llm(LLM(model="gpt-4o", usage_id="switched")) + class TestEventServiceStartWithRunningStatus: """Test cases for EventService.start handling of RUNNING execution status.""" From 2f998a299388e1fac6aee642e66bcc1a5578b174 Mon Sep 17 00:00:00 2001 From: VascoSch92 Date: Wed, 8 Jul 2026 13:54:16 +0200 Subject: [PATCH 2/6] Centralize meta.json sync and cover the agent's switch_llm tool MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Extract the mirror-into-meta.json logic into a single EventService helper, _sync_agent_to_meta(), used by switch_llm, switch_profile, and a new post-run hook. The post-run hook covers the third switch path — the agent's built-in switch_llm tool (SwitchLLMExecutor -> conversation.switch_profile), which bypasses the HTTP endpoints — so tool-initiated switches also survive a restart. An identity check against a start()-established baseline keeps the hook a no-op for ordinary runs. --- .../openhands/agent_server/event_service.py | 69 +++++++++++---- tests/agent_server/test_event_service.py | 83 +++++++++++++++++++ 2 files changed, 136 insertions(+), 16 deletions(-) diff --git a/openhands-agent-server/openhands/agent_server/event_service.py b/openhands-agent-server/openhands/agent_server/event_service.py index a883661ba69..3d5b6773e2a 100644 --- a/openhands-agent-server/openhands/agent_server/event_service.py +++ b/openhands-agent-server/openhands/agent_server/event_service.py @@ -86,6 +86,10 @@ class EventService: owner_instance_id: str = field(default_factory=lambda: uuid4().hex) lease_ttl_seconds: float = DEFAULT_LEASE_TTL_SECONDS _conversation: LocalConversation | None = field(default=None, init=False) + # The agent object last mirrored into meta.json. Lets _sync_agent_to_meta + # cheaply detect an LLM/profile swap (which replaces the agent object) and + # skip the no-op case where a run left the agent untouched. + _synced_agent: AgentBase | None = field(default=None, init=False) _pub_sub: PubSub[Event] = field( default_factory=lambda: PubSub[Event](max_subscribers=50), init=False ) @@ -845,6 +849,8 @@ def _token_streaming_callback(chunk: LLMStreamChunk | str) -> None: conversation.set_confirmation_policy(self.stored.confirmation_policy) conversation.set_security_analyzer(self.stored.security_analyzer) self._conversation = conversation + # Baseline for _sync_agent_to_meta: meta.json already matches this agent. + self._synced_agent = conversation.agent self._conversation._state.set_write_guard(self._write_guard) if not self._external_lease_renewal: self._lease_task = asyncio.create_task(self._renew_lease_loop()) @@ -996,6 +1002,16 @@ async def _run_and_publish(): self._run_task = None await self._publish_state_update() + # Persist an in-run agent swap (the agent's switch_llm tool) + # to meta.json so it survives a restart. Best-effort: a + # failure here must not break run completion. + try: + await self._sync_agent_to_meta() + except Exception: + logger.exception( + "Failed to persist in-run agent change to meta.json" + ) + # Re-arm a run for input stranded while this task was # wrapping up. A send_message(run=True) that arrived during # the wait_for_pending() tail above had its run() rejected as @@ -1415,35 +1431,56 @@ async def switch_acp_model(self, model: str) -> None: ) await self.save_meta() - async def switch_llm(self, llm: LLM) -> None: - """Swap the conversation's LLM, mirroring it into ``meta.json``. - - Like :meth:`switch_acp_model`, the new agent must be written back to - ``meta.json`` (``self.stored.agent``): ``start()`` rebuilds the runtime - agent from there and ``ConversationState.create()`` copies it over the - persisted ``base_state.json`` on resume. A switch that only updated the - live conversation would be silently reverted — reinstating the - conversation's creation-time LLM (and its ``timeout``) — on the next - agent-server restart. + async def _sync_agent_to_meta(self) -> None: + """Mirror the live agent into ``meta.json`` when it has changed. + + ``start()`` rebuilds the runtime agent from ``meta.json`` + (``self.stored.agent``) and ``ConversationState.create()`` copies it + over the persisted ``base_state.json`` on resume. So every way the live + agent's LLM can change — the ``/switch_llm`` and ``/switch_profile`` + endpoints, and the agent's own ``switch_llm`` tool mid-run — must be + written back to ``meta.json`` or it silently reverts to the + conversation's creation-time config (including the LLM ``timeout``) on + the next agent-server restart. This is the single place that persists + that change; callers just invoke it after a potential swap. + + An LLM/profile swap replaces the agent object, so the identity check + against ``_synced_agent`` makes this a no-op for the common case of a + run that left the agent untouched. ``_synced_agent`` is established in + ``start()`` alongside ``_conversation``; a ``None`` baseline means the + service was never started, so there is nothing to reconcile. """ + conversation = self._conversation + if ( + conversation is None + or self._synced_agent is None + or conversation.agent is self._synced_agent + ): + return + self.stored = self.stored.model_copy(update={"agent": conversation.agent}) + self._synced_agent = conversation.agent + await self.save_meta() + + async def switch_llm(self, llm: LLM) -> None: + """Swap the conversation's LLM and persist it (see + :meth:`_sync_agent_to_meta` for why the switch is mirrored to + ``meta.json``).""" if self._conversation is None: raise ValueError("inactive_service") loop = asyncio.get_running_loop() await loop.run_in_executor(None, self._conversation.switch_llm, llm) - self.stored = self.stored.model_copy(update={"agent": self._conversation.agent}) - await self.save_meta() + await self._sync_agent_to_meta() async def switch_profile(self, profile_name: str) -> None: - """Switch the conversation's LLM to a stored profile, mirroring it into - ``meta.json`` so it survives a restart (see :meth:`switch_llm`).""" + """Switch the conversation's LLM to a stored profile and persist it + (see :meth:`_sync_agent_to_meta`).""" if self._conversation is None: raise ValueError("inactive_service") loop = asyncio.get_running_loop() await loop.run_in_executor( None, self._conversation.switch_profile, profile_name ) - self.stored = self.stored.model_copy(update={"agent": self._conversation.agent}) - await self.save_meta() + await self._sync_agent_to_meta() async def close(self): self._closing = True diff --git a/tests/agent_server/test_event_service.py b/tests/agent_server/test_event_service.py index d95f4bc462f..9c16908ba52 100644 --- a/tests/agent_server/test_event_service.py +++ b/tests/agent_server/test_event_service.py @@ -1871,6 +1871,7 @@ async def test_switch_llm_persists_to_meta(self, tmp_path): new_llm = LLM(model="gpt-4o", usage_id="switched", timeout=600) # Stand in for a live conversation whose switch_llm installed new_llm. service._conversation = MagicMock() + service._synced_agent = stored.agent # baseline start() would establish service._conversation.agent = stored.agent.model_copy(update={"llm": new_llm}) await service.switch_llm(new_llm) @@ -1908,6 +1909,7 @@ async def test_switch_profile_persists_to_meta(self, tmp_path): profile_llm = LLM(model="gpt-4o", usage_id="profile:fast", timeout=600) service._conversation = MagicMock() + service._synced_agent = stored.agent # baseline start() would establish service._conversation.agent = stored.agent.model_copy( update={"llm": profile_llm} ) @@ -1939,6 +1941,87 @@ async def test_switch_llm_inactive_service_raises_value_error(self, tmp_path): with pytest.raises(ValueError, match="inactive_service"): await service.switch_llm(LLM(model="gpt-4o", usage_id="switched")) + @pytest.mark.asyncio + async def test_sync_agent_to_meta_noop_when_agent_unchanged(self, tmp_path): + """No meta.json write when the live agent object is unchanged. + + The post-run hook calls this after every run; the identity check must + keep it a no-op for ordinary runs so meta.json is not rewritten each + turn. + """ + stored = StoredConversation( + id=uuid4(), + agent=Agent(llm=LLM(model="gpt-4o", usage_id="agent"), tools=[]), + workspace=LocalWorkspace(working_dir=str(tmp_path)), + confirmation_policy=NeverConfirm(), + initial_message=None, + metrics=None, + ) + service = EventService(stored=stored, conversations_dir=tmp_path) + service._conversation = MagicMock() + service._conversation.agent = stored.agent + # Baseline matches the live agent (as start() leaves it after resume). + service._synced_agent = stored.agent + + with patch.object(service, "save_meta", new=AsyncMock()) as save_meta: + await service._sync_agent_to_meta() + + save_meta.assert_not_awaited() + + @pytest.mark.asyncio + async def test_in_run_switch_llm_persists_to_meta(self, tmp_path): + """The agent's own switch_llm tool swaps the LLM mid-run, bypassing the + /switch_llm and /switch_profile endpoints. The post-run sync must still + mirror the new agent into meta.json so the switched timeout survives a + restart (the same reconciliation the endpoints rely on). + """ + import json + + from pydantic import SecretStr + + from openhands.sdk.testing import TestLLM + + with patch("openhands.sdk.llm.utils.model_info.httpx.get") as mock_get: + mock_get.return_value = MagicMock(json=lambda: {"data": []}) + stored = StoredConversation( + id=uuid4(), + agent=Agent( + llm=LLM( + usage_id="agent", + model="test-model", + api_key=SecretStr("x"), + timeout=300, + ), + tools=[], + ), + workspace=LocalWorkspace(working_dir=str(tmp_path / "workspace")), + ) + service = EventService( + stored=stored, conversations_dir=tmp_path / "conversations" + ) + (tmp_path / "workspace").mkdir(parents=True, exist_ok=True) + await service.start() + + # Simulate the switch_llm tool: swap the live LLM directly on the + # conversation (not via EventService.switch_llm), timeout 300 -> 600. + switched = TestLLM.from_messages( + [Message(role="assistant", content=[TextContent(text="done")])], + usage_id="switched", + ).model_copy(update={"timeout": 600}) + service.get_conversation().switch_llm(switched) + + # A run finishes on the content-only reply, firing the post-run sync. + await service.run() + run_task = service._run_task + assert run_task is not None + await asyncio.wait_for(run_task, timeout=15) + + conv_dir = (tmp_path / "conversations") / stored.id.hex + meta = json.loads((conv_dir / "meta.json").read_text()) + assert meta["agent"]["llm"]["timeout"] == 600 + + await service.close() + class TestEventServiceStartWithRunningStatus: """Test cases for EventService.start handling of RUNNING execution status.""" From 1725bafa3a8e7a62aae13990609b945d41504ea1 Mon Sep 17 00:00:00 2001 From: VascoSch92 Date: Wed, 8 Jul 2026 14:09:36 +0200 Subject: [PATCH 3/6] Persist only llm/condenser to meta.json; keep stored agent plugin-unmerged MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses review feedback (trim comments) and a correctness gap: mirroring the whole live agent baked plugin-merged agent_context/mcp_config into meta.json, which would double-merge plugins on resume (_ensure_plugins_loaded merges once per process on top of the stored agent). Instead, surgically update the stored agent's llm/condenser only — the fields a switch changes — mirroring the switch_acp_model precedent. Detection is keyed on the LLM object identity (a swap replaces it; plugin loading replaces the agent but keeps the LLM), so ordinary and plugin-loading runs stay no-ops. Add a regression test that a plugin-style agent swap is not persisted. --- .../openhands/agent_server/event_service.py | 72 +++++++++---------- tests/agent_server/test_event_service.py | 48 +++++++++++-- 2 files changed, 75 insertions(+), 45 deletions(-) diff --git a/openhands-agent-server/openhands/agent_server/event_service.py b/openhands-agent-server/openhands/agent_server/event_service.py index 3d5b6773e2a..e0d0a7d0ea9 100644 --- a/openhands-agent-server/openhands/agent_server/event_service.py +++ b/openhands-agent-server/openhands/agent_server/event_service.py @@ -86,10 +86,8 @@ class EventService: owner_instance_id: str = field(default_factory=lambda: uuid4().hex) lease_ttl_seconds: float = DEFAULT_LEASE_TTL_SECONDS _conversation: LocalConversation | None = field(default=None, init=False) - # The agent object last mirrored into meta.json. Lets _sync_agent_to_meta - # cheaply detect an LLM/profile swap (which replaces the agent object) and - # skip the no-op case where a run left the agent untouched. - _synced_agent: AgentBase | None = field(default=None, init=False) + # LLM last written to meta.json; _sync_llm_to_meta fires only when it swaps. + _synced_llm: LLM | None = field(default=None, init=False) _pub_sub: PubSub[Event] = field( default_factory=lambda: PubSub[Event](max_subscribers=50), init=False ) @@ -849,8 +847,8 @@ def _token_streaming_callback(chunk: LLMStreamChunk | str) -> None: conversation.set_confirmation_policy(self.stored.confirmation_policy) conversation.set_security_analyzer(self.stored.security_analyzer) self._conversation = conversation - # Baseline for _sync_agent_to_meta: meta.json already matches this agent. - self._synced_agent = conversation.agent + # Baseline for _sync_llm_to_meta: meta.json already matches this LLM. + self._synced_llm = conversation.agent.llm self._conversation._state.set_write_guard(self._write_guard) if not self._external_lease_renewal: self._lease_task = asyncio.create_task(self._renew_lease_loop()) @@ -1002,14 +1000,13 @@ async def _run_and_publish(): self._run_task = None await self._publish_state_update() - # Persist an in-run agent swap (the agent's switch_llm tool) - # to meta.json so it survives a restart. Best-effort: a - # failure here must not break run completion. + # Persist an in-run LLM swap (switch_llm tool); best-effort + # so it can never break run completion. try: - await self._sync_agent_to_meta() + await self._sync_llm_to_meta() except Exception: logger.exception( - "Failed to persist in-run agent change to meta.json" + "Failed to persist in-run LLM change to meta.json" ) # Re-arm a run for input stranded while this task was @@ -1431,56 +1428,55 @@ async def switch_acp_model(self, model: str) -> None: ) await self.save_meta() - async def _sync_agent_to_meta(self) -> None: - """Mirror the live agent into ``meta.json`` when it has changed. - - ``start()`` rebuilds the runtime agent from ``meta.json`` - (``self.stored.agent``) and ``ConversationState.create()`` copies it - over the persisted ``base_state.json`` on resume. So every way the live - agent's LLM can change — the ``/switch_llm`` and ``/switch_profile`` - endpoints, and the agent's own ``switch_llm`` tool mid-run — must be - written back to ``meta.json`` or it silently reverts to the - conversation's creation-time config (including the LLM ``timeout``) on - the next agent-server restart. This is the single place that persists - that change; callers just invoke it after a potential swap. - - An LLM/profile swap replaces the agent object, so the identity check - against ``_synced_agent`` makes this a no-op for the common case of a - run that left the agent untouched. ``_synced_agent`` is established in - ``start()`` alongside ``_conversation``; a ``None`` baseline means the - service was never started, so there is nothing to reconcile. + async def _sync_llm_to_meta(self) -> None: + """Persist an LLM swap into ``meta.json`` so it survives a restart. + + On resume ``start()`` rebuilds the agent from ``meta.json`` and + ``ConversationState.create()`` copies it over ``base_state.json``, so a + switch that only touched the live conversation reverts to the + creation-time LLM (and its ``timeout``). Only the stored agent's + ``llm``/``condenser`` are updated — not the whole live agent — so its + plugin-unmerged ``agent_context``/``mcp_config`` stay intact (persisting + the merged agent would double-merge plugins on resume). Keyed on LLM + object identity, so plugin loading — which replaces the agent but keeps + the LLM — is a no-op. ``_synced_llm`` is ``None`` only before start(). """ conversation = self._conversation if ( conversation is None - or self._synced_agent is None - or conversation.agent is self._synced_agent + or self._synced_llm is None + or conversation.agent.llm is self._synced_llm ): return - self.stored = self.stored.model_copy(update={"agent": conversation.agent}) - self._synced_agent = conversation.agent + agent = self.stored.agent.model_copy( + update={ + "llm": conversation.agent.llm, + "condenser": conversation.agent.condenser, + } + ) + self.stored = self.stored.model_copy(update={"agent": agent}) + self._synced_llm = conversation.agent.llm await self.save_meta() async def switch_llm(self, llm: LLM) -> None: """Swap the conversation's LLM and persist it (see - :meth:`_sync_agent_to_meta` for why the switch is mirrored to - ``meta.json``).""" + :meth:`_sync_llm_to_meta`).""" if self._conversation is None: raise ValueError("inactive_service") loop = asyncio.get_running_loop() await loop.run_in_executor(None, self._conversation.switch_llm, llm) - await self._sync_agent_to_meta() + await self._sync_llm_to_meta() async def switch_profile(self, profile_name: str) -> None: """Switch the conversation's LLM to a stored profile and persist it - (see :meth:`_sync_agent_to_meta`).""" + (see :meth:`_sync_llm_to_meta`).""" if self._conversation is None: raise ValueError("inactive_service") loop = asyncio.get_running_loop() await loop.run_in_executor( None, self._conversation.switch_profile, profile_name ) - await self._sync_agent_to_meta() + await self._sync_llm_to_meta() async def close(self): self._closing = True diff --git a/tests/agent_server/test_event_service.py b/tests/agent_server/test_event_service.py index 9c16908ba52..b044c5d5896 100644 --- a/tests/agent_server/test_event_service.py +++ b/tests/agent_server/test_event_service.py @@ -1871,7 +1871,7 @@ async def test_switch_llm_persists_to_meta(self, tmp_path): new_llm = LLM(model="gpt-4o", usage_id="switched", timeout=600) # Stand in for a live conversation whose switch_llm installed new_llm. service._conversation = MagicMock() - service._synced_agent = stored.agent # baseline start() would establish + service._synced_llm = stored.agent.llm # baseline start() would establish service._conversation.agent = stored.agent.model_copy(update={"llm": new_llm}) await service.switch_llm(new_llm) @@ -1909,7 +1909,7 @@ async def test_switch_profile_persists_to_meta(self, tmp_path): profile_llm = LLM(model="gpt-4o", usage_id="profile:fast", timeout=600) service._conversation = MagicMock() - service._synced_agent = stored.agent # baseline start() would establish + service._synced_llm = stored.agent.llm # baseline start() would establish service._conversation.agent = stored.agent.model_copy( update={"llm": profile_llm} ) @@ -1942,8 +1942,8 @@ async def test_switch_llm_inactive_service_raises_value_error(self, tmp_path): await service.switch_llm(LLM(model="gpt-4o", usage_id="switched")) @pytest.mark.asyncio - async def test_sync_agent_to_meta_noop_when_agent_unchanged(self, tmp_path): - """No meta.json write when the live agent object is unchanged. + async def test_sync_llm_to_meta_noop_when_llm_unchanged(self, tmp_path): + """No meta.json write when the live LLM is unchanged. The post-run hook calls this after every run; the identity check must keep it a no-op for ordinary runs so meta.json is not rewritten each @@ -1960,14 +1960,48 @@ async def test_sync_agent_to_meta_noop_when_agent_unchanged(self, tmp_path): service = EventService(stored=stored, conversations_dir=tmp_path) service._conversation = MagicMock() service._conversation.agent = stored.agent - # Baseline matches the live agent (as start() leaves it after resume). - service._synced_agent = stored.agent + # Baseline matches the live LLM (as start() leaves it after resume). + service._synced_llm = stored.agent.llm with patch.object(service, "save_meta", new=AsyncMock()) as save_meta: - await service._sync_agent_to_meta() + await service._sync_llm_to_meta() save_meta.assert_not_awaited() + @pytest.mark.asyncio + async def test_sync_llm_to_meta_ignores_plugin_merge(self, tmp_path): + """A run that loads plugins replaces the agent object but keeps the same + LLM. That must NOT be mirrored into meta.json: the stored agent has to + stay plugin-unmerged, or plugins double-merge on every resume. + """ + from openhands.sdk.context.agent_context import AgentContext + + stored = StoredConversation( + id=uuid4(), + agent=Agent(llm=LLM(model="gpt-4o", usage_id="agent"), tools=[]), + workspace=LocalWorkspace(working_dir=str(tmp_path)), + confirmation_policy=NeverConfirm(), + initial_message=None, + metrics=None, + ) + service = EventService(stored=stored, conversations_dir=tmp_path) + llm = stored.agent.llm + service._conversation = MagicMock() + service._synced_llm = llm + # Mimic _ensure_plugins_loaded: new agent object, merged agent_context, + # but the same LLM object. + service._conversation.agent = stored.agent.model_copy( + update={"agent_context": AgentContext(system_message_suffix="from plugin")} + ) + assert service._conversation.agent.llm is llm + + with patch.object(service, "save_meta", new=AsyncMock()) as save_meta: + await service._sync_llm_to_meta() + + save_meta.assert_not_awaited() + # The stored agent keeps its original context, not the merged one. + assert service.stored.agent.agent_context is None + @pytest.mark.asyncio async def test_in_run_switch_llm_persists_to_meta(self, tmp_path): """The agent's own switch_llm tool swaps the LLM mid-run, bypassing the From 8a5cdfce24cf1dc4747f9bee586fd785298d83bc Mon Sep 17 00:00:00 2001 From: VascoSch92 Date: Thu, 9 Jul 2026 13:40:48 +0200 Subject: [PATCH 4/6] refactor(agent-server): capture in-run LLM switch via agent-change listener Replace the post-run _sync_llm_to_meta hook with a listener on ConversationStateUpdateEvent(key="agent"), flushed at run teardown, so the in-run switch_llm tool's swap is persisted to meta.json as an event instead of polled after every run. The /switch_llm and /switch_profile endpoints keep their synchronous persist; the LLM-identity guard keeps plugin merges and ordinary runs no-ops. --- .../openhands/agent_server/event_service.py | 64 +++++++++++++------ 1 file changed, 45 insertions(+), 19 deletions(-) diff --git a/openhands-agent-server/openhands/agent_server/event_service.py b/openhands-agent-server/openhands/agent_server/event_service.py index e0d0a7d0ea9..6246859eb38 100644 --- a/openhands-agent-server/openhands/agent_server/event_service.py +++ b/openhands-agent-server/openhands/agent_server/event_service.py @@ -106,6 +106,9 @@ class EventService: _closing: bool = field(default=False, init=False) _run_lock: asyncio.Lock = field(default_factory=asyncio.Lock, init=False) _callback_wrapper: AsyncCallbackWrapper | None = field(default=None, init=False) + # Reacts to the agent-change event to mirror an in-run LLM swap into + # meta.json (see _on_conversation_event / _sync_llm_to_meta). + _meta_sync_listener: AsyncCallbackWrapper | None = field(default=None, init=False) _lease: ConversationLease | None = field(default=None, init=False) _lease_generation: int | None = field(default=None, init=False) _lease_task: asyncio.Task | None = field(default=None, init=False) @@ -773,6 +776,12 @@ async def start(self): self._callback_wrapper = AsyncCallbackWrapper( self._pub_sub, loop=asyncio.get_running_loop() ) + # Listener that mirrors an LLM swap into meta.json when the agent + # changes. The wrapper bridges worker-thread emissions onto the main + # loop, so _sync_llm_to_meta's save_meta() runs there safely. + self._meta_sync_listener = AsyncCallbackWrapper( + self._on_conversation_event, loop=asyncio.get_running_loop() + ) # Only wire token streaming for agents that can actually emit token # callbacks. SDK LLM agents need stream=True, while ACP agents emit @@ -828,7 +837,7 @@ def _token_streaming_callback(chunk: LLMStreamChunk | str) -> None: plugins=self.stored.plugins, persistence_dir=str(self.conversations_dir), conversation_id=self.stored.id, - callbacks=[self._callback_wrapper], + callbacks=[self._callback_wrapper, self._meta_sync_listener], token_callbacks=([_token_streaming_callback] if streaming_enabled else []), max_iteration_per_run=self.stored.max_iterations, stuck_detection=self.stored.stuck_detection, @@ -996,19 +1005,19 @@ async def _run_and_publish(): None, self._callback_wrapper.wait_for_pending, 30.0 ) + # An in-run switch_llm tool changes state.agent, which the + # meta-sync listener persists to meta.json off the main loop. + # Flush it here so the swap is durable before the run task + # completes (the listener is a no-op for ordinary runs). + if self._meta_sync_listener: + await loop.run_in_executor( + None, self._meta_sync_listener.wait_for_pending, 30.0 + ) + # Clear task reference and publish state update self._run_task = None await self._publish_state_update() - # Persist an in-run LLM swap (switch_llm tool); best-effort - # so it can never break run completion. - try: - await self._sync_llm_to_meta() - except Exception: - logger.exception( - "Failed to persist in-run LLM change to meta.json" - ) - # Re-arm a run for input stranded while this task was # wrapping up. A send_message(run=True) that arrived during # the wait_for_pending() tail above had its run() rejected as @@ -1428,18 +1437,35 @@ async def switch_acp_model(self, model: str) -> None: ) await self.save_meta() + async def _on_conversation_event(self, event: Event) -> None: + """Persist an in-run LLM swap the moment the agent changes. + + The agent's own ``switch_llm`` tool swaps the LLM mid-run without going + through the endpoints; that swap ends in ``state.agent = ...``, which + emits ``ConversationStateUpdateEvent(key="agent")``. Reacting to that one + event covers the tool path (the endpoints persist synchronously + themselves). Best-effort so it can never break a run; + :meth:`_sync_llm_to_meta`'s identity guard keeps ordinary runs and + plugin merges (new agent object, same LLM) a no-op. + """ + if not ( + isinstance(event, ConversationStateUpdateEvent) and event.key == "agent" + ): + return + try: + await self._sync_llm_to_meta() + except Exception: + logger.exception("Failed to persist in-run LLM change to meta.json") + async def _sync_llm_to_meta(self) -> None: """Persist an LLM swap into ``meta.json`` so it survives a restart. - On resume ``start()`` rebuilds the agent from ``meta.json`` and - ``ConversationState.create()`` copies it over ``base_state.json``, so a - switch that only touched the live conversation reverts to the - creation-time LLM (and its ``timeout``). Only the stored agent's - ``llm``/``condenser`` are updated — not the whole live agent — so its - plugin-unmerged ``agent_context``/``mcp_config`` stay intact (persisting - the merged agent would double-merge plugins on resume). Keyed on LLM - object identity, so plugin loading — which replaces the agent but keeps - the LLM — is a no-op. ``_synced_llm`` is ``None`` only before start(). + Resume rebuilds the agent from ``meta.json`` and copies it over + ``base_state.json``, so a live-only switch reverts to the creation-time + LLM (and its ``timeout``). Only ``llm``/``condenser`` are mirrored — not + the whole agent — so plugin-merged ``agent_context``/``mcp_config`` isn't + baked in (it would double-merge on resume). Keyed on LLM identity, so + plugin loading (new agent, same LLM) is a no-op. """ conversation = self._conversation if ( From 5a221bbc02dcaa6d39a696df591c64aaee69369a Mon Sep 17 00:00:00 2001 From: VascoSch92 Date: Fri, 24 Jul 2026 16:53:38 +0200 Subject: [PATCH 5/6] docs(.pr): add restart-timeout reproduction evidence for #4032 Adds the QA harness used to check whether the LLM timeout really is lost across an agent-server restart, and under which conditions. - timeout_restart_evidence.py: end-to-end reproduction against a real agent-server process (SIGKILLed and restarted on the same persistence dirs), a real mock LLM and a real agent run. Reads the timeout three ways: cold, warm, and behaviourally by stalling the LLM and measuring when the agent gives up. - no_switch_repro.py: the three no-switch paths (plain agent, agent profile launch, profile edited after creation), in-process and offline. - mock_llm.py: OpenAI-compatible mock with a switchable stall mode. - RESULTS.md: the recorded runs. Findings: the revert reproduces only when a switch leaves the live LLM diverged from meta.json, which is what this PR fixes; without a switch the creation-time timeout already survives, including at the commit the issue was filed against. Also documents that a cold read right after a restart is served from base_state.json and still reports the pre-restart value, so manual verification has to touch the conversation first. --- .pr/RESULTS.md | 154 +++++++++++ .pr/mock_llm.py | 79 ++++++ .pr/no_switch_repro.py | 237 +++++++++++++++++ .pr/timeout_restart_evidence.py | 453 ++++++++++++++++++++++++++++++++ 4 files changed, 923 insertions(+) create mode 100644 .pr/RESULTS.md create mode 100644 .pr/mock_llm.py create mode 100644 .pr/no_switch_repro.py create mode 100644 .pr/timeout_restart_evidence.py diff --git a/.pr/RESULTS.md b/.pr/RESULTS.md new file mode 100644 index 00000000000..f21bc3f1a60 --- /dev/null +++ b/.pr/RESULTS.md @@ -0,0 +1,154 @@ +# Issue #4032 — QA evidence for *LLM profile timeout is reset after agent-server restart* + +Verification for *fix(agent-server): persist LLM/profile switch to meta.json so +it survives restart*. + +Run it yourself: + +```bash +# The end-to-end reproduction: real agent-server process, SIGKILLed and +# restarted, real mock LLM, real agent run, real HTTP. +uv run python .pr/timeout_restart_evidence.py switch +uv run python .pr/timeout_restart_evidence.py noswitch + +# Point it at another checkout to see the bug on main: +uv run python .pr/timeout_restart_evidence.py switch --repo /path/to/main + +# The no-switch scenarios, in-process and fast (no network, no API key): +uv run python .pr/no_switch_repro.py +``` + +Nothing is mocked or monkeypatched inside the server. `timeout_restart_evidence.py` +starts a real `agent-server`, drives it over HTTP, kills it with `SIGKILL` +(a container stop, not a graceful shutdown), restarts it on the same +persistence dirs, and reads the conversation back. `OH_SECRET_KEY` is set so +secrets survive the restart — without it the restored conversation loses its +`api_key` and fails for a reason unrelated to the timeout. + +Environment: macOS 15 (arm64), Python 3.13, source under test at `aa22e6985`, +compared against `main` at `059ce65d9`. The reported baseline `65ee52f81` was +also checked (see §3). A full run of one scenario takes ~90 s. + +The profile under test uses `timeout=5` (the SDK default is `300`) with +`num_retries=0`, so a stalled LLM separates the two outcomes in seconds rather +than minutes. + +## 1. The bug, and that it is gone + +`switch` scenario: the conversation is created with the default timeout and +then moved onto the profile via `POST /conversations/{id}/switch_llm` — the +path the OpenHands app-server uses for its profile picker. + +**On `main`:** + +``` +>>> on-disk BEFORE restart + meta.json: [('$.agent.llm.timeout', 300)] + base_state.json: [('$.agent.llm.timeout', 5)] + +>>> SIGKILL the agent-server (container restart) + +>>> restored, COLD read (stale, from base_state.json): timeout=5, usage_id=profile-slow +>>> restored, WARM read (live, hydrated agent): timeout=300, usage_id=agent + +>>> on-disk AFTER restart + hydration + meta.json: [('$.agent.llm.timeout', 300)] + base_state.json: [('$.agent.llm.timeout', 300)] + +>>> behavioural probe — stall the LLM, watch when the agent gives up + stalled requests seen by the mock: 1 + agent gave up after: >45s (still waiting) + + => TIMEOUT PRESERVED ACROSS RESTART: False + => REVERTED 5 -> 300 (the SDK default is 300) +``` + +**With this PR:** + +``` +>>> on-disk BEFORE restart + meta.json: [('$.agent.llm.timeout', 5)] + base_state.json: [('$.agent.llm.timeout', 5)] + +>>> restored, WARM read (live, hydrated agent): timeout=5, usage_id=profile-slow + +>>> behavioural probe — stall the LLM, watch when the agent gives up + stalled requests seen by the mock: 3 + agent gave up after: 17.3s + + => TIMEOUT PRESERVED ACROSS RESTART: True +``` + +The behavioural line is the one that matters: it is not a field read back out +of a JSON file, it is the agent actually abandoning a stalled request. 17.3 s +across 3 attempts is ~5 s each — the profile's timeout. On `main` the agent was +still waiting at 45 s, consistent with the reinstated 300 s default. + +## 2. The timeout is *not* lost when no switch is involved + +This is worth stating explicitly, because the report reads as though it is. +`no_switch_repro.py` covers three no-switch paths, and +`timeout_restart_evidence.py noswitch` covers the same thing end-to-end: + +| scenario | at creation | after restart | +| --- | --- | --- | +| A. plain agent created with `timeout=600` | 600 | **600** | +| B. started from `agent_profile_id` (canvas path) | 600 | **600** | +| C. B, but the LLM profile is edited to 1234 afterwards | 600 | **600** | +| end-to-end `noswitch`, real server restart | 5 | **5** (17.3 s behavioural) | + +A profile timeout *does* reach a conversation without any switch — in +OpenHands, `POST /profiles/{name}/activate` calls `switch_to_profile()`, which +copies the profile's LLM into `agent_settings.llm`, and conversation creation +preserves `timeout` from there. That path was never broken. Only a *live* +divergence from `meta.json` reverts, and only a switch creates one. + +Scenario C is the bug report's literal repro wording ("change a profile's +timeout to 1234, restart the container"). Editing a profile does not affect an +existing conversation before *or* after a restart — the expanded LLM is frozen +at creation — so the restart is not what changes the value there. Whether a +restore should re-read the active profile is a separate design question, noted +in the PR discussion. + +## 3. The reported baseline behaves the same way + +The issue was filed against agent-server `65ee52f81`. The no-switch scenarios +were re-run against that exact commit and preserve the timeout there too (600 +at creation, 600 after restart, for both the plain-agent and `agent_profile_id` +paths). So this is not a regression introduced after the report — the +switch-not-mirrored path was the broken one all along. + +## 4. Why this was hard to pin down: the cold read lies + +The `COLD`/`WARM` split above is not an artifact of the harness, it is a real +property of the server and it explains why the symptom is so slippery. + +Persisted conversations hydrate lazily (#4100). Before hydration, +`GET /api/conversations/{id}` is answered from `base_state.json` on disk +(`_conversation_info` → `_load_persisted_state_sync`), which still holds the +**pre-restart** agent — so right after a restart the API reports the *correct* +timeout. The moment anything actually uses the conversation, +`ConversationState.create()` runs `state.agent = agent` with the agent rebuilt +from `meta.json` (`event_service.py`), and `base_state.json` is overwritten +with it. + +Net effect on `main`: a client can read back the right timeout while the agent, +on its next real request, uses the reverted one. Anyone verifying this by hand +should touch the conversation first, then read the timeout — otherwise the +stale value looks like a pass. + +With this PR the two files agree, so cold and warm reads agree too. + +## 5. Scope check + +`noswitch` was also run against this PR to confirm it does not perturb the +path it is not meant to touch: + +``` + mode: noswitch repo: sdk-pr-4028 + declared AFTER restart WARM: 5 behavioural: 17.3s + => TIMEOUT PRESERVED ACROSS RESTART: True +``` + +Identical to `main`'s result for the same scenario, as expected: the sync is a +no-op unless the live LLM object actually changed. diff --git a/.pr/mock_llm.py b/.pr/mock_llm.py new file mode 100644 index 00000000000..07c548b4728 --- /dev/null +++ b/.pr/mock_llm.py @@ -0,0 +1,79 @@ +"""Minimal OpenAI-compatible mock LLM used by ``timeout_restart_evidence.py``. + +Two modes, toggled at runtime via ``POST /_control``: + +``fast`` + answer immediately. +``hang`` + sleep ``hang_seconds`` before answering, so the *client's* configured + request timeout is what decides when it gives up. + +The hang mode is the whole point: an LLM request timeout is applied client +side, so the only way to observe which timeout the agent is really using is to +stall the server and measure when the client bails out. +""" + +from __future__ import annotations + +import asyncio +import time +from typing import Any + +from fastapi import FastAPI, Request +from fastapi.responses import JSONResponse + + +app = FastAPI() + +STATE: dict[str, Any] = { + "mode": "fast", + "hang_seconds": 600.0, + "requests": [], +} + + +@app.post("/_control") +async def control(request: Request) -> dict[str, Any]: + """Switch modes; returns the new state (minus the request log).""" + body = await request.json() + STATE.update(body) + return {"ok": True, "state": {k: v for k, v in STATE.items() if k != "requests"}} + + +@app.get("/_calls") +async def calls() -> dict[str, Any]: + """Every completion request seen so far, oldest first.""" + return {"calls": STATE["requests"]} + + +@app.post("/v1/chat/completions") +@app.post("/chat/completions") +async def completions(request: Request) -> JSONResponse: + body = await request.json() + started = time.time() + STATE["requests"].append({"at": started, "mode": STATE["mode"]}) + if STATE["mode"] == "hang": + await asyncio.sleep(float(STATE["hang_seconds"])) + return JSONResponse( + { + "id": "chatcmpl-mock", + "object": "chat.completion", + "created": int(started), + "model": body.get("model", "mock"), + "choices": [ + { + "index": 0, + "message": { + "role": "assistant", + "content": "Hello from the mock LLM.", + }, + "finish_reason": "stop", + } + ], + "usage": { + "prompt_tokens": 10, + "completion_tokens": 5, + "total_tokens": 15, + }, + } + ) diff --git a/.pr/no_switch_repro.py b/.pr/no_switch_repro.py new file mode 100644 index 00000000000..45a7813700e --- /dev/null +++ b/.pr/no_switch_repro.py @@ -0,0 +1,237 @@ +"""Issue #4032 — does the timeout revert when *no* switch is involved? + +The report was read as: "make a profile with timeout=600, talk to the agent, +restore the conversation later, and the timeout has reverted" — with no LLM or +profile switch anywhere. This script tries to reproduce exactly that, three +ways, and prints the on-disk state at every step so the result is checkable +rather than asserted. + +Run it yourself:: + + uv run python .pr/no_switch_repro.py + +No API key and no network are needed: the agent loop is never started, so the +LLM is never called. Each scenario uses a real ``ConversationService`` against +a real on-disk persistence dir, and "restart" means tearing the service down +and constructing a fresh one over the same directory — the genuine +resume-from-``meta.json`` path. + +Scenarios +--------- +A. plain agent created with ``timeout=600`` (what OpenHands sends after + ``POST /profiles/{name}/activate`` copies the profile's LLM into + ``agent_settings.llm``). +B. conversation started from an ``agent_profile_id`` whose referenced LLM + profile has ``timeout=600`` — the agent-canvas path. +C. same as B, but the LLM profile is *edited* to 1234 after the conversation + already exists. This is the literal wording of the bug report's repro + steps, so it is worth showing what it actually does. + +For the scenario that *does* revert (an LLM switch that is not mirrored into +``meta.json``), see ``timeout_restart_evidence.py``. +""" + +from __future__ import annotations + +import asyncio +import json +import os +import tempfile +from pathlib import Path +from typing import Any +from uuid import UUID, uuid4 + +from openhands.agent_server.conversation_service import ConversationService +from openhands.agent_server.models import StartConversationRequest +from openhands.sdk import LLM, Agent +from openhands.sdk.security.confirmation_policy import NeverConfirm +from openhands.sdk.workspace import LocalWorkspace + + +PROFILE_TIMEOUT = 600 +EDITED_TIMEOUT = 1234 + + +def timeouts_in(path: Path) -> list[tuple[str, Any]]: + """Every ``timeout`` value appearing anywhere in a JSON file, with paths.""" + found: list[tuple[str, Any]] = [] + + def walk(node: Any, trail: str = "$") -> None: + if isinstance(node, dict): + for key, value in node.items(): + if key == "timeout": + found.append((f"{trail}.{key}", value)) + else: + walk(value, f"{trail}.{key}") + elif isinstance(node, list): + for index, value in enumerate(node): + walk(value, f"{trail}[{index}]") + + walk(json.loads(path.read_text())) + return found + + +def dump_disk(conv_dir: Path) -> None: + for name in ("meta.json", "base_state.json"): + path = conv_dir / name + found = timeouts_in(path) if path.exists() else "" + print(f" {name}: {found}") + + +def make_llm(timeout: int, usage_id: str = "agent") -> LLM: + return LLM(model="gpt-4o", usage_id=usage_id, timeout=timeout, api_key="sk-x") + + +async def live_timeout(service: ConversationService, cid: UUID) -> int | None: + event_service = await service.get_event_service(cid) + assert event_service is not None + return event_service.get_conversation().agent.llm.timeout + + +async def scenario_a(root: Path) -> bool: + print("\n=== A. plain agent created with timeout=600, no switch ===") + root.mkdir(parents=True, exist_ok=True) + conversations = root / "conversations" + workspace = root / "workspace" + workspace.mkdir() + + request = StartConversationRequest( + agent=Agent(llm=make_llm(PROFILE_TIMEOUT), tools=[]), + workspace=LocalWorkspace(working_dir=str(workspace)), + confirmation_policy=NeverConfirm(), + ) + + async with ConversationService(conversations_dir=conversations) as primary: + info, _ = await primary.start_conversation(request) + cid = info.id + before = await live_timeout(primary, cid) + print(f" at creation: timeout={before}") + + print(" on disk after shutdown:") + dump_disk(conversations / cid.hex) + + async with ConversationService(conversations_dir=conversations) as restarted: + after = await live_timeout(restarted, cid) + print(f" after restart: timeout={after}") + + ok = before == PROFILE_TIMEOUT and after == PROFILE_TIMEOUT + print(f" => preserved: {ok}") + return ok + + +def seed_profiles(persistence: Path, timeout: int) -> UUID: + """Save an LLM profile plus an agent profile referencing it.""" + from openhands.agent_server.persistence import ( + get_agent_profile_store, + get_llm_profile_store, + reset_stores, + ) + from openhands.sdk.profiles.agent_profile import OpenHandsAgentProfile + + reset_stores() + os.environ["OH_PERSISTENCE_DIR"] = str(persistence) + + get_llm_profile_store().save("slow", make_llm(timeout), include_secrets=True) + profile = OpenHandsAgentProfile( + id=uuid4(), + name="slow-agent", + revision=1, + llm_profile_ref="slow", + tools=[], + ) + get_agent_profile_store().save(profile) + return profile.id + + +def edit_llm_profile(timeout: int) -> None: + from openhands.agent_server.persistence import get_llm_profile_store + + get_llm_profile_store().save("slow", make_llm(timeout), include_secrets=True) + + +async def scenario_b_and_c(root: Path) -> tuple[bool, bool]: + print("\n=== B. conversation started from agent_profile_id (canvas path) ===") + root.mkdir(parents=True, exist_ok=True) + persistence = root / "persistence" + persistence.mkdir() + profile_id = seed_profiles(persistence, PROFILE_TIMEOUT) + + conversations = root / "conversations" + workspace = root / "workspace" + workspace.mkdir() + + request = StartConversationRequest( + agent_profile_id=profile_id, + workspace=LocalWorkspace(working_dir=str(workspace)), + confirmation_policy=NeverConfirm(), + ) + + async with ConversationService(conversations_dir=conversations) as primary: + info, _ = await primary.start_conversation(request) + cid = info.id + before = await live_timeout(primary, cid) + print(f" at creation: timeout={before}") + + # --- scenario C starts here: edit the profile mid-conversation --- + edit_llm_profile(EDITED_TIMEOUT) + after_edit = await live_timeout(primary, cid) + print( + f" after editing the profile to {EDITED_TIMEOUT}: timeout={after_edit}" + ) + + print(" on disk after shutdown:") + dump_disk(conversations / cid.hex) + + async with ConversationService(conversations_dir=conversations) as restarted: + after = await live_timeout(restarted, cid) + print(f" after restart: timeout={after}") + + b_ok = before == PROFILE_TIMEOUT and after == PROFILE_TIMEOUT + print(f" => B preserved across restart: {b_ok}") + + print("\n=== C. profile edited after creation (the report's literal steps) ===") + c_unchanged = after_edit == PROFILE_TIMEOUT and after == PROFILE_TIMEOUT + print( + f" live value never moved to {EDITED_TIMEOUT}: " + f"before restart={after_edit}, after restart={after}" + ) + print( + " => the restart changes nothing here; an edited-but-never-switched " + f"profile is not picked up either way: {c_unchanged}" + ) + return b_ok, c_unchanged + + +async def amain() -> int: + from openhands.agent_server.persistence import reset_stores + + previous = os.environ.get("OH_PERSISTENCE_DIR") + results: list[bool] = [] + try: + with tempfile.TemporaryDirectory() as tmp: + results.append(await scenario_a(Path(tmp) / "a")) + with tempfile.TemporaryDirectory() as tmp: + b_ok, c_ok = await scenario_b_and_c(Path(tmp) / "bc") + results.extend([b_ok, c_ok]) + finally: + reset_stores() + if previous is None: + os.environ.pop("OH_PERSISTENCE_DIR", None) + else: + os.environ["OH_PERSISTENCE_DIR"] = previous + + print("\n=== SUMMARY ===") + print( + " Without a switch, the creation-time timeout survives the restart " + "in every path tested." + ) + print(f" all scenarios behaved as described: {all(results)}") + return 0 if all(results) else 1 + + +def main() -> int: + return asyncio.run(amain()) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.pr/timeout_restart_evidence.py b/.pr/timeout_restart_evidence.py new file mode 100644 index 00000000000..7ffdfea3415 --- /dev/null +++ b/.pr/timeout_restart_evidence.py @@ -0,0 +1,453 @@ +"""Issue #4032 — QA evidence for *the LLM timeout is reset after a restart*. + +Everything here is real: a real ``agent-server`` process (SIGKILLed and +restarted on the same persistence dirs), a real mock LLM, a real agent run, and +real HTTP. Nothing is mocked or monkeypatched inside the server. + +Run it yourself:: + + uv run python .pr/timeout_restart_evidence.py noswitch + uv run python .pr/timeout_restart_evidence.py switch + + # A/B against another checkout (e.g. main, to see the bug): + uv run python .pr/timeout_restart_evidence.py switch --repo /path/to/main + +Two scenarios: + +``noswitch`` + A profile carries a non-default timeout and the conversation is created + with it. This is what OpenHands does after ``POST /profiles/{name}/ + activate``, which copies the profile's LLM into ``agent_settings.llm`` + (``settings_models.py::switch_to_profile``) — so a profile timeout reaches + a conversation with no switch anywhere. No ``switch_llm`` / + ``switch_profile`` call is made at any point in this scenario. + +``switch`` + The conversation is created with the default timeout and then moved onto + the profile via ``POST /conversations/{id}/switch_llm`` — the path the + OpenHands app-server uses for its profile picker. + +The timeout is read three ways, because they disagree and that disagreement is +the most confusing part of the bug report: + +cold read + ``GET /api/conversations/{id}`` *before* the restored conversation is + hydrated. Conversations hydrate lazily (#4100), so this is answered from + ``base_state.json`` on disk (``_conversation_info`` -> + ``_load_persisted_state_sync``) and still shows the *pre-restart* agent. + It is a stale read, not the live agent. +warm read + the same endpoint after the conversation has been hydrated, which is when + ``ConversationState.create()`` actually runs and applies + ``state.agent = agent`` from ``meta.json``. +behavioural + the mock LLM stalls and we measure when the agent gives up. An LLM request + timeout is client side, so this is the only way to see the timeout the + agent is really applying. +""" + +from __future__ import annotations + +import argparse +import json +import os +import shutil +import signal +import socket +import subprocess +import sys +import tempfile +import time +from pathlib import Path +from typing import Any + +import httpx + + +HERE = Path(__file__).resolve().parent +DEFAULT_REPO = HERE.parent + +# Deliberately tiny so a stalled request reveals the effective timeout in +# seconds rather than minutes. The SDK default (``LLM.timeout``) is 300. +PROFILE_TIMEOUT = 5 +SDK_DEFAULT_TIMEOUT = 300 + +# How long we are willing to watch a stalled request before concluding the +# agent is not using PROFILE_TIMEOUT. Must sit well above PROFILE_TIMEOUT and +# well below SDK_DEFAULT_TIMEOUT so the two outcomes are unambiguous. +BEHAVIOUR_CAP = 45.0 + +# Any fixed value works; it only has to be stable across the restart, so the +# restored conversation can decrypt the api_key it persisted. Without it the +# server warns "OH_SECRET_KEY was not defined" and the restored conversation +# loses its api_key, failing for a reason unrelated to the timeout. +SECRET_KEY = "issue-4032-evidence-key-not-for-production" + + +def log(msg: str) -> None: + print(f"\n>>> {msg}", flush=True) + + +def port_free(port: int) -> bool: + """True when nothing is *listening* on the port. + + Uses connect rather than bind: a bind probe also trips on lingering + TIME_WAIT sockets from a previous run, which are harmless. + """ + with socket.socket() as sock: + sock.settimeout(0.5) + return sock.connect_ex(("127.0.0.1", port)) != 0 + + +def require_free(port: int) -> None: + if not port_free(port): + raise SystemExit( + f"port {port} is already in use. A stale server there would " + f"silently serve this run and invalidate it — kill it first." + ) + + +def wait_http(url: str, timeout: float = 180.0) -> None: + deadline = time.time() + timeout + while time.time() < deadline: + try: + httpx.get(url, timeout=2.0) + return + except httpx.HTTPError: + time.sleep(0.3) + raise SystemExit(f"timed out waiting for {url}") + + +def hard_kill(proc: subprocess.Popen[bytes] | None) -> None: + """SIGKILL the whole process group. + + ``uv run`` spawns a child python; killing only ``uv`` leaves the server + listening, which would let a stale process serve the next run. + """ + if proc is None: + return + try: + os.killpg(os.getpgid(proc.pid), signal.SIGKILL) + except (ProcessLookupError, PermissionError): + pass + try: + proc.wait(timeout=30) + except subprocess.TimeoutExpired: + pass + + +def timeouts_in(path: Path) -> list[tuple[str, Any]]: + """Every ``timeout`` value appearing anywhere in a JSON file, with paths.""" + found: list[tuple[str, Any]] = [] + + def walk(node: Any, trail: str = "$") -> None: + if isinstance(node, dict): + for key, value in node.items(): + if key == "timeout": + found.append((f"{trail}.{key}", value)) + else: + walk(value, f"{trail}.{key}") + elif isinstance(node, list): + for index, value in enumerate(node): + walk(value, f"{trail}[{index}]") + + walk(json.loads(path.read_text())) + return found + + +class Harness: + def __init__(self, mode: str, repo: Path, agent_port: int, mock_port: int): + self.mode = mode + self.repo = repo + self.agent_port = agent_port + self.mock_port = mock_port + self.agent = f"http://127.0.0.1:{agent_port}" + self.mock = f"http://127.0.0.1:{mock_port}" + # Written outside the repo on purpose: a run produces whole + # conversation dirs, and those are artifacts, not evidence to commit. + self.root = Path(tempfile.gettempdir()) / f"oh-4032-evidence-{mode}-{repo.name}" + self.server: subprocess.Popen[bytes] | None = None + self.mock_proc: subprocess.Popen[bytes] | None = None + + # -- process control --------------------------------------------------- + + def start_agent_server(self, tag: str) -> None: + require_free(self.agent_port) + env = { + **os.environ, + "OH_CONVERSATIONS_PATH": str(self.root / "conversations"), + "OH_WORKSPACE_PATH": str(self.root / "project"), + "OH_BASH_EVENTS_DIR": str(self.root / "bash_events"), + "OH_PERSISTENCE_DIR": str(self.root / "persistence"), + "OH_ENABLE_VSCODE": "false", + "OH_SECRET_KEY": SECRET_KEY, + } + logf = open(self.root / f"agent-server-{tag}.log", "w") + self.server = subprocess.Popen( + [ + "uv", + "run", + "python", + "-m", + "openhands.agent_server", + "--host", + "127.0.0.1", + "--port", + str(self.agent_port), + ], + cwd=self.repo, + env=env, + stdout=logf, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + wait_http(f"{self.agent}/health") + log(f"agent-server ({tag}) up, pid={self.server.pid} [{self.repo}]") + + def start_mock_llm(self) -> None: + require_free(self.mock_port) + logf = open(self.root / "mock-llm.log", "w") + self.mock_proc = subprocess.Popen( + [ + "uv", + "run", + "uvicorn", + "mock_llm:app", + "--host", + "127.0.0.1", + "--port", + str(self.mock_port), + "--log-level", + "warning", + ], + cwd=HERE, + env={**os.environ, "PYTHONPATH": str(HERE)}, + stdout=logf, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + wait_http(f"{self.mock}/_calls") + self.set_mock_mode("fast") + + # -- server interaction ------------------------------------------------ + + def set_mock_mode(self, mode: str, hang_seconds: float = 600.0) -> None: + httpx.post( + f"{self.mock}/_control", + json={"mode": mode, "hang_seconds": hang_seconds}, + timeout=10.0, + ) + + def mock_calls(self) -> int: + return len(httpx.get(f"{self.mock}/_calls", timeout=10.0).json()["calls"]) + + def read(self, cid: str) -> dict[str, Any]: + response = httpx.get(f"{self.agent}/api/conversations/{cid}", timeout=30.0) + response.raise_for_status() + info = response.json() + llm = info["agent"]["llm"] + return { + "timeout": llm.get("timeout"), + "usage_id": llm.get("usage_id"), + "status": info.get("execution_status"), + } + + def send(self, cid: str, text: str) -> None: + httpx.post( + f"{self.agent}/api/conversations/{cid}/events", + # run=True: SendMessageRequest.run defaults to False, and without + # it the message is appended but the agent loop never runs. + json={ + "role": "user", + "content": [{"type": "text", "text": text}], + "run": True, + }, + timeout=120.0, + ) + + def talk(self, cid: str, text: str, cap: float = 90.0) -> str: + before = self.mock_calls() + self.send(cid, text) + deadline = time.time() + cap + while time.time() < deadline: + time.sleep(0.3) + status = self.read(cid)["status"] + if self.mock_calls() > before and status != "running": + return f"{status} (llm calls: {self.mock_calls() - before})" + return f"TIMED_OUT (llm calls: {self.mock_calls() - before})" + + def behavioural_timeout(self, cid: str) -> tuple[float | None, int]: + """Stall the LLM, return (seconds until the agent gave up, requests).""" + self.set_mock_mode("hang") + before = self.mock_calls() + self.send(cid, "stall please") + + requested_at = None + deadline = time.time() + 30 + while time.time() < deadline: + if self.mock_calls() > before: + requested_at = time.time() + break + time.sleep(0.2) + if requested_at is None: + return None, 0 + + deadline = requested_at + BEHAVIOUR_CAP + while time.time() < deadline: + time.sleep(0.4) + if self.read(cid)["status"] != "running": + return time.time() - requested_at, self.mock_calls() - before + return None, self.mock_calls() - before + + def dump_disk(self, conv_dir: Path, label: str) -> None: + log(f"on-disk {label}") + for name in ("meta.json", "base_state.json"): + path = conv_dir / name + found = timeouts_in(path) if path.exists() else "" + print(f" {name}: {found}") + + # -- the scenario ------------------------------------------------------ + + def run(self) -> int: + if self.root.exists(): + shutil.rmtree(self.root) + self.root.mkdir(parents=True) + (self.root / "project").mkdir() + + require_free(self.agent_port) + require_free(self.mock_port) + log(f"mode={self.mode} repo={self.repo}") + print(f" run artifacts and server logs: {self.root}") + self.start_mock_llm() + self.start_agent_server("phase1") + + profile_llm: dict[str, Any] = { + "model": "openai/gpt-4o", + "base_url": f"{self.mock}/v1", + "api_key": "sk-mock", + "usage_id": "profile-slow", + "timeout": PROFILE_TIMEOUT, + "num_retries": 0, + } + log(f"saving LLM profile 'slow' (timeout={PROFILE_TIMEOUT})") + response = httpx.post( + f"{self.agent}/api/profiles/slow", + json={"llm": profile_llm, "include_secrets": True}, + timeout=30.0, + ) + response.raise_for_status() + + if self.mode == "noswitch": + creation_llm = {**profile_llm, "usage_id": "agent"} + else: + creation_llm = {k: v for k, v in profile_llm.items() if k != "timeout"} + creation_llm["usage_id"] = "agent" + + log("creating conversation") + response = httpx.post( + f"{self.agent}/api/conversations", + json={ + "agent": {"kind": "Agent", "llm": creation_llm, "tools": []}, + "workspace": { + "kind": "LocalWorkspace", + "working_dir": str(self.root / "project"), + }, + "confirmation_policy": {"kind": "NeverConfirm"}, + }, + timeout=180.0, + ) + response.raise_for_status() + created = response.json() + cid = created["id"] + conv_dir = Path(created["persistence_dir"]) + print(f" conversation {cid}") + print(f" at creation: {self.read(cid)}") + + if self.mode == "switch": + log("POST /switch_llm — move the conversation onto the profile's LLM") + response = httpx.post( + f"{self.agent}/api/conversations/{cid}/switch_llm", + json={"llm": profile_llm}, + timeout=60.0, + ) + response.raise_for_status() + print(f" after switch: {self.read(cid)}") + + log("talking to the agent") + print(f" run ended: {self.talk(cid, 'hello')}") + before_restart = self.read(cid)["timeout"] + self.dump_disk(conv_dir, "BEFORE restart") + + log("SIGKILL the agent-server (container restart)") + hard_kill(self.server) + self.server = None + time.sleep(1) + + self.start_agent_server("phase2") + cold = self.read(cid) + log(f"restored, COLD read (stale, from base_state.json): {cold}") + # Touching any endpoint that needs the live EventService hydrates the + # conversation, which is when ConversationState.create() really runs. + httpx.get( + f"{self.agent}/api/conversations/{cid}/events/search?limit=1", + timeout=180.0, + ) + warm = self.read(cid) + log(f"restored, WARM read (live, hydrated agent): {warm}") + self.dump_disk(conv_dir, "AFTER restart + hydration") + + self.set_mock_mode("fast") + log("behavioural probe — stall the LLM, watch when the agent gives up") + seconds, calls = self.behavioural_timeout(cid) + observed = ( + f"{seconds:.1f}s" + if seconds is not None + else f">{BEHAVIOUR_CAP:.0f}s (still waiting)" + ) + print(f" stalled requests seen by the mock: {calls}") + print(f" agent gave up after: {observed}") + + log("VERDICT") + preserved = warm["timeout"] == PROFILE_TIMEOUT + print(f" mode : {self.mode}") + print(f" repo : {self.repo}") + print(f" configured profile timeout : {PROFILE_TIMEOUT}") + print(f" declared BEFORE restart : {before_restart}") + print(f" declared AFTER restart COLD: {cold['timeout']} (stale)") + print(f" declared AFTER restart WARM: {warm['timeout']} (live agent)") + print(f" behavioural AFTER restart : {observed}") + print(f" => TIMEOUT PRESERVED ACROSS RESTART: {preserved}") + if not preserved: + print( + f" => REVERTED {before_restart} -> {warm['timeout']} " + f"(the SDK default is {SDK_DEFAULT_TIMEOUT})" + ) + return 0 if preserved else 1 + + def cleanup(self) -> None: + hard_kill(self.server) + hard_kill(self.mock_proc) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("mode", choices=["noswitch", "switch"]) + parser.add_argument( + "--repo", + type=Path, + default=DEFAULT_REPO, + help="checkout to run the agent-server from (default: this repo)", + ) + parser.add_argument("--agent-port", type=int, default=8898) + parser.add_argument("--mock-port", type=int, default=8899) + args = parser.parse_args() + + harness = Harness(args.mode, args.repo.resolve(), args.agent_port, args.mock_port) + try: + return harness.run() + finally: + harness.cleanup() + + +if __name__ == "__main__": + sys.exit(main()) From 12241acc3ad7e86860a1dac97e16f955a10b8f05 Mon Sep 17 00:00:00 2001 From: Engel Nyst Date: Fri, 24 Jul 2026 19:37:45 +0200 Subject: [PATCH 6/6] docs(.pr): independent repro for the active-profile / no-switch case (#4032) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Answers the question: profile timeout=600, made active, NEW conversation started from it, never switched — is it 600 or 300 after an agent-server restart? Independent of the existing harness: dumps both parsed paths and raw byte tokens from meta.json and base_state.json, then restarts the service over the same dir and reads the live agent timeout. Result on this branch AND on main: 600 -> 600. The active profile's LLM is copied into the agent at creation and written to both files; with no switch the two never diverge, so the meta.json rebuild reinstates the same 600. The 300 default only surfaces when a switch isn't mirrored into meta.json. Co-authored-by: smolpaws --- .pr/engel_active_profile_question.py | 166 +++++++++++++++++++++++++++ 1 file changed, 166 insertions(+) create mode 100644 .pr/engel_active_profile_question.py diff --git a/.pr/engel_active_profile_question.py b/.pr/engel_active_profile_question.py new file mode 100644 index 00000000000..94243c52b3c --- /dev/null +++ b/.pr/engel_active_profile_question.py @@ -0,0 +1,166 @@ +"""Engel's exact question (issue #4032 context): + + User makes an LLM profile with timeout=600, saves it, makes it ACTIVE, + starts a NEW conversation with that active profile, and NEVER switches. + After an agent-server restart: is the timeout 600 or 300, and why? + +This is an independent check (not the PR's own harness). It: + + 1. saves an LLM profile ``slow`` with timeout=600, + 2. references it from an agent profile (the "active profile"), + 3. starts a NEW conversation via ``agent_profile_id`` — the agent-server + equivalent of "start a conversation with the active profile", + 4. reads the LIVE agent timeout at creation, + 5. dumps the RAW meta.json / base_state.json bytes (grepping "timeout"), + 6. tears the service down and builds a fresh one over the same dir + (= an agent-server restart), touches the conversation, reads the LIVE + timeout again, + 7. prints a verdict. + +No network / API key: the agent loop never runs, so the LLM is never called. +Run: uv run python .pr/engel_active_profile_question.py +""" + +from __future__ import annotations + +import asyncio +import json +import os +import re +import tempfile +from pathlib import Path +from uuid import UUID, uuid4 + +from openhands.agent_server.conversation_service import ConversationService +from openhands.agent_server.models import StartConversationRequest +from openhands.sdk import LLM +from openhands.sdk.security.confirmation_policy import NeverConfirm +from openhands.sdk.workspace import LocalWorkspace + + +PROFILE_TIMEOUT = 600 +SDK_DEFAULT_TIMEOUT = 300 # openhands-sdk .../llm/llm.py: timeout Field(default=300) + + +def grep_timeout(path: Path) -> list[tuple[str, object]]: + found: list[tuple[str, object]] = [] + + def walk(node, trail="$"): + if isinstance(node, dict): + for k, v in node.items(): + if k == "timeout": + found.append((f"{trail}.{k}", v)) + else: + walk(v, f"{trail}.{k}") + elif isinstance(node, list): + for i, v in enumerate(node): + walk(v, f"{trail}[{i}]") + + walk(json.loads(path.read_text())) + return found + + +def raw_timeout_tokens(path: Path) -> list[str]: + """Prove it from the literal bytes, not just parsed structure.""" + text = path.read_text() + return re.findall(r'"timeout"\s*:\s*[0-9]+', text) + + +def make_llm(timeout: int) -> LLM: + return LLM(model="gpt-4o", usage_id="agent", timeout=timeout, api_key="sk-x") + + +def seed_active_profile(persistence: Path, timeout: int) -> UUID: + from openhands.agent_server.persistence import ( + get_agent_profile_store, + get_llm_profile_store, + reset_stores, + ) + from openhands.sdk.profiles.agent_profile import OpenHandsAgentProfile + + reset_stores() + os.environ["OH_PERSISTENCE_DIR"] = str(persistence) + # 1) LLM profile with the user's chosen timeout, saved. + get_llm_profile_store().save("slow", make_llm(timeout), include_secrets=True) + # 2) An agent profile that references it — this is the "active profile". + profile = OpenHandsAgentProfile( + id=uuid4(), name="slow-agent", revision=1, llm_profile_ref="slow", tools=[] + ) + get_agent_profile_store().save(profile) + return profile.id + + +async def live_timeout(service: ConversationService, cid: UUID) -> int | None: + event_service = await service.get_event_service(cid) + assert event_service is not None + return event_service.get_conversation().agent.llm.timeout + + +async def amain() -> int: + from openhands.agent_server.persistence import reset_stores + + previous = os.environ.get("OH_PERSISTENCE_DIR") + try: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + persistence = root / "persistence" + persistence.mkdir(parents=True) + conversations = root / "conversations" + workspace = root / "workspace" + workspace.mkdir() + + profile_id = seed_active_profile(persistence, PROFILE_TIMEOUT) + print(f"Saved LLM profile 'slow' timeout={PROFILE_TIMEOUT}, made active.") + print( + f"SDK default timeout if nothing carried it = {SDK_DEFAULT_TIMEOUT}\n" + ) + + request = StartConversationRequest( + agent_profile_id=profile_id, + workspace=LocalWorkspace(working_dir=str(workspace)), + confirmation_policy=NeverConfirm(), + ) + + # ---- start a NEW conversation with the active profile, no switch ---- + async with ConversationService(conversations_dir=conversations) as svc: + info, _ = await svc.start_conversation(request) + cid = info.id + created = await live_timeout(svc, cid) + print(f"[create] live agent llm.timeout = {created}") + + conv_dir = conversations / cid.hex + print("\n[on disk after shutdown] (parsed paths + raw byte tokens)") + for name in ("meta.json", "base_state.json"): + p = conv_dir / name + print(f" {name}") + print(f" parsed: {grep_timeout(p)}") + print(f" raw : {raw_timeout_tokens(p)}") + + # ---- restart the agent-server (fresh service, same dir) ---- + async with ConversationService(conversations_dir=conversations) as svc2: + restarted = await live_timeout(svc2, cid) # touch => hydrate + print(f"\n[after restart] live agent llm.timeout = {restarted}") + + print("\n=== VERDICT ===") + verdict = "600" if restarted == PROFILE_TIMEOUT else str(restarted) + print(f" It is {verdict}.") + print( + " Why: the active profile's LLM (timeout=600) is copied into the " + "conversation's\n agent at CREATION and persisted to BOTH files. " + "With no switch, the two files\n never diverge, so the restart " + "rebuild from meta.json reinstates the SAME 600.\n The 300 default " + "only appears if some path builds an LLM WITHOUT carrying the\n " + "profile's value — which is what a switch that isn't mirrored into " + "meta.json does." + ) + return 0 if restarted == PROFILE_TIMEOUT else 1 + finally: + reset_stores() + if previous is None: + os.environ.pop("OH_PERSISTENCE_DIR", None) + else: + os.environ["OH_PERSISTENCE_DIR"] = previous + + +if __name__ == "__main__": + raise SystemExit(asyncio.run(amain()))