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
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
# Copyright (c) Microsoft. All rights reserved.

from __future__ import annotations

import hashlib
import json
from abc import ABC, abstractmethod
from datetime import datetime
from datetime import datetime, timezone
from typing import Any, Generic, Protocol, TypeVar

from agent_framework import (
Expand Down Expand Up @@ -34,6 +35,12 @@ def _encoded_checkpoint_hash(value: Any) -> str:
return hashlib.sha256(payload).hexdigest()


def _parse_checkpoint_timestamp(timestamp: str) -> datetime:
"""Treat naive checkpoint timestamps as UTC when comparing checkpoints."""
parsed = datetime.fromisoformat(timestamp)
return parsed.replace(tzinfo=timezone.utc) if parsed.tzinfo is None else parsed


def _select_latest_checkpoint(checkpoints: list[WorkflowCheckpoint]) -> WorkflowCheckpoint:
"""Return the latest checkpoint, resolving timestamp ties through the lineage chain.

Expand All @@ -44,8 +51,8 @@ def _select_latest_checkpoint(checkpoints: list[WorkflowCheckpoint]) -> Workflow
If several unsuperseded candidates remain, the one with the greatest ``checkpoint_id``
is returned, so the choice among them is stable too.
"""
newest_timestamp = max(datetime.fromisoformat(cp.timestamp) for cp in checkpoints)
candidates = [cp for cp in checkpoints if datetime.fromisoformat(cp.timestamp) == newest_timestamp]
newest_timestamp = max(_parse_checkpoint_timestamp(cp.timestamp) for cp in checkpoints)
candidates = [cp for cp in checkpoints if _parse_checkpoint_timestamp(cp.timestamp) == newest_timestamp]
superseded_ids = {cp.previous_checkpoint_id for cp in candidates}
leaves = [cp for cp in candidates if cp.checkpoint_id not in superseded_ids]
return max(leaves or candidates, key=lambda cp: cp.checkpoint_id)
Expand Down
50 changes: 50 additions & 0 deletions python/packages/foundry_hosting/tests/test_state_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,56 @@ async def test_get_latest_breaks_ties_between_unsuperseded_checkpoints_by_id(
assert latest.checkpoint_id == "leaf-b"


@pytest.mark.parametrize(
("parent_timestamp", "child_timestamp"),
[
("2026-01-01T00:00:00", "2026-01-02T00:00:00+00:00"),
("2026-01-01T00:00:00+00:00", "2026-01-02T00:00:00"),
("2026-01-01T00:00:00", "2026-01-01T00:00:00+00:00"),
],
)
@pytest.mark.parametrize("reverse_save_order", [False, True])
async def test_get_latest_accepts_mixed_naive_and_aware_timestamps_after_save(
parent_timestamp: str, child_timestamp: str, reverse_save_order: bool
) -> None:
"""Naive timestamps use UTC when selecting saved checkpoints, including lineage ties."""
store = _store()
saved: dict[str, Any] = {}

async def set_item(key: str, value: Any, *, call_id: str) -> None:
saved[key] = value

async def get_item(key: str, *, call_id: str) -> SimpleNamespace:
return SimpleNamespace(value=saved[key])

store.set_item.side_effect = set_item
store.get_item.side_effect = get_item
checkpoints = [
_checkpoint("parent", timestamp=parent_timestamp),
_checkpoint("child", timestamp=child_timestamp, previous_checkpoint_id="parent"),
]
if reverse_save_order:
checkpoints.reverse()
store.list_keys.return_value = SimpleNamespace(
keys=[SimpleNamespace(key=checkpoint.checkpoint_id) for checkpoint in checkpoints],
has_more=False,
last_id=None,
)
with patch(
"agent_framework_foundry_hosting._state_store.FoundryStateStore.get_or_create",
new=AsyncMock(return_value=store),
):
storage = FoundryCheckpointStore("context-1", _platform_context())
for checkpoint in checkpoints:
await storage.save(checkpoint)
latest = await storage.get_latest(workflow_name="workflow")

assert latest is not None
assert latest.checkpoint_id == "child"
assert saved["parent"]["timestamp"] == parent_timestamp
assert saved["child"]["timestamp"] == child_timestamp


async def test_get_latest_returns_none_when_no_checkpoints_exist(monkeypatch: pytest.MonkeyPatch) -> None:
storage = FoundryCheckpointStore("context-1", _platform_context())
monkeypatch.setattr(storage, "list_checkpoints", AsyncMock(return_value=[]))
Expand Down
Loading