Skip to content
Closed
Show file tree
Hide file tree
Changes from 10 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
2 changes: 2 additions & 0 deletions scripts/ci/audit_codeql_default_setup_rollout.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,7 @@ def load_payload(path: Path | None, stdin: TextIO) -> list[dict[str, Any]]:


def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse CLI arguments for either the file-payload or live-collection mode."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("snapshots_json", nargs="?", type=Path)
parser.add_argument("--repository")
Expand All @@ -277,6 +278,7 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:


def main(argv: list[str] | None = None) -> int:
"""Audit CodeQL rollout state from file or live snapshots and print verdicts."""
args = parse_args(argv)
try:
live_mode = args.repository is not None or args.pr is not None
Expand Down
6 changes: 4 additions & 2 deletions scripts/ci/noema_review_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@

from scripts.ci.opencode_review_normalize_output import changed_file_is_material


PRIMARY_REVIEW_AUTHORS = {
"opencode-agent[bot]",
"opencode-agent",
Expand Down Expand Up @@ -1636,7 +1635,10 @@ def call_llm(
gateway_telemetry: dict[str, str | int] = {}
if isinstance(exc, urllib.error.HTTPError):
active_phase = "response_error"
gateway_telemetry = _extract_http_error_telemetry(exc)
try:
gateway_telemetry = _extract_http_error_telemetry(exc)
finally:
exc.close()
model_value = gateway_telemetry.get("served_model")
served_model = model_value if isinstance(model_value, str) else None
elapsed = time.monotonic() - attempt_started
Expand Down
2 changes: 2 additions & 0 deletions scripts/ci/pingora_edge_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,8 @@ def _github_open_json(url: str, token: str) -> object:
with github_opener.open(request, timeout=30) as response:
payload = response.read(MAX_RESPONSE_BYTES + 1)
except (HTTPError, URLError, TimeoutError) as exc:
if isinstance(exc, HTTPError):
exc.close()
raise PolicyError(f"GitHub API request failed for policy evidence: {type(exc).__name__}") from exc
if len(payload) > MAX_RESPONSE_BYTES:
raise PolicyError("GitHub API policy response exceeded the bounded response size")
Expand Down
3 changes: 3 additions & 0 deletions scripts/ci/pr_review_merge_scheduler_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ class SchedulerAdmissionGate:
"""Persist and bound review-worker leases for one scheduler execution."""

def __init__(self, state_path: Path, *, sequence: int, dispatch_budget: int) -> None:
"""Bind this gate to one durable state file, run sequence, and worker budget."""
if sequence < 1:
raise ValueError("admission sequence must be positive")
if dispatch_budget < 0:
Expand All @@ -68,6 +69,7 @@ def admit(self, component: str, repository: str, pr: dict[str, Any]) -> bool:
selected: list[DispatchLease] = []

def lease(state):
"""Apply this request to `state` and record any lease it wins."""
plan = plan_dispatches(
state,
[request],
Expand All @@ -88,6 +90,7 @@ def reconcile(self, repository: str, prs: Sequence[dict[str, Any]]) -> None:
live_prs = {int(pr["number"]): pr for pr in prs}

def reconcile_state(state):
"""Mark exact-head dispatched leases complete and superseded ones stale."""
records = dict(state.records)
latest = dict(state.latest_sequences)
for identity, record in tuple(records.items()):
Expand Down
5 changes: 3 additions & 2 deletions scripts/ci/reconcile_repository_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,9 @@
import sys
from pathlib import Path
from typing import Any
from urllib.error import URLError
from urllib.error import HTTPError, URLError
from urllib.request import HTTPRedirectHandler, Request, build_opener


ORGANIZATION = "ContextualWisdomLab"
REPOSITORY_RE = re.compile(r"^[A-Za-z0-9_.-]+$")
TOPIC_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,49}$")
Expand Down Expand Up @@ -247,6 +246,8 @@ def _pages_publication_ready(repository: str, current: dict[str, Any]) -> None:
if not response.read(1):
raise RuntimeError(f"GitHub Pages returned empty content for {repository}")
except (URLError, TimeoutError, OSError) as exc:
if isinstance(exc, HTTPError):
exc.close()
raise RuntimeError(f"GitHub Pages is not reachable for {repository}") from exc


Expand Down
20 changes: 20 additions & 0 deletions scripts/ci/review_admission_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,15 @@

@dataclass(frozen=True)
class WorkerBoundary:
"""The credential, permission set, and concurrency namespace one review worker runs under."""

credential: str
permissions: tuple[str, ...]
concurrency_namespace: str
cancel_in_progress: bool = True

def concurrency_group(self, request: AdmissionRequest) -> str:
"""Return this worker's `{namespace}-{repository}-{pull_request}` concurrency group."""
return (
f"{self.concurrency_namespace}-{request.repository}-{request.pull_request}"
)
Expand All @@ -52,6 +55,8 @@ def concurrency_group(self, request: AdmissionRequest) -> str:

@dataclass(frozen=True)
class AdmissionRequest:
"""One validated request to admit a review worker onto a specific PR head."""

repository: str
pull_request: int
head_sha: str
Expand All @@ -68,6 +73,7 @@ def create(
component: str,
sequence: int,
) -> AdmissionRequest:
"""Validate and normalize raw fields into an `AdmissionRequest`."""
if isinstance(pull_request, bool) or not isinstance(pull_request, int):
raise TypeError("pull request must be an integer")
if isinstance(sequence, bool) or not isinstance(sequence, int):
Expand All @@ -87,35 +93,45 @@ def create(

@property
def identity(self) -> str:
"""Return the unique key identifying this exact request (including its sequence)."""
return f"{self.repository}#{self.pull_request}@{self.head_sha}:{self.component}"

@property
def stream(self) -> str:
"""Return the key identifying this request's PR+component stream across sequences."""
return f"{self.repository}#{self.pull_request}:{self.component}"


@dataclass(frozen=True)
class RequestRecord:
"""An admission request paired with its current lifecycle status."""

request: AdmissionRequest
status: str


@dataclass(frozen=True)
class DispatchLease:
"""A request that has been granted a worker boundary to run under."""

request: AdmissionRequest
boundary: WorkerBoundary


@dataclass(frozen=True)
class ControllerState:
"""The durable admission controller's full state: known records and per-stream sequences."""

records: dict[str, RequestRecord]
latest_sequences: dict[str, int]

@classmethod
def empty(cls) -> ControllerState:
"""Return the initial state with no records and no sequences observed yet."""
return cls({}, {})

def to_json(self) -> str:
"""Serialize this state to its canonical, deterministically-ordered JSON form."""
payload = {
"latest_sequences": self.latest_sequences,
"records": {
Expand All @@ -130,6 +146,7 @@ def to_json(self) -> str:

@classmethod
def from_json(cls, value: str) -> ControllerState:
"""Parse and fully validate a state snapshot, rejecting any inconsistent JSON."""
payload = json.loads(value)
if not isinstance(payload, dict):
raise TypeError("durable admission state must be an object")
Expand Down Expand Up @@ -204,6 +221,7 @@ def _open_regular_nofollow(path: Path, flags: int, mode: int = 0o600) -> int:


def _read_state(path: Path) -> ControllerState:
"""Read and parse one state file, rejecting a symlink and non-UTF-8 content."""
descriptor = _open_regular_nofollow(path, os.O_RDONLY)
try:
with os.fdopen(descriptor, encoding="utf-8") as stream:
Expand Down Expand Up @@ -282,6 +300,8 @@ def update_state_file(

@dataclass(frozen=True)
class DispatchPlan:
"""The result of one admission pass: the updated state, grants, and rejections."""

state: ControllerState
dispatches: tuple[DispatchLease, ...]
rejections: dict[str, str]
Expand Down
9 changes: 5 additions & 4 deletions scripts/ci/sandboxed_web_e2e.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
import json
import os
import platform
import signal
import shutil
import shlex
import shutil
import signal
import socket
import subprocess
import sys
Expand All @@ -27,7 +27,6 @@

from scripts.ci import sandboxed_verify


RESULT_MARKER = "SANDBOXED_WEB_E2E_RESULT"
SANDBOX_MOUNT = "/workspace"

Expand Down Expand Up @@ -584,7 +583,9 @@ def wait_for_url(url: str, timeout: int, service: Service) -> bool:
if 200 <= response.status < 500:
return True
time.sleep(1)
except (urllib.error.URLError, TimeoutError):
except (urllib.error.URLError, TimeoutError) as exc:
if isinstance(exc, urllib.error.HTTPError):
exc.close()
time.sleep(1)
return False

Expand Down
Loading
Loading