{"record":{"id":"6f1682d4fd44d086","repo":"microsoft/autogen","slug":"host-connection-is-not-set","errorCode":null,"errorMessage":"Host connection is not set.","messagePattern":"Host connection is not set\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"python/packages/autogen-ext/src/autogen_ext/runtimes/grpc/_worker_runtime.py","lineNumber":362,"sourceCode":"        # Wait for the signal to trigger the shutdown event.\n        await shutdown_event.wait()\n\n        # Stop the runtime.\n        await self.stop()\n\n    @property\n    def _known_agent_names(self) -> Set[str]:\n        return set(self._agent_factories.keys())\n\n    async def _send_message(\n        self,\n        runtime_message: agent_worker_pb2.Message,\n        send_type: Literal[\"send\", \"publish\"],\n        recipient: AgentId | TopicId,\n        telemetry_metadata: Mapping[str, str],\n    ) -> None:\n        if self._host_connection is None:\n            raise RuntimeError(\"Host connection is not set.\")\n        with self._trace_helper.trace_block(send_type, recipient, parent=telemetry_metadata):\n            await self._host_connection.send(runtime_message)\n\n    async def send_message(\n        self,\n        message: Any,\n        recipient: AgentId,\n        *,\n        sender: AgentId | None = None,\n        cancellation_token: CancellationToken | None = None,\n        message_id: str | None = None,\n    ) -> Any:\n        # TODO: use message_id\n        if not self._running:\n            raise ValueError(\"Runtime must be running when sending message.\")\n        if self._host_connection is None:\n            raise RuntimeError(\"Host connection is not set.\")\n        data_type = self._serialization_registry.type_name(message)","sourceCodeStart":344,"sourceCodeEnd":380,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-ext/src/autogen_ext/runtimes/grpc/_worker_runtime.py#L344-L380","documentation":"GrpcWorkerAgentRuntime._send_message sends a protobuf runtime message over the host connection; if the internal _host_connection is None (runtime never started, or connection already torn down) it raises RuntimeError('Host connection is not set.'). This is the internal chokepoint used by both send_message and publish_message paths.","triggerScenarios":"A background publish/send task created before stop() completes executes after the host connection is closed, or calling the runtime's messaging APIs from a path that bypassed start() — the public methods also check _running first, so this is typically seen from fire-and-forget tasks racing stop().","commonSituations":"Publishing messages from tasks that outlive runtime.stop(); awaiting runtime.stop() while background tasks queued via _background_tasks are still sending; tests that construct the runtime and call internals directly.","solutions":["Ensure `await runtime.stop()` has drained in-flight sends (stop() gathers background tasks) before closing/awaiting further operations","Never fire publish_message/send_message after stop(); check runtime state before enqueueing work","Catch RuntimeError in wrappers that may race shutdown and treat it as a cancellation"],"exampleFix":"# before\ntask = asyncio.create_task(publish_later(runtime))\nawait runtime.stop()  # task may then hit 'Host connection is not set.'\n\n# after\nawait runtime.stop()  # stop() drains background tasks first\ntask.cancel()","handlingStrategy":"try-catch","validationCode":"# Avoid hitting it: never enqueue sends after stop(); ensure background tasks are awaited by stop() first\nif shutting_down.is_set():\n    raise OperationRejected(\"runtime shutting down\")","typeGuard":null,"tryCatchPattern":"try:\n    await runtime.publish_message(msg, topic)\nexcept RuntimeError as e:\n    if \"Host connection is not set\" in str(e):\n        log.warning(\"send after shutdown dropped\")\n    else:\n        raise","preventionTips":["Signal shutdown and stop publishing before calling runtime.stop()","Track pending background sends and drain them before stop","Treat this RuntimeError as an expected shutdown race, not a crash"],"tags":["python","autogen","grpc","lifecycle","race-condition"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}