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
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,33 @@ if outcome.status != "COMPLETED":

`head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head.

## Waiting for deploy verification

After a deploy job, `wait_for_deploy_verification` holds the job until Proofline's checks of that commit's deploys settle. Name the full 40-character lowercase commit SHA the job deployed and, with `through`, the last check to wait for: `LANDING` (the default), `MINUTES_20`, `HOUR_1` or `DAY_1`. The token needs `reviews:read`.

```python
import os
from uuid import UUID
from proofline import ProoflineClient

with ProoflineClient() as client:
outcome = client.wait_for_deploy_verification(
UUID(os.environ["PROOFLINE_ORGANIZATION_ID"]),
UUID(os.environ["PROOFLINE_REPOSITORY_ID"]),
os.environ["DEPLOYED_SHA"],
through="MINUTES_20",
timeout=1800,
)
for deploy in outcome.deploys:
print(deploy.environment_id, deploy.status, deploy.reason_codes, deploy.deploy_url)
if outcome.status != "HEALTHY":
raise SystemExit(f"Deploy verification: {outcome.status}")
```

A deploy settles once every check through `through` recorded a result, or once its verification ended. The outcome is `HEALTHY` only when each recorded deploy's checks recorded `HEALTHY` with no gap. A check that a later deploy replaced counts only after a healthy landing check, as `VERIFIED_UNTIL_SUPERSEDED` reads it. A regression ends the wait at once with `REGRESSED`, whichever check recorded it, even past `through` and while other deploys are still due. Once every deploy settles, a failed GitHub deployment gives `FAILED`, and a gap, an `INCOMPLETE` check, a check never recorded, an unverified or rolled-back deploy, or a result this SDK does not know gives `INCOMPLETE`. Each `DeployVerdict` names its environment, its `status`, the deploy's `state` and the `reason_codes` that leave it unproven. `environment_id` holds the wait to the deploys of one environment. Between reads the wait sleeps until the next check it needs is due, reading at least every five minutes so a failed or newly recorded deploy still ends it early; an overdue check falls back to the usual backoff.

A commit with no recorded deploy keeps the wait open, because the deploy may still be recorded, and ends as `TIMED_OUT`, never `HEALTHY`. Any other wait still open at `timeout` also returns `TIMED_OUT` with each deploy's verdict so far; a deploy still due reads `PENDING`. Any other `commit_sha`, `through` or `timeout` raises `ValueError` before a request.

## Review exports

`export_reviews` reads one CSV or NDJSON page over the bounded transport. Export tokens require `analytics:read`.
Expand Down
3 changes: 3 additions & 0 deletions proofline/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from ._transport import VERSION as __version__
from ._transport import ProoflineError, RunNowRefusal
from .client import AsyncProoflineClient, ProoflineClient, ReviewFilters
from .deploys import DeployVerdict, DeployVerificationOutcome
from .exports import ExportDataset, ExportFormat, ExportPage
from .knowledge import KnowledgeResult
from .outcomes import AssessmentGap, CheckGap, ReviewOutcome
Expand All @@ -51,6 +52,8 @@
"CustomerAssessmentDetail",
"CustomerFinding",
"CustomerReviewDetail",
"DeployVerdict",
"DeployVerificationOutcome",
"ExportDataset",
"ExportFormat",
"ExportPage",
Expand Down
131 changes: 131 additions & 0 deletions proofline/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import math
from asyncio import sleep as async_sleep
from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
from datetime import UTC, datetime
from string import hexdigits
from time import monotonic, sleep
from types import TracebackType
Expand Down Expand Up @@ -44,6 +45,7 @@
from ._generated.models.agent_session import AgentSession
from ._generated.models.agent_session_prompt_type_0 import AgentSessionPromptType0
from ._generated.models.agent_session_prompt_type_1 import AgentSessionPromptType1
from ._generated.models.commit_deploy_verifications import CommitDeployVerifications
from ._generated.models.commit_review_request import CommitReviewRequest
from ._generated.models.commit_review_response import CommitReviewResponse
from ._generated.models.coverage_upload_request import CoverageUploadRequest
Expand Down Expand Up @@ -72,6 +74,14 @@
from ._generated.types import UNSET, Response, Unset
from ._mcp import AsyncMcpClient, McpClient
from ._transport import ProoflineError
from .deploys import (
DeployCheckpointName,
DeployVerificationOutcome,
checkpoint_index,
deploy_commit,
next_due,
)
from .deploys import outcome as deploy_outcome
from .exports import ExportDataset, ExportFormat, ExportPage, decode_export
from .fixes import AsyncFixesClient, FixesClient
from .knowledge import AsyncKnowledgeClient, KnowledgeClient
Expand Down Expand Up @@ -139,6 +149,33 @@ def _configuration(
)


# A check due later than this is still read at least this often, so a deploy that
# fails or is recorded between checks ends the wait without waiting for the check.
_DEPLOY_READ_CEILING = 300.0


def utc_now() -> datetime:
return datetime.now(UTC)


def _deploy_delay(
verifications: CommitDeployVerifications | None,
through: int,
environment_id: UUID | None,
interval: float,
) -> float:
# Checks are recorded on a schedule the ledger already names, so sleeping until
# the next one is due replaces reads that could only return the same snapshot.
due = (
None
if verifications is None
else next_due(verifications, through, environment_id=environment_id)
)
if due is None:
return interval
return max(interval, min((due - utc_now()).total_seconds(), _DEPLOY_READ_CEILING))


def _review_url(base_url: str, organization_id: UUID, review_id: UUID) -> str:
return (
f"{base_url}/orgs/by-id/{quote(str(organization_id), safe='')}"
Expand Down Expand Up @@ -583,6 +620,58 @@ def wait_for_review(
finally:
_transport.DEADLINE.reset(deadline)

def wait_for_deploy_verification(
self,
organization_id: UUID,
repository_id: UUID,
commit_sha: str,
*,
through: DeployCheckpointName = "LANDING",
environment_id: UUID | None = None,
timeout: float = 1800,
) -> DeployVerificationOutcome:
"""Wait until every recorded deploy of a commit settles, or return TIMED_OUT.

A deploy settles once each check through ``through`` recorded a result,
or its verification ended. A recorded regression ends the wait at once,
whichever check recorded it. A commit with no recorded deploy keeps the
wait open, since a deploy may still be recorded; it is never HEALTHY.

environment_id holds the wait to the deploys of one environment.
"""

if not math.isfinite(timeout) or timeout < 0:
raise ValueError("The deploy timeout must be a finite nonnegative number of seconds.")
deploy_commit(commit_sha)
index = checkpoint_index(through)
last: CommitDeployVerifications | None = None
deadline = _transport.DEADLINE.set(monotonic() + timeout)
interval = 5.0
try:
while (_transport.remaining() or 0) > 0:
try:
last = self.get_commit_deploy_verifications(
organization_id, repository_id, commit_sha
)
except ProoflineError as error:
if error.status == 0 and (_transport.remaining() or 0) <= 0:
break
raise
if (_transport.remaining() or 0) <= 0:
break
result = deploy_outcome(last, commit_sha, index, environment_id=environment_id)
if result is not None:
return result
delay = _deploy_delay(last, index, environment_id, interval)
sleep(min(delay, _transport.remaining() or 0))
interval = min(60, interval * 2)
timed_out = deploy_outcome(
last, commit_sha, index, environment_id=environment_id, forced="TIMED_OUT"
)
return timed_out or DeployVerificationOutcome("TIMED_OUT", commit_sha)
finally:
_transport.DEADLINE.reset(deadline)


class AsyncProoflineClient(AsyncOperations):
def __init__(
Expand Down Expand Up @@ -968,3 +1057,45 @@ async def wait_for_review(
return timed_out or ReviewOutcome("TIMED_OUT", url)
finally:
_transport.DEADLINE.reset(deadline)

async def wait_for_deploy_verification(
self,
organization_id: UUID,
repository_id: UUID,
commit_sha: str,
*,
through: DeployCheckpointName = "LANDING",
environment_id: UUID | None = None,
timeout: float = 1800,
) -> DeployVerificationOutcome:
if not math.isfinite(timeout) or timeout < 0:
raise ValueError("The deploy timeout must be a finite nonnegative number of seconds.")
deploy_commit(commit_sha)
index = checkpoint_index(through)
last: CommitDeployVerifications | None = None
deadline = _transport.DEADLINE.set(monotonic() + timeout)
interval = 5.0
try:
while (_transport.remaining() or 0) > 0:
try:
last = await self.get_commit_deploy_verifications(
organization_id, repository_id, commit_sha
)
except ProoflineError as error:
if error.status == 0 and (_transport.remaining() or 0) <= 0:
break
raise
if (_transport.remaining() or 0) <= 0:
break
result = deploy_outcome(last, commit_sha, index, environment_id=environment_id)
if result is not None:
return result
delay = _deploy_delay(last, index, environment_id, interval)
await async_sleep(min(delay, _transport.remaining() or 0))
interval = min(60, interval * 2)
timed_out = deploy_outcome(
last, commit_sha, index, environment_id=environment_id, forced="TIMED_OUT"
)
return timed_out or DeployVerificationOutcome("TIMED_OUT", commit_sha)
finally:
_transport.DEADLINE.reset(deadline)
Loading