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
3 changes: 2 additions & 1 deletion proofline/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
77 changes: 76 additions & 1 deletion proofline/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 (
Expand Down Expand Up @@ -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__(
Expand Down Expand Up @@ -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")
67 changes: 66 additions & 1 deletion proofline/outcomes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
)
9 changes: 8 additions & 1 deletion scripts/contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading