{"record":{"id":"f322e7b558914712","repo":"microsoft/autogen","slug":"runtime-must-be-running-when-publishing-message","errorCode":null,"errorMessage":"Runtime must be running when publishing message.","messagePattern":"Runtime must be running when publishing message\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"python/packages/autogen-ext/src/autogen_ext/runtimes/grpc/_worker_runtime.py","lineNumber":423,"sourceCode":"\n            # TODO: Find a way to handle timeouts/errors\n            task = asyncio.create_task(self._send_message(runtime_message, \"send\", recipient, telemetry_metadata))\n            self._background_tasks.add(task)\n            task.add_done_callback(self._raise_on_exception)\n            task.add_done_callback(self._background_tasks.discard)\n            return await future\n\n    async def publish_message(\n        self,\n        message: Any,\n        topic_id: TopicId,\n        *,\n        sender: AgentId | None = None,\n        cancellation_token: CancellationToken | None = None,\n        message_id: str | None = None,\n    ) -> None:\n        if not self._running:\n            raise ValueError(\"Runtime must be running when publishing message.\")\n        if self._host_connection is None:\n            raise RuntimeError(\"Host connection is not set.\")\n        if message_id is None:\n            message_id = str(uuid.uuid4())\n\n        message_type = self._serialization_registry.type_name(message)\n        with self._trace_helper.trace_block(\n            \"create\", topic_id, parent=None, extraAttributes={\"message_type\": message_type}\n        ):\n            serialized_message = self._serialization_registry.serialize(\n                message, type_name=message_type, data_content_type=self._payload_serialization_format\n            )\n\n            sender_id = sender or AgentId(\"unknown\", \"unknown\")\n            attributes = {\n                _constants.DATA_CONTENT_TYPE_ATTR: cloudevent_pb2.CloudEvent.CloudEventAttributeValue(\n                    ce_string=self._payload_serialization_format\n                ),","sourceCodeStart":405,"sourceCodeEnd":441,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-ext/src/autogen_ext/runtimes/grpc/_worker_runtime.py#L405-L441","documentation":"GrpcWorkerAgentRuntime.publish_message requires the runtime to be running: if _running is False it raises ValueError('Runtime must be running when publishing message.') since publishing needs the host connection established by start().","triggerScenarios":"Calling `await runtime.publish_message(msg, topic_id)` before await runtime.start() completes or after stop(); registering a callback/type that publishes during registration before start.","commonSituations":"Publishing from module-level or __init__ code of an agent or service before the runtime started; shutdown ordering where background publishers outlive stop(); notebook cell re-runs.","solutions":["Await runtime.start() before any publish_message call","Move eager publishes from constructors into the agent's first message handler or an explicit on_start hook","Gate publishers on runtime state during shutdown to avoid racing stop()"],"exampleFix":"# before\nawait runtime.publish_message(event, topic)  # before start()\nawait runtime.start()\n\n# after\nawait runtime.start()\nawait runtime.publish_message(event, topic)","handlingStrategy":"validation","validationCode":"if not started:\n    await runtime.start()\n    started = True\nawait runtime.publish_message(event, topic)","typeGuard":null,"tryCatchPattern":"try:\n    await runtime.publish_message(event, topic)\nexcept ValueError as e:\n    if \"must be running\" in str(e):\n        await runtime.start()\n        await runtime.publish_message(event, topic)\n    else:\n        raise","preventionTips":["Await start() before publishing","Delay publishers (timers, queues) until after startup completes","Stop background publishers before calling stop()"],"tags":["python","autogen","grpc","lifecycle","pubsub"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}