Files
microsoft--agent-framework/python/packages/devui/tests/devui/test_checkpoints.py
Eduard van Valkenburg 6e95517659 Python: Split type checkers by target (pyright source, 5 checkers on tests/samples) (#6443)
* Python: Split type checkers by target (pyright source, 5 checkers on tests/samples)

Rework the typing setup along the lines of the 'too many type checkers'
approach:

- Pyright (strict) is now the sole source-code type checker; mypy is
  removed from source and its [tool.mypy] block becomes a relaxed profile
  used only for tests/samples.
- Tests are checked by all five checkers (pyright relaxed, mypy, pyrefly,
  ty, zuban); samples by pyright, pyrefly, and ty. All run in a relaxed/
  basic profile so authors aren't forced into over-annotation.
- Add pyrightconfig.tests.json and bump sample pyright configs to basic.
- Unify test/sample typing onto the same parallel fan-out used by source
  pyright via run_command_items in task_runner.py.
- Make version-conditional imports symmetric: keep or drop the
  '# type: ignore' on both branches so results match across interpreter
  versions (local vs CI).
- Update SKILL.md, DEV_SETUP.md, and CODING_STANDARD.md for the five
  gating checkers and pyright on source+tests+samples.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Python: Fix merge regressions from main (typing + runtime)

Merging main into the type-checker split branch surfaced regressions that
the new five-checker test suite and unit tests caught:

Runtime fixes:
- anthropic: restore the dropped `cache_read_input_token_count` mapping in
  _parse_usage_from_anthropic (lost during merge conflict resolution).
- gemini: _get_function_calling_mode test helper returned str(enum)
  ('FunctionCallingConfigMode.AUTO') instead of the enum value ('AUTO').
- openai: _response_id_from_token test helper was an infinite self-recursion;
  return token['response_id'].
- orchestrations: reset output_events per approval iteration so the terminal
  output assertion counts only the final run.
- core: drop a stale duplicate harness test whose message ('non-negative')
  contradicted the source ('positive').
- purview: import PolicyLocation/PolicyScope/ProtectionScopeActivities/
  ExecutionMode used by the processor tests.

Type-checker fixes (tests, relaxed profile):
- core: pyright/mypy/pyrefly/ty/zuban green-ups across the harness, MCP,
  observability and types tests.
- anthropic/openai: route provider-namespaced UsageDetails keys through a
  dict cast (extra_items TypedDict unsupported by mypy/ty).
- purview: typed model constructors and cache-mock casts.
- ag-ui: annotate WorkflowContext[Any, Any] so yield_output accepts test
  payloads, guard Optional forwarded_props, and ty-ignore intentional bad args.

Source pyright (sole source checker) flagged unnecessary ignores newly
introduced by merged code in core _tools.py and declarative _declarative_base.py.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Python: Isolate per-package mypy cache in test-typing fan-out

The parallel test-typing fan-out runs many mypy processes concurrently,
all defaulting to a single shared ./.mypy_cache. Concurrent writes corrupt
the cache and mypy aborts with INTERNAL ERROR (intermittently, depending on
worker timing) -- which is why CI's Test Typing job failed on a shifting set
of packages while a single-package run was fine.

Give each mypy invocation an isolated cache dir keyed by its target paths so
incremental caching still works per package without races. Other checkers
(zuban/pyrefly/ty/pyright) maintain their own caches and are unaffected.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Python: Make lab pyright-only on source (drop source mypy)

Lab was the last package still running mypy on its source code, requiring
mypy-only `# type: ignore` comments that pyright (the sole source checker
everywhere else) flags as unnecessary. Align lab with the rest of the
monorepo:

- Remove the lab source mypy poe tasks (mypy-gaia/lightning/tau2) and the
  now-dead strict [tool.mypy] config block.
- Drop the 'Run lab mypy' CI step; lab source is type-checked by pyright only.

Lab tests remain covered by the workspace test-typing fan-out (mypy, pyrefly,
ty, zuban, pyright over tests using the relaxed root config).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Python: Fix test-typing regressions from latest main merge

A fresh merge from main brought in new test code never run under the
five-checker test-typing suite. Green up across the affected packages:

- core: narrow Optional span.attributes with 'and' guards in span filters
  and assert+cast the json.loads(...attributes[...]) reads (test_observability);
  match the existing as_agent ignore on the protocol-typed fixture (test_clients).
- openai: align new streaming tests with the established chat_options dict
  pattern (ChatOptions TypedDict isn't assignable to dict), route Optional
  .annotations[0] access through a small _first_annotation helper (mirrors the
  file's assert-not-None convention), and annotate a mapped ResponseStream.
- foundry_hosting: annotate error: dict[str, Any] = body.get(...) or {}
  (zuban needs the annotation).
- foundry: narrow ignores for the live AIProjectClient credential arg (pyrefly)
  and connections.get_default (zuban) SDK type gaps.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* updated pyright version

* pyright fix

* Python: Fix source typing for pyright 1.1.410

Pyright 1.1.410 tightened several checks. Apply the same source fixes as
upstream PR #6275:

- anthropic: import AsyncAnthropicBedrock from anthropic.lib.bedrock and
  AsyncAnthropicVertex from anthropic.lib.vertex (no longer re-exported from
  the anthropic top-level package -> reportPrivateImportUsage).
- core _types.py: cast the transform-hook result to UpdateT (reportAssignmentType).
- core _workflows/_events.py: annotate the @contextmanager helper as
  Generator[None] instead of Iterator[None] (reportDeprecated).
- redis: build the combined filter expression with an explicit loop instead of
  reduce(and_, ...), which pyright could no longer fully type (drops the now
  unused functools.reduce / operator.and_ imports).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Python: Accept plain-text body in Azure Functions workflow/run endpoint

The workflow_orchestrator already accepts plain strings as well as JSON
objects via context.get_input(), but the start_workflow_orchestration HTTP
handler only accepted JSON and returned 400 for any non-JSON body. This made
the functions integration tests that POST text/plain to /api/workflow/run
(e.g. test_09_workflow_shared_state) fail consistently with 400 != 202.

Fall back to the raw request body (decoded as UTF-8) when the body is not
JSON, rejecting only a truly empty body. The JSON path is unchanged.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-06-18 15:06:20 +00:00

463 lines
18 KiB
Python

# Copyright (c) Microsoft. All rights reserved.
"""Tests for checkpoint-as-conversation-items implementation."""
from dataclasses import dataclass
import pytest
from agent_framework import (
Executor,
InMemoryCheckpointStorage,
WorkflowBuilder,
WorkflowContext,
handler,
response_handler,
)
from agent_framework_devui._conversations import (
CheckpointConversationManager,
InMemoryConversationStore,
)
@dataclass
class WorkflowTestData:
"""Simple test data."""
value: str
@dataclass
class WorkflowHILRequest:
"""HIL request for testing."""
question: str
class WorkflowTestExecutor(Executor):
"""Test executor with HIL."""
def __init__(self, id: str) -> None:
super().__init__(id=id)
self._data_value: str | None = None
@handler
async def process(self, data: WorkflowTestData, ctx: WorkflowContext) -> None:
"""Process data and request approval."""
self._data_value = data.value
# Request HIL (checkpoint created here)
await ctx.request_info(request_data=WorkflowHILRequest(question=f"Approve {data.value}?"), response_type=str)
@response_handler
async def handle_response(
self, original_request: WorkflowHILRequest, response: str, ctx: WorkflowContext[str]
) -> None:
"""Handle HIL response."""
value = self._data_value or ""
await ctx.send_message(f"{value}_approved" if response.lower() == "yes" else f"{value}_rejected")
@pytest.fixture
def conversation_store():
"""Create in-memory conversation store."""
return InMemoryConversationStore()
@pytest.fixture
def checkpoint_manager(conversation_store):
"""Create checkpoint manager."""
return CheckpointConversationManager(conversation_store)
@pytest.fixture
def test_workflow():
"""Create test workflow with checkpointing."""
executor = WorkflowTestExecutor(id="test_executor")
checkpoint_storage = InMemoryCheckpointStorage()
return WorkflowBuilder(
name="Test Workflow",
description="Test checkpoint behavior",
start_executor=executor,
checkpoint_storage=checkpoint_storage,
).build()
class TestCheckpointConversationManager:
"""Test CheckpointConversationManager functionality - CONVERSATION-SCOPED."""
@pytest.mark.asyncio
async def test_conversation_scoped_checkpoint_save(self, checkpoint_manager, test_workflow):
"""Test checkpoint save in a specific conversation."""
entity_id = "test_entity"
conversation_id = f"conv_{entity_id}_test123"
# Create conversation first
checkpoint_manager.conversation_store.create_conversation(
metadata={"entity_id": entity_id, "type": "workflow_session"}, conversation_id=conversation_id
)
# Create test checkpoint
import uuid
from agent_framework._workflows._checkpoint import WorkflowCheckpoint
checkpoint = WorkflowCheckpoint(
checkpoint_id=str(uuid.uuid4()),
workflow_name=test_workflow.name,
graph_signature_hash=test_workflow.graph_signature_hash,
messages={},
state={"test": "data"},
)
# Get checkpoint storage for this conversation and save
storage = checkpoint_manager.get_checkpoint_storage(conversation_id)
checkpoint_id = await storage.save(checkpoint)
assert checkpoint_id == checkpoint.checkpoint_id
# Verify checkpoint stored in THIS conversation only
checkpoints = await storage.list_checkpoints(workflow_name=test_workflow.name)
assert len(checkpoints) == 1
assert checkpoints[0].checkpoint_id == checkpoint.checkpoint_id
@pytest.mark.asyncio
async def test_conversation_isolation(self, checkpoint_manager, test_workflow):
"""Test that conversations are isolated - checkpoints don't leak between conversations."""
entity_id = "test_entity"
conv_a = f"conv_{entity_id}_aaa"
conv_b = f"conv_{entity_id}_bbb"
# Create two conversations
checkpoint_manager.conversation_store.create_conversation(
metadata={"entity_id": entity_id, "type": "workflow_session"}, conversation_id=conv_a
)
checkpoint_manager.conversation_store.create_conversation(
metadata={"entity_id": entity_id, "type": "workflow_session"}, conversation_id=conv_b
)
# Save checkpoint to conversation A
import uuid
from agent_framework._workflows._checkpoint import WorkflowCheckpoint
checkpoint_a = WorkflowCheckpoint(
checkpoint_id=str(uuid.uuid4()),
workflow_name=test_workflow.name,
graph_signature_hash=test_workflow.graph_signature_hash,
messages={},
state={"conversation": "A"},
)
storage_a = checkpoint_manager.get_checkpoint_storage(conv_a)
await storage_a.save(checkpoint_a)
# Verify conversation A has checkpoint
checkpoints_a = await storage_a.list_checkpoints(workflow_name=test_workflow.name)
assert len(checkpoints_a) == 1
# Verify conversation B has NO checkpoints (isolation)
storage_b = checkpoint_manager.get_checkpoint_storage(conv_b)
checkpoints_b = await storage_b.list_checkpoints(workflow_name=test_workflow.name)
assert len(checkpoints_b) == 0
@pytest.mark.asyncio
async def test_list_checkpoints_in_session(self, checkpoint_manager, test_workflow):
"""Test listing checkpoints within a session."""
entity_id = "test_entity"
conversation_id = f"session_{entity_id}_test456"
# Create session
checkpoint_manager.conversation_store.create_conversation(
metadata={"entity_id": entity_id, "type": "workflow_session"}, conversation_id=conversation_id
)
# Save multiple checkpoints
import uuid
from agent_framework._workflows._checkpoint import WorkflowCheckpoint
storage = checkpoint_manager.get_checkpoint_storage(conversation_id)
checkpoint_ids = []
for i in range(3):
checkpoint = WorkflowCheckpoint(
checkpoint_id=str(uuid.uuid4()),
workflow_name=test_workflow.name,
graph_signature_hash=test_workflow.graph_signature_hash,
messages={},
state={"iteration": i},
)
saved_id = await storage.save(checkpoint)
checkpoint_ids.append(saved_id)
# List checkpoints using the storage
checkpoints_list = await storage.list_checkpoints(workflow_name=test_workflow.name)
assert len(checkpoints_list) == 3
# Verify all checkpoint IDs are present
loaded_ids = [cp.checkpoint_id for cp in checkpoints_list]
for saved_id in checkpoint_ids:
assert saved_id in loaded_ids
@pytest.mark.asyncio
async def test_checkpoints_appear_as_conversation_items(self, checkpoint_manager, test_workflow):
"""Test that checkpoints appear as conversation items through the standard API."""
entity_id = "test_entity"
conversation_id = f"session_{entity_id}_items_test"
# Create session
checkpoint_manager.conversation_store.create_conversation(
metadata={"entity_id": entity_id, "type": "workflow_session"}, conversation_id=conversation_id
)
# Save multiple checkpoints
from agent_framework._workflows._checkpoint import WorkflowCheckpoint
storage = checkpoint_manager.get_checkpoint_storage(conversation_id)
checkpoint_ids = []
for i in range(2):
checkpoint = WorkflowCheckpoint(
checkpoint_id=f"checkpoint_{i}",
workflow_name=test_workflow.name,
graph_signature_hash=test_workflow.graph_signature_hash,
messages={},
state={"iteration": i},
)
saved_id = await storage.save(checkpoint)
checkpoint_ids.append(saved_id)
# List conversation items - should include checkpoints
items, has_more = await checkpoint_manager.conversation_store.list_items(conversation_id)
# Filter for checkpoint items
checkpoint_items = [item for item in items if (isinstance(item, dict) and item.get("type") == "checkpoint")]
# Verify we have the correct number of checkpoint items
assert len(checkpoint_items) == 2, f"Expected 2 checkpoint items, got {len(checkpoint_items)}"
# Verify checkpoint items have correct structure
for item in checkpoint_items:
assert item.get("type") == "checkpoint"
assert item.get("checkpoint_id") in checkpoint_ids
assert item.get("workflow_name") == test_workflow.name
assert "timestamp" in item
item_id = item.get("id")
assert isinstance(item_id, str)
assert item_id.startswith("checkpoint_") # ID format: checkpoint_{checkpoint_id}
@pytest.mark.asyncio
async def test_load_checkpoint_from_session(self, checkpoint_manager, test_workflow):
"""Test loading checkpoint from a specific session."""
entity_id = "test_entity"
conversation_id = f"session_{entity_id}_test789"
# Create session
checkpoint_manager.conversation_store.create_conversation(
metadata={"entity_id": entity_id, "type": "workflow_session"}, conversation_id=conversation_id
)
# Create and save a checkpoint
import uuid
from agent_framework._workflows._checkpoint import WorkflowCheckpoint
original_checkpoint = WorkflowCheckpoint(
checkpoint_id=str(uuid.uuid4()),
workflow_name=test_workflow.name,
graph_signature_hash=test_workflow.graph_signature_hash,
messages={},
state={"test_key": "test_value"},
)
# Save to this session
storage = checkpoint_manager.get_checkpoint_storage(conversation_id)
await storage.save(original_checkpoint)
# Load checkpoint from this session
loaded_checkpoint = await storage.load(original_checkpoint.checkpoint_id)
assert loaded_checkpoint is not None
assert loaded_checkpoint.checkpoint_id == original_checkpoint.checkpoint_id
assert loaded_checkpoint.workflow_name == original_checkpoint.workflow_name
assert loaded_checkpoint.state == {"test_key": "test_value"}
class TestCheckpointStorage:
"""Test InMemoryCheckpointStorage per conversation - SESSION-SCOPED."""
@pytest.mark.asyncio
async def test_checkpoint_storage_protocol(self, checkpoint_manager, test_workflow):
"""Test that adapter implements CheckpointStorage protocol."""
entity_id = "test_entity"
conversation_id = f"session_{entity_id}_adapter_test"
# Create session
checkpoint_manager.conversation_store.create_conversation(
metadata={"entity_id": entity_id, "type": "workflow_session"}, conversation_id=conversation_id
)
# Get storage adapter for this session
storage = checkpoint_manager.get_checkpoint_storage(conversation_id)
# Create test checkpoint
import uuid
from agent_framework._workflows._checkpoint import WorkflowCheckpoint
checkpoint = WorkflowCheckpoint(
checkpoint_id=str(uuid.uuid4()),
workflow_name=test_workflow.name,
graph_signature_hash=test_workflow.graph_signature_hash,
messages={},
state={"test": "data"},
)
# Test save
checkpoint_id = await storage.save(checkpoint)
assert checkpoint_id == checkpoint.checkpoint_id
# Test load
loaded = await storage.load(checkpoint_id)
assert loaded is not None
assert loaded.checkpoint_id == checkpoint_id
# Test list_checkpoint_ids
ids = await storage.list_checkpoint_ids(workflow_name=test_workflow.name)
assert checkpoint_id in ids
# Test list_checkpoints
checkpoints_list = await storage.list_checkpoints(workflow_name=test_workflow.name)
assert len(checkpoints_list) >= 1
assert any(cp.checkpoint_id == checkpoint_id for cp in checkpoints_list)
class TestIntegration:
"""Integration tests for checkpoint workflow execution."""
@pytest.mark.asyncio
async def test_manual_checkpoint_save_via_injected_storage(self, checkpoint_manager, test_workflow):
"""Test manual checkpoint save via build-time storage injection."""
entity_id = "test_entity"
conversation_id = f"session_{entity_id}_integration_test1"
# Create session conversation
checkpoint_manager.conversation_store.create_conversation(
metadata={"entity_id": entity_id, "type": "workflow_session"}, conversation_id=conversation_id
)
# Get checkpoint storage for this session
checkpoint_storage = checkpoint_manager.get_checkpoint_storage(conversation_id)
# Set build-time storage (equivalent to checkpoint_storage= at build time)
# Note: In production, DevUI uses runtime injection via run(stream=True) parameter
if hasattr(test_workflow, "_runner") and hasattr(test_workflow._runner, "context"):
test_workflow._runner.context._checkpoint_storage = checkpoint_storage
# Create and save a checkpoint via injected storage
import uuid
from agent_framework._workflows._checkpoint import WorkflowCheckpoint
checkpoint = WorkflowCheckpoint(
checkpoint_id=str(uuid.uuid4()),
workflow_name=test_workflow.name,
graph_signature_hash=test_workflow.graph_signature_hash,
messages={},
state={"injected": True},
)
await checkpoint_storage.save(checkpoint)
# Verify checkpoint is accessible via storage (in this session)
storage_checkpoints = await checkpoint_storage.list_checkpoints(workflow_name=test_workflow.name)
assert len(storage_checkpoints) > 0
assert storage_checkpoints[0].checkpoint_id == checkpoint.checkpoint_id
@pytest.mark.asyncio
async def test_checkpoint_roundtrip_via_storage(self, checkpoint_manager, test_workflow):
"""Test checkpoint save/load roundtrip via storage adapter."""
entity_id = "test_entity"
conversation_id = f"session_{entity_id}_integration_test2"
# Create session conversation
checkpoint_manager.conversation_store.create_conversation(
metadata={"entity_id": entity_id, "type": "workflow_session"}, conversation_id=conversation_id
)
# Set build-time storage for testing
checkpoint_storage = checkpoint_manager.get_checkpoint_storage(conversation_id)
test_workflow._runner.context._checkpoint_storage = checkpoint_storage
# Create checkpoint
import uuid
from agent_framework._workflows._checkpoint import WorkflowCheckpoint
checkpoint = WorkflowCheckpoint(
checkpoint_id=str(uuid.uuid4()),
workflow_name=test_workflow.name,
graph_signature_hash=test_workflow.graph_signature_hash,
messages={},
state={"ready_to_resume": True},
)
checkpoint_id = await checkpoint_storage.save(checkpoint)
# Verify checkpoint can be loaded for resume
loaded = await checkpoint_storage.load(checkpoint_id)
assert loaded is not None
assert loaded.checkpoint_id == checkpoint_id
assert loaded.state == {"ready_to_resume": True}
# Verify checkpoint is accessible via storage (for UI to list checkpoints)
checkpoints = await checkpoint_storage.list_checkpoints(workflow_name=test_workflow.name)
assert len(checkpoints) > 0
assert checkpoints[0].checkpoint_id == checkpoint_id
@pytest.mark.asyncio
async def test_workflow_auto_saves_checkpoints_to_injected_storage(self, checkpoint_manager, test_workflow):
"""Test that workflows automatically save checkpoints to our conversation-backed storage.
This is the critical end-to-end test that verifies the entire checkpoint flow:
1. Storage is set as build-time storage (simulates checkpoint_storage=...)
2. Workflow runs and pauses at HIL point (IDLE_WITH_PENDING_REQUESTS status)
3. Framework automatically saves checkpoint to our storage
4. Checkpoint is accessible via manager for UI to list/resume
Note: In production, DevUI passes checkpoint_storage to run(stream=True) as runtime parameter.
This test uses build-time injection to verify framework's checkpoint auto-save behavior.
"""
entity_id = "test_entity"
conversation_id = f"session_{entity_id}_integration_test3"
# Create session conversation
checkpoint_manager.conversation_store.create_conversation(
metadata={"entity_id": entity_id, "type": "workflow_session"}, conversation_id=conversation_id
)
# Set build-time storage to test automatic checkpoint saves
checkpoint_storage = checkpoint_manager.get_checkpoint_storage(conversation_id)
test_workflow._runner.context._checkpoint_storage = checkpoint_storage
# Verify no checkpoints initially
checkpoints_before = await checkpoint_storage.list_checkpoints(workflow_name=test_workflow.name)
assert len(checkpoints_before) == 0
# Run workflow until it reaches IDLE_WITH_PENDING_REQUESTS (after checkpoint is created)
saw_request_event = False
async for event in test_workflow.run(WorkflowTestData(value="test"), stream=True):
if event.type == "request_info":
saw_request_event = True
# Wait for IDLE_WITH_PENDING_REQUESTS status (comes after checkpoint creation)
if event.type == "status" and "IDLE_WITH_PENDING_REQUESTS" in str(event.state):
break
assert saw_request_event, "Test workflow should have emitted request_info event (type='request_info')"
# Verify checkpoint was AUTOMATICALLY saved to our storage by the framework
checkpoints_after = await checkpoint_storage.list_checkpoints(workflow_name=test_workflow.name)
assert len(checkpoints_after) > 0, "Workflow should have auto-saved checkpoint at HIL pause"
# Verify checkpoint has correct workflow identity
checkpoint = checkpoints_after[0]
assert checkpoint.workflow_name == test_workflow.name