Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/a2a/server/agent_execution/active_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -979,6 +979,9 @@ async def cancel(
updated = Task()
updated.CopyFrom(task)
updated.status.state = TaskState.TASK_STATE_CANCELED
# CopyFrom carried over the previous state's timestamp; a terminal
# transition has to be stamped with its own time.
updated.status.timestamp.FromDatetime(datetime.now(timezone.utc))
await self._task_manager.save_task_event(updated)
task = updated
return task
Expand Down Expand Up @@ -1113,6 +1116,7 @@ async def _mark_task_as_failed(self, exception: Exception) -> Task | None:
context_id=task.context_id,
status=TaskStatus(
state=TaskState.TASK_STATE_FAILED,
timestamp=datetime.now(timezone.utc),
),
)
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import warnings

from contextlib import aclosing
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, cast

from a2a.plugins.manager import get_global
Expand Down Expand Up @@ -354,6 +355,9 @@ async def _write_cancel(
cancelled = Task()
cancelled.CopyFrom(current)
cancelled.status.state = TaskState.TASK_STATE_CANCELED
# CopyFrom carried over the previous state's timestamp; stamping here
# also covers the event built from this status below.
cancelled.status.timestamp.FromDatetime(datetime.now(timezone.utc))
event = TaskStatusUpdateEvent(
task_id=task_id,
context_id=current.context_id,
Expand Down
19 changes: 18 additions & 1 deletion src/a2a/server/tasks/task_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import logging

from datetime import datetime, timezone
from typing import TYPE_CHECKING

from a2a.plugins.types import TaskEventInfo
Expand Down Expand Up @@ -220,6 +221,15 @@ async def get_task(self) -> Task | None:
logger.debug('Task %s not found.', self.task_id)
return self._current_task

def _stamp_status_timestamp(
self, holder: Task | TaskStatusUpdateEvent
) -> None:
"""Supply a timestamp for a status when the agent did not provide one."""
if holder.HasField('status') and not holder.status.HasField(
'timestamp'
):
holder.status.timestamp.FromDatetime(datetime.now(timezone.utc))

async def save_task_event(
self, event: Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent
) -> Task | None:
Expand Down Expand Up @@ -260,6 +270,7 @@ async def save_task_event(
task_id_from_event,
)
if isinstance(event, Task):
self._stamp_status_timestamp(event)
self._pending_event = event
try:
await self._save_task(event)
Expand All @@ -278,6 +289,10 @@ async def save_task_event(
logger.debug(
'Updating task %s status to: %s', task.id, event.status.state
)
# Stamped on the event, not the copy below: the same event object
# is published to subscribers, push notifications and the event
# table, so it has to carry the timestamp too.
self._stamp_status_timestamp(event)
if task.status.HasField('message'):
task.history.append(task.status.message)
if event.metadata:
Expand Down Expand Up @@ -383,12 +398,14 @@ def _init_task_obj(self, task_id: str, context_id: str) -> Task:
context_id,
)
history = [self._initial_message] if self._initial_message else []
return Task(
task = Task(
id=task_id,
context_id=context_id,
status=TaskStatus(state=TaskState.TASK_STATE_SUBMITTED),
history=history,
)
self._stamp_status_timestamp(task)
return task

async def _save_task(self, task: Task) -> None:
"""Saves the task and updates the snapshot.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2080,6 +2080,7 @@ async def test_on_message_send_non_blocking():
assert result is not None
assert isinstance(result, Task)
assert result.status.state == TaskState.TASK_STATE_SUBMITTED
assert result.status.HasField('timestamp')


@pytest.mark.asyncio
Expand Down Expand Up @@ -3669,6 +3670,21 @@ async def cancel(self, context: RequestContext, event_queue: EventQueue):
pass


class ExplodingExecutor(AgentExecutor):
"""Creates the task, then crashes mid-flight (issue #1331)."""

task_id = None

async def execute(self, context: RequestContext, event_queue: EventQueue):
task = new_task_from_user_message(context.message)
self.task_id = task.id
await event_queue.enqueue_event(task)
raise RuntimeError('agent crashed mid-flight')

async def cancel(self, context: RequestContext, event_queue: EventQueue):
pass


@pytest.mark.asyncio
async def test_on_message_send_raises_when_agent_produces_no_events():
"""A silent executor must fail fast instead of hanging forever (#1330)."""
Expand Down Expand Up @@ -3718,3 +3734,37 @@ async def test_on_message_send_stream_raises_when_agent_produces_no_events():
params, create_server_call_context()
):
pass


@pytest.mark.asyncio
async def test_framework_failure_persists_timestamp_on_failed_task():
"""A framework-written FAILED status carries a timestamp (#1331)."""
task_store = InMemoryTaskStore()
executor = ExplodingExecutor()
request_handler = DefaultRequestHandlerV2(
agent_executor=executor,
task_store=task_store,
agent_card=create_default_agent_card(),
)
params = SendMessageRequest(
message=Message(
role=Role.ROLE_USER,
message_id='msg_explode',
parts=[Part(text='Hi')],
),
configuration=SendMessageConfiguration(
accepted_output_modes=['text/plain']
),
)

with pytest.raises(RuntimeError, match='agent crashed mid-flight'):
await request_handler.on_message_send(
params, create_server_call_context()
)

stored = await task_store.get(
executor.task_id, create_server_call_context()
)
assert stored is not None
assert stored.status.state == TaskState.TASK_STATE_FAILED
assert stored.status.HasField('timestamp')
36 changes: 36 additions & 0 deletions tests/server/tasks/test_database_task_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
from a2a.compat.v0_3.model_conversions import core_to_compat_task_model
from a2a.server.context import ServerCallContext
from a2a.server.models import Base, TaskModel # Important: To get Base.metadata
from a2a.server.tasks import TaskManager
from a2a.server.tasks.database_task_store import DatabaseTaskStore
from a2a.types.a2a_pb2 import (
Artifact,
Expand All @@ -33,6 +34,7 @@
Task,
TaskState,
TaskStatus,
TaskStatusUpdateEvent,
)
from a2a.utils.constants import DEFAULT_LIST_TASKS_PAGE_SIZE
from a2a.utils.errors import InvalidParamsError
Expand Down Expand Up @@ -227,6 +229,40 @@ async def test_get_task(db_store_parameterized: DatabaseTaskStore) -> None:
) # Cleanup


@pytest.mark.asyncio
async def test_manager_timestamps_support_database_status_filter(
db_store_parameterized: DatabaseTaskStore,
) -> None:
manager = TaskManager(
task_id='timestamp-filter-task',
context_id='timestamp-filter-context',
task_store=db_store_parameterized,
initial_message=None,
context=TEST_CONTEXT,
)
event = TaskStatusUpdateEvent(
task_id='timestamp-filter-task',
context_id='timestamp-filter-context',
status=TaskStatus(state=TaskState.TASK_STATE_WORKING),
)
await manager.save_task_event(event)
assert event.status.HasField('timestamp')

timestamp = event.status.timestamp.ToDatetime(tzinfo=timezone.utc)
request = ListTasksRequest(status=TaskState.TASK_STATE_WORKING)
request.status_timestamp_after.FromDatetime(
timestamp - timedelta(seconds=1)
)
listed = await db_store_parameterized.list(request, TEST_CONTEXT)
assert [task.id for task in listed.tasks] == ['timestamp-filter-task']

request.status_timestamp_after.FromDatetime(
timestamp + timedelta(seconds=1)
)
listed = await db_store_parameterized.list(request, TEST_CONTEXT)
assert not listed.tasks


@pytest.mark.asyncio
@pytest.mark.parametrize(
'params, expected_ids, total_count, next_cursor',
Expand Down
Loading
Loading