[Bug]: Streaming follow-up on an existing task does not begin with a Task; enqueuing the current task drops the follow-up message from history
Mantenedores costumam responder em até 2 dias
Avaliação
Esta issue ainda não foi avaliada.
Descrição
What happened?
When a client continues an existing task with SendStreamingMessage (for example, after TASK_STATE_INPUT_REQUIRED), the stream does not begin with a Task object. The spec requires one, in §3.1.2 Send Streaming Message, Behavior 2:
If the agent returns a Task, the stream MUST begin with the Task object, followed by zero or more TaskStatusUpdateEvent or TaskArtifactUpdateEvent objects.
The executor cannot fix this from its side. Enqueueing the current task first, as the v1.0 migration guide shows (task = context.current_task or new_task_from_user_message(...) followed by enqueue_event(task)), makes the stream start with a Task. But the follow-up user message is then never written to the task history, and an ERROR is logged.
Reproduced on a2a-sdk 1.1.5 and 1.2.1. I found no change to the affected code on main since 1.2.1.
Expected: a streamed follow-up on an existing task begins with a Task (its current state), and the follow-up user message is added to Task.history.
Actual (reproduction below):
| Executor | 2nd stream | history after 2nd turn |
|---|---|---|
enqueues Task only for a new task (as in tests/integration/test_end_to_end.py) |
status_update, status_update, no leading Task |
user 1, agent, user 2 |
always enqueues context.current_task first (migration guide) |
task, status_update, status_update |
user 1, agent. User 2 is missing, and ERROR … already exists. Ignoring task replacement. is logged |
Where it comes from (v1.2.1)
default_request_handler_v2.py#L466:on_message_send_streamsubscribes withinclude_initial_task=False, so the handler never emits the stored task. The leadingTaskhas to come from the executor.active_task.py#L274-L283: when the executor enqueues aTaskand the task already exists,_handle_initial_tasklogs the ERROR, ignores the event, and still setsself.message_to_save = None. The follow-up message was stored inmessage_to_savewhen the request started, so_handle_task_modification_eventno longer adds it to history.active_task.py#L291-L299: theInvalidAgentResponseErrorcheck added in #979 ("Agent should enqueue Task before …") only fires when no task exists yet, so a continuation without a leadingTaskpasses silently.test_end_to_end.py#L589-L596:test_end_to_end_input_requiredcurrently expects the follow-up stream to bestatus_update, artifact_update, status_update.
Related
- #965 was fixed for new tasks by #979.
- The earlier attempt #964 injected
Task(SUBMITTED)in the handler, but only whennot params.message.task_id, so continuations were out of scope there too. - #1188 concerns resuming from a stale snapshot after
input_required. It's related but different: that report is about multi-replica state, and this one reproduces on a single in-memory replica.
Possible directions (maintainers will know better)
- Handler: for a message that carries
task_idof an existing task, emit the stored task as the first stream event, ason_subscribe_to_taskalready does withinclude_initial_task=True. Ideally that snapshot would already include the follow-up message. - Consumer: when the executor enqueues a
Taskwhose id matches the existing task, treat it as "emit current state": keep or applymessage_to_saveand don't log an ERROR. That would make the migration-guide pattern correct.
I'm happy to test a fix. Which direction do you prefer?
Reproduction
Self-contained. Needs a2a-sdk[http-server] (and httpx). Run python repro.py for row 1 and python repro.py --always for row 2.
import asyncio
import logging
import sys
import httpx
from a2a.client import ClientConfig, ClientFactory
from a2a.helpers.proto_helpers import new_task_from_user_message
from a2a.server.agent_execution import AgentExecutor, RequestContext
from a2a.server.events import EventQueue
from a2a.server.request_handlers import DefaultRequestHandler
from a2a.server.routes import create_agent_card_routes, create_jsonrpc_routes
from a2a.server.tasks import TaskUpdater
from a2a.server.tasks.inmemory_task_store import InMemoryTaskStore
from a2a.types import (
AgentCapabilities,
AgentCard,
AgentInterface,
GetTaskRequest,
Message,
Part,
Role,
SendMessageRequest,
TaskState,
)
from a2a.utils import TransportProtocol
from starlette.applications import Starlette
ALWAYS_ENQUEUE_TASK = '--always' in sys.argv
class Executor(AgentExecutor):
async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:
task = context.current_task or new_task_from_user_message(context.message)
if ALWAYS_ENQUEUE_TASK or context.current_task is None:
await event_queue.enqueue_event(task)
updater = TaskUpdater(event_queue, task.id, task.context_id)
await updater.update_status(TaskState.TASK_STATE_WORKING)
if context.current_task is None:
await updater.update_status(
TaskState.TASK_STATE_INPUT_REQUIRED,
message=updater.new_agent_message([Part(text='Which one?')]),
)
else:
await updater.complete()
async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:
raise NotImplementedError
async def main() -> None:
card = AgentCard(
name='repro',
description='repro',
version='1.0.0',
capabilities=AgentCapabilities(streaming=True),
default_input_modes=['text/plain'],
default_output_modes=['text/plain'],
supported_interfaces=[
AgentInterface(protocol_binding=TransportProtocol.JSONRPC, url='http://testserver')
],
)
handler = DefaultRequestHandler(
agent_executor=Executor(), task_store=InMemoryTaskStore(), agent_card=card
)
app = Starlette(
routes=[
*create_agent_card_routes(agent_card=card, card_url='/'),
*create_jsonrpc_routes(request_handler=handler, rpc_url='/'),
]
)
http = httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://testserver')
client = ClientFactory(
ClientConfig(httpx_client=http, supported_protocol_bindings=[TransportProtocol.JSONRPC])
).create(card)
async def send(text: str, task_id: str | None = None) -> list:
message = Message(role=Role.ROLE_USER, message_id=f'msg-{text}', parts=[Part(text=text)])
if task_id:
message.task_id = task_id
return [e async for e in client.send_message(SendMessageRequest(message=message))]
first = await send('first')
task_id = first[0].task.id
second = await send('second', task_id)
task = await client.get_task(GetTaskRequest(id=task_id))
print('first stream: ', [e.WhichOneof('payload') for e in first])
print('second stream:', [e.WhichOneof('payload') for e in second])
print('final state: ', TaskState.Name(task.status.state))
print('history: ', [(Role.Name(m.role), m.message_id) for m in task.history])
if __name__ == '__main__':
logging.basicConfig(level=logging.ERROR, format='%(levelname)s %(name)s: %(message)s')
asyncio.run(main())
Environment: a2a-sdk 1.1.5 (PyPI) and 1.2.1 (tag v1.2.1), Python 3.14, macOS, JSON-RPC transport, InMemoryTaskStore.
Relevant log output
$ python repro.py
first stream: ['task', 'status_update', 'status_update']
second stream: ['status_update', 'status_update']
final state: TASK_STATE_COMPLETED
history: [('ROLE_USER', 'msg-first'), ('ROLE_AGENT', '<uuid>'), ('ROLE_USER', 'msg-second')]
$ python repro.py --always
ERROR a2a.server.agent_execution.active_task: Task <uuid> already exists. Ignoring task replacement.
first stream: ['task', 'status_update', 'status_update']
second stream: ['task', 'status_update', 'status_update']
final state: TASK_STATE_COMPLETED
history: [('ROLE_USER', 'msg-first'), ('ROLE_AGENT', '<uuid>')]
Code of Conduct
- I agree to follow this project's Code of Conduct
- Linguagem predominante
- Python
- Estrelas
- 2.2k
- Forks
- 518
- Merge médio
- 3d 12h
- PRs com merge (30d)
- 39
Preparar o ambiente
- Sem Dockerfile nem arquivo Docker Compose
- Tem um modelo de pull request
- Ler o guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Mais de a2aproject/a2a-python
-
[Bug]: `A2A-Version` validation ignores minor versions and the query parameterTalvez já em andamento @rohityan assumiu há 60 dias. Abertacomponent: server status:awaiting response
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 75/100
a2aproject/a2a-python#1204 · 3 comentários · 1 responsável ·
Mantenedores costumam responder em até 2 dias
-
[Bug]: REST task/request id sanitizationTalvez já em andamento @Linux2010 assumiu há 119 dias. Abertamaintainers-only
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 65/100
a2aproject/a2a-python#805 · 1 comentário ·
Mantenedores costumam responder em até 2 dias
-
[Bug]: TaskEventStream methods don't receive ServerCallContextTalvez já em andamento @rohityan assumiu há 2 dias. Aberta
a2aproject/a2a-python#1374 · 2 responsáveis ·
Mantenedores costumam responder em até 2 dias
-
[Bug]: v0.3 JSON-RPC compat adapter returns -32603 for all A2A errors (e.g. TaskNotFound should be -32001)Talvez já em andamento @shwetangsinha0509 assumiu há 2 dias. Abertacomponent: server status:awaiting response
a2aproject/a2a-python#1368 · 2 comentários · 1 responsável ·
Mantenedores costumam responder em até 2 dias
-
[Bug]: VersionedDatabaseTaskStore get() and delete() fail with "no such table" when initialize() was not calledTalvez já em andamento @cchinchilla-dev assumiu há 3 dias. Abertacomponent: server status:awaiting response
a2aproject/a2a-python#1356 · 1 comentário · 1 responsável ·
Mantenedores costumam responder em até 2 dias
Todas as issues de a2aproject/a2a-python
Issues semelhantes
-
intake mcp-intake needs-ac needs-human-review priority:medium
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 67/100
Ikalus1988/MisakaNet#3848 · 2 comentários ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 75/100
521xueweihan/HelloGitHub#4105 ·
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 75/100
igormcsouza/bookloud#54 ·
-
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 90/100
aws-samples/sample-per-model-bedrock#526 ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 78/100
ok-oldking/ok-wuthering-waves#1802 ·
Mantenedores costumam responder em até 2 dias