diff --git a/proofline/__init__.py b/proofline/__init__.py index 48902066..b7e2942f 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -36,10 +36,11 @@ from .client import AsyncProoflineClient, ProoflineClient, ReviewFilters from .exports import ExportDataset, ExportFormat, ExportPage from .knowledge import KnowledgeResult -from .outcomes import AssessmentGap, CheckGap, ReviewOutcome +from .outcomes import AgentSessionOutcome, AssessmentGap, CheckGap, ReviewOutcome __all__ = [ "AgentSession", + "AgentSessionOutcome", "AgentVendor", "AssessmentGap", "AsyncProoflineClient", diff --git a/proofline/client.py b/proofline/client.py index 72f2514e..95633cfe 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -75,7 +75,7 @@ from .exports import ExportDataset, ExportFormat, ExportPage, decode_export from .fixes import AsyncFixesClient, FixesClient from .knowledge import AsyncKnowledgeClient, KnowledgeClient -from .outcomes import ReviewOutcome, outcome +from .outcomes import AgentSessionOutcome, ReviewOutcome, agent_session_outcome, outcome T = TypeVar("T") AgentSessionPrompt = AgentSessionPromptType0 | AgentSessionPromptType1 @@ -154,6 +154,13 @@ def _page_limits(page_size: int, max_pages: int, max_items: int) -> None: ) +def _wait_budget_args(timeout: float, poll_interval: float) -> None: + if not math.isfinite(timeout) or timeout < 0: + raise ValueError("The wait timeout must be a finite nonnegative number of seconds.") + if not math.isfinite(poll_interval) or poll_interval <= 0: + raise ValueError("The poll interval must be a finite positive number of seconds.") + + def _head_commit(value: str | None) -> None: # Only a full SHA names one exact commit; a branch or an abbreviation does not. if value is not None and ( @@ -586,6 +593,40 @@ def wait_for_review( ) return timed_out or ReviewOutcome("TIMED_OUT", url) + def wait_for_agent_session( + self, + organization_id: UUID, + session_id: UUID, + *, + timeout: float = 300, + poll_interval: float = 5.0, + ) -> AgentSessionOutcome: + """Wait for an agent session to reach a terminal state or return TIMED_OUT.""" + + _wait_budget_args(timeout, poll_interval) + last: AgentSession | None = None + interval = float(poll_interval) + with _transport.review_wait_budget(timeout): + while timeout == 0 or (_transport.remaining() or 0) > 0: + try: + last = self.get_agent_session(organization_id, session_id) + except _transport.RetryDeadlineExceeded: + break + except ProoflineError as error: + if timeout > 0 and error.status == 0 and (_transport.remaining() or 0) <= 0: + break + raise + result = agent_session_outcome(last, session_id=session_id) + if result is not None: + return result + budget = _transport.remaining() + if timeout == 0 or not budget: + break + sleep(min(interval, budget)) + interval = min(60.0, interval * 2) + timed_out = agent_session_outcome(last, "TIMED_OUT", session_id=session_id) + return timed_out or AgentSessionOutcome("TIMED_OUT") + class AsyncProoflineClient(AsyncOperations): def __init__( @@ -973,3 +1014,37 @@ async def wait_for_review( last, url, "TIMED_OUT", review_id=review_id, head_commit_sha=head_commit_sha ) return timed_out or ReviewOutcome("TIMED_OUT", url) + + async def wait_for_agent_session( + self, + organization_id: UUID, + session_id: UUID, + *, + timeout: float = 300, + poll_interval: float = 5.0, + ) -> AgentSessionOutcome: + """Wait for an agent session to reach a terminal state or return TIMED_OUT.""" + + _wait_budget_args(timeout, poll_interval) + last: AgentSession | None = None + interval = float(poll_interval) + with _transport.review_wait_budget(timeout): + while timeout == 0 or (_transport.remaining() or 0) > 0: + try: + last = await self.get_agent_session(organization_id, session_id) + except _transport.RetryDeadlineExceeded: + break + except ProoflineError as error: + if timeout > 0 and error.status == 0 and (_transport.remaining() or 0) <= 0: + break + raise + result = agent_session_outcome(last, session_id=session_id) + if result is not None: + return result + budget = _transport.remaining() + if timeout == 0 or not budget: + break + await async_sleep(min(interval, budget)) + interval = min(60.0, interval * 2) + timed_out = agent_session_outcome(last, "TIMED_OUT", session_id=session_id) + return timed_out or AgentSessionOutcome("TIMED_OUT") diff --git a/proofline/outcomes.py b/proofline/outcomes.py index fa363b32..cb34563a 100644 --- a/proofline/outcomes.py +++ b/proofline/outcomes.py @@ -3,15 +3,27 @@ from __future__ import annotations from dataclasses import dataclass, field -from typing import Literal +from typing import Literal, cast from uuid import UUID +from ._generated.models.agent_session import AgentSession from ._generated.models.customer_code_assessment import CustomerCodeAssessment from ._generated.models.customer_review_detail import CustomerReviewDetail from ._generated.types import Unset from ._transport import ProoflineError OutcomeStatus = Literal["COMPLETED", "INCOMPLETE", "FAILED", "STOPPED", "TIMED_OUT"] +AgentSessionStatus = Literal[ + "FINISHED", + "FAILED", + "REFUSED", + "HEAD_MOVED", + "UNKNOWN", + "TIMED_OUT", +] +_TERMINAL_AGENT_SESSION_STATUSES = frozenset( + ("FINISHED", "FAILED", "REFUSED", "HEAD_MOVED", "UNKNOWN") +) COMPLETE_CHECKS = frozenset(("READY", "BLOCKED", "NOT_APPLICABLE")) COMPLETE_LIFECYCLES = frozenset(("GATING", "SHADOW", "QUARANTINED", "RETIRED")) _KNOWN_ASSESSMENTS = frozenset( @@ -52,6 +64,16 @@ class ReviewOutcome: reason: str | None = None +@dataclass(frozen=True) +class AgentSessionOutcome: + status: AgentSessionStatus + session: AgentSession | None = field(default=None, repr=False) + cause: str | None = None + pull_request_url: str | None = None + vendor_url: str | None = None + observed_head_sha: str | None = None + + def text(value: object) -> str | None: return value if isinstance(value, str) and value else None @@ -243,3 +265,46 @@ def outcome( return ReviewOutcome(status, review_url, review, tuple(gaps)) gaps.append(AssessmentGap(None, "UNKNOWN", (head_gap,))) return ReviewOutcome(status, review_url, review, tuple(gaps), _HEAD_REASONS[head_gap]) + + +def _validate_agent_session(session: AgentSession, session_id: UUID | None) -> None: + if ( + not isinstance(session.id, UUID) + or (session_id is not None and session.id != session_id) + or type(session.done) is not bool + or not isinstance(session.status, str) + ): + raise ProoflineError( + 0, + "urn:proofline:sdk:invalid-response", + "The agent session has invalid identity or status metadata.", + ) + + +def agent_session_outcome( + session: AgentSession | None, + forced: AgentSessionStatus | None = None, + *, + session_id: UUID | None = None, +) -> AgentSessionOutcome | None: + if session is None: + return AgentSessionOutcome(forced or "TIMED_OUT") + _validate_agent_session(session, session_id) + cause = text(session.cause) + pull_request_url = text(session.pull_request_url) + vendor_url = text(session.vendor_url) + observed_head_sha = text(session.observed_head_sha) + if forced is not None: + return AgentSessionOutcome( + forced, session, cause, pull_request_url, vendor_url, observed_head_sha + ) + if not session.done: + return None + status: AgentSessionStatus = ( + cast(AgentSessionStatus, session.status) + if session.status in _TERMINAL_AGENT_SESSION_STATUSES + else "UNKNOWN" + ) + return AgentSessionOutcome( + status, session, cause, pull_request_url, vendor_url, observed_head_sha + ) diff --git a/scripts/contracts.py b/scripts/contracts.py index 6e6255a2..803bbde8 100644 --- a/scripts/contracts.py +++ b/scripts/contracts.py @@ -42,7 +42,14 @@ def main() -> None: raise SystemExit("ReviewFilters differs from the list_reviews query parameters.") for client in (ProoflineClient, AsyncProoflineClient): - helpers = {"close", "aclose", "iter_export_pages", "iter_reviews", "wait_for_review"} + helpers = { + "close", + "aclose", + "iter_export_pages", + "iter_reviews", + "wait_for_agent_session", + "wait_for_review", + } exposed = { name for name in dir(client) diff --git a/tests/test_agent_session_wait.py b/tests/test_agent_session_wait.py new file mode 100644 index 00000000..5b7b2caf --- /dev/null +++ b/tests/test_agent_session_wait.py @@ -0,0 +1,240 @@ +from __future__ import annotations + +from typing import Any +from uuid import UUID + +import pytest + +from proofline import AgentSessionOutcome, ProoflineError +from tests.http_server import Reply, Request, Server +from tests.test_http import ( + FINDING, + HEAD, + MODES, + ORG, + PRIVATE, + REVIEW, + Clock, + call, + session, +) + +SESSION_ID = UUID("00000000-0000-4000-8000-000000000099") +CONNECTION_ID = UUID("00000000-0000-4000-8000-000000000098") +USER_ID = UUID("00000000-0000-4000-8000-000000000097") +REPO_ID = UUID("00000000-0000-4000-8000-000000000096") + + +def agent_session_payload( + status: str, + *, + done: bool, + session_id: UUID = SESSION_ID, + cause: str | None = None, + observed_head_sha: str | None = None, + pull_request_url: str | None = None, + vendor_url: str | None = None, + untrusted_vendor_summary: str | None = None, +) -> dict[str, Any]: + payload: dict[str, Any] = { + "attempt": 1, + "connection_id": str(CONNECTION_ID), + "created_at": "2026-10-01T00:00:00Z", + "done": done, + "finding_id": str(FINDING), + "id": str(session_id), + "requested_by_user_id": str(USER_ID), + "review_id": str(REVIEW), + "status": status, + "target": { + "github_repository_id": 12345, + "head_sha": HEAD, + "pull_request_number": 42, + "repository_full_name": "owner/repo", + "repository_id": str(REPO_ID), + }, + "updated_at": "2026-10-01T00:00:10Z", + "vendor": "DEVIN", + } + if cause is not None: + payload["cause"] = cause + if observed_head_sha is not None: + payload["observed_head_sha"] = observed_head_sha + if pull_request_url is not None: + payload["pull_request_url"] = pull_request_url + if vendor_url is not None: + payload["vendor_url"] = vendor_url + if untrusted_vendor_summary is not None: + payload["untrusted_vendor_summary"] = untrusted_vendor_summary + return payload + + +@MODES +async def test_wait_for_agent_session_polls_until_finished( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + responses = [ + agent_session_payload("REQUESTED", done=False), + agent_session_payload("STARTING", done=False), + agent_session_payload("RUNNING", done=False), + agent_session_payload( + "FINISHED", + done=True, + pull_request_url="https://github.com/owner/repo/pull/99", + vendor_url="https://app.devin.ai/sessions/abc", + untrusted_vendor_summary=PRIVATE, + ), + ] + seen_paths: list[str] = [] + + def respond(request: Request, index: int) -> Reply: + seen_paths.append(request.path) + return Reply(body=responses[index]) + + with Server(respond) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_agent_session", ORG, SESSION_ID, timeout=100) + + assert isinstance(result, AgentSessionOutcome) + assert result.status == "FINISHED" + assert result.cause is None + assert result.pull_request_url == "https://github.com/owner/repo/pull/99" + assert result.vendor_url == "https://app.devin.ai/sessions/abc" + assert result.observed_head_sha is None + assert result.session is not None + assert result.session.id == SESSION_ID + assert result.session.untrusted_vendor_summary == PRIVATE + assert PRIVATE not in repr(result) + assert clock.delays == [5, 10, 20] + assert seen_paths == [f"/api/v1/organizations/{ORG}/agent-sessions/{SESSION_ID}"] * 4 + + +@MODES +@pytest.mark.parametrize( + ("raw_status", "expected_status", "cause", "observed_head_sha"), + [ + ("FAILED", "FAILED", "VENDOR_ERROR", None), + ("REFUSED", "REFUSED", "RATE_LIMITED", None), + ("HEAD_MOVED", "HEAD_MOVED", "PR_HEAD_CHANGED", "b" * 40), + ("UNKNOWN", "UNKNOWN", "LOST_SESSION", None), + ("FUTURE_STATUS", "UNKNOWN", None, None), + ], +) +async def test_wait_for_agent_session_terminal_statuses( + mode: str, + raw_status: str, + expected_status: str, + cause: str | None, + observed_head_sha: str | None, +) -> None: + body = agent_session_payload( + raw_status, + done=True, + cause=cause, + observed_head_sha=observed_head_sha, + ) + with Server(lambda request, index: Reply(body=body)) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_agent_session", ORG, SESSION_ID, timeout=10) + + assert result.status == expected_status + assert result.cause == cause + assert result.observed_head_sha == observed_head_sha + + +@MODES +async def test_wait_for_agent_session_timeout_zero_does_one_read(mode: str) -> None: + body = agent_session_payload("RUNNING", done=False, vendor_url="https://vendor.example/1") + with Server(lambda request, index: Reply(body=body)) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_agent_session", ORG, SESSION_ID, timeout=0) + assert len(server.requests) == 1 + + assert result.status == "TIMED_OUT" + assert result.vendor_url == "https://vendor.example/1" + assert result.session is not None + assert result.session.status == "RUNNING" + + +@MODES +async def test_wait_for_agent_session_custom_poll_interval_and_deadline_expiry( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + body = agent_session_payload("RUNNING", done=False) + with Server(lambda request, index: Reply(body=body)) as server: + async with session(mode, server.url) as client: + result = await call( + client, + "wait_for_agent_session", + ORG, + SESSION_ID, + timeout=7, + poll_interval=2, + ) + + assert result.status == "TIMED_OUT" + assert clock.delays == [2, 4, 1] + + +@MODES +async def test_wait_for_agent_session_retry_deadline_returns_timed_out( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + with Server(lambda request, index: Reply(status=503, headers={"Retry-After": "30"})) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_agent_session", ORG, SESSION_ID, timeout=10) + + assert result.status == "TIMED_OUT" + assert result.session is None + + +@MODES +async def test_wait_for_agent_session_rejects_mismatched_id_and_invalid_args(mode: str) -> None: + other_id = UUID("00000000-0000-4000-8000-000000000123") + body = agent_session_payload("FINISHED", done=True, session_id=other_id) + with Server(lambda request, index: Reply(body=body)) as server: + async with session(mode, server.url) as client: + for bad_timeout in (-1, float("nan"), float("inf")): + with pytest.raises(ValueError): + await call( + client, + "wait_for_agent_session", + ORG, + SESSION_ID, + timeout=bad_timeout, + ) + for bad_interval in (0, -1, float("nan"), float("inf")): + with pytest.raises(ValueError): + await call( + client, + "wait_for_agent_session", + ORG, + SESSION_ID, + poll_interval=bad_interval, + ) + with pytest.raises(ProoflineError) as exc_info: + await call(client, "wait_for_agent_session", ORG, SESSION_ID, timeout=10) + assert exc_info.value.type == "urn:proofline:sdk:invalid-response" + + +@MODES +async def test_wait_for_agent_session_propagates_non_retryable_http_errors(mode: str) -> None: + with Server( + lambda request, index: Reply( + status=404, + headers={"Content-Type": "application/problem+json"}, + body={ + "type": "https://proofline.sh/problems/not-found", + "title": "Not Found", + "status": 404, + "detail": "Agent session not found.", + }, + ) + ) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as exc_info: + await call(client, "wait_for_agent_session", ORG, SESSION_ID, timeout=10) + assert exc_info.value.status == 404