Skip to content
Merged
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
4 changes: 4 additions & 0 deletions docs/reference/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,10 @@ Behavior:
is too loaded to deploy
- counts only controller states that still consume runtime capacity; pending
labels by themselves do not count as active previews
- expires overdue previews before evaluating a new start, so delayed GitHub
schedules cannot leave stale runtimes occupying every admission slot
- keeps failed stop/cleanup states and their dependency leases capacity-visible
until cleanup succeeds
- runs storage-preserving `envctl blast-all` cleanup when active preview count
reaches zero, passing keep-volume flags so leftover containers and processes
are killed without deleting copied runtime storage
Expand Down
147 changes: 114 additions & 33 deletions python/envctl_engine/pr_preview_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,25 @@
PR_PREVIEW_SERVICE_ENV_OVERLAY_PATTERN = re.compile(
r"^ENVCTL_[A-Z][A-Z0-9_]*_ENV__[A-Z_][A-Z0-9_]*$"
)
FAILED_START_STATUSES = frozenset({"public_route_unhealthy", "start_failed"})
CAPACITY_CONSUMING_PREVIEW_STATUSES = frozenset({"running", "starting", "qa_user_failed", "public_route_failed"})
FAILED_START_STATUSES = frozenset(
{
"public_route_cleanup_failed",
"public_route_unhealthy",
"start_cleanup_failed",
Comment on lines +104 to +106

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear cleanup-failed state after retry cleanup

When a PR is already in start_cleanup_failed or public_route_cleanup_failed, adding these values to FAILED_START_STATUSES makes a retry run cleanup_failed_start_preview() and then continue. If that cleanup succeeds but the retry fails before saving a replacement state, such as an envctl import failure, the old cleanup-failed state remains on disk and is still capacity-consuming even though the runtime was just blasted and leases may have been released, so unrelated previews can keep being denied. Clear/save the state after successful retry cleanup before proceeding.

Useful? React with 👍 / 👎.

"start_failed",
}
)
CAPACITY_CONSUMING_PREVIEW_STATUSES = frozenset(
{
"public_route_cleanup_failed",
"public_route_failed",
"qa_user_failed",
"running",
"start_cleanup_failed",
"starting",
"stop_failed",
}
)
PUBLIC_ROUTE_HEALTH_DEADLINE_SECONDS = 30.0
PUBLIC_ROUTE_HEALTH_INTERVAL_SECONDS = 2.0
PUBLIC_ROUTE_REQUEST_TIMEOUT_SECONDS = 5.0
Expand Down Expand Up @@ -1896,6 +1913,11 @@ def start(
)
return 0

self.expire_overdue_previews(
self.active_prs_with_label(),
now=utc_now(),
exclude_pr_numbers={pr.number},
)
Comment on lines +1916 to +1920

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Make stale-preview expiry best-effort during start

In the pull_request_target start path, this new pre-admission expiry pass makes every label/synchronize start depend on active_prs_with_label(), which ultimately runs gh pr list through CommandRunner.json with check=True. If that GitHub list call has a transient failure, the controller raises before deploying the PR already present in the event payload and before posting the normal failure comment; stale-preview expiry is an optimization, so it should be caught/logged as best-effort rather than aborting all new preview starts during a list API hiccup.

Useful? React with 👍 / 👎.

active_previews = self.capacity_consuming_preview_states()
stats = collect_machine_stats(self.config.preview_root, self.runner)
reasons = overload_reasons(
Expand Down Expand Up @@ -2165,13 +2187,11 @@ def run_import() -> CommandResult:
)
self.save_state(state)
cleanup_code = self.cleanup_failed_start_preview(state)
self.release_external_dependency_leases(
pr.number,
external_dependencies,
self.record_failed_start_cleanup(
state,
cleanup_code=cleanup_code,
cleanup_failed_status="start_cleanup_failed",
)
if external_dependencies:
state = PreviewState(**{**asdict(state), "external_dependencies": {}})
self.save_state(state)
self.comment(
pr.number,
self.render_failure_comment(
Expand Down Expand Up @@ -2293,13 +2313,11 @@ def run_import() -> CommandResult:
)
self.save_state(state)
cleanup_code = self.cleanup_failed_start_preview(state)
self.release_external_dependency_leases(
pr.number,
external_dependencies,
self.record_failed_start_cleanup(
state,
cleanup_code=cleanup_code,
cleanup_failed_status="public_route_cleanup_failed",
)
if external_dependencies:
state = PreviewState(**{**asdict(state), "external_dependencies": {}})
self.save_state(state)
self.comment(
pr.number,
self.render_failure_comment(
Expand Down Expand Up @@ -2454,6 +2472,34 @@ def cleanup_failed_start_preview(self, state: PreviewState) -> int:
self.remove_project_docker_artifacts(raw_name)
return 0

def record_failed_start_cleanup(
self,
state: PreviewState,
*,
cleanup_code: int,
cleanup_failed_status: str,
) -> PreviewState:
status = state.status
external_dependencies = state.external_dependencies
if cleanup_code == 0:
self.release_external_dependency_leases(
state.pr_number,
external_dependencies,
)
external_dependencies = {}
else:
status = cleanup_failed_status
updated = PreviewState(
**{
**asdict(state),
"status": status,
"updated_at": isoformat(utc_now()) or "",
"external_dependencies": external_dependencies,
}
)
self.save_state(updated)
return updated

def publish_public_routes(
self,
pr_number: int,
Expand Down Expand Up @@ -2672,27 +2718,14 @@ def sweep(self) -> int:
if not active_prs:
return self.blast_all_if_scaled_to_zero()
now = utc_now()
exit_code = 0
expired_pr_numbers, exit_code = self.expire_overdue_previews(
active_prs,
now=now,
)
for pr in active_prs:
state = self.load_state(pr.number)
active_since = self.label_active_since(pr.number)
saved_active_since = parse_github_datetime(state.label_added_at) if state and state.label_added_at else None
if active_since is None:
active_since = saved_active_since
elif saved_active_since is not None and saved_active_since > active_since:
active_since = saved_active_since
if active_since is None:
active_since = now
expires_at = active_since + timedelta(minutes=self.config.ttl_minutes)
if now >= expires_at:
self.comment(
pr.number,
self.render_ttl_comment(pr, active_since, expires_at),
)
stop_code = self.stop(pr, reason="preview TTL expired", comment=False)
self.remove_label(pr.number)
exit_code = exit_code or stop_code
if pr.number in expired_pr_numbers:
continue
state = self.load_state(pr.number)
if state and state.status in {"running", "starting"}:
if state.head_sha and state.head_sha != pr.head_sha:
exit_code = exit_code or self.start(
Expand All @@ -2715,6 +2748,54 @@ def sweep(self) -> int:
exit_code = exit_code or self.start(pr, reason="scheduled reconciliation")
return exit_code

def expire_overdue_previews(
self,
active_prs: list[PullRequestInfo],
*,
now: datetime,
exclude_pr_numbers: set[int] | None = None,
) -> tuple[set[int], int]:
excluded = exclude_pr_numbers or set()
expired: set[int] = set()
exit_code = 0
for pr in active_prs:
if pr.number in excluded:
continue
state = self.load_state(pr.number)
active_since = self.label_active_since(pr.number)
saved_active_since = (
parse_github_datetime(state.label_added_at)
if state and state.label_added_at
else None
)
if active_since is None:
active_since = saved_active_since
elif (
saved_active_since is not None
and saved_active_since > active_since
):
active_since = saved_active_since
if active_since is None:
active_since = now
expires_at = active_since + timedelta(
minutes=self.config.ttl_minutes
)
if now < expires_at:
continue
expired.add(pr.number)
self.comment(
pr.number,
self.render_ttl_comment(pr, active_since, expires_at),
)
stop_code = self.stop(
pr,
reason="preview TTL expired",
comment=False,
)
self.remove_label(pr.number)
exit_code = exit_code or stop_code
return expired, exit_code

def blast_all_if_scaled_to_zero(
self,
candidate_states: list[PreviewState] | None = None,
Expand Down
1 change: 1 addition & 0 deletions tests/python/runtime/test_engine_runtime_resume_startup.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,7 @@ def test_resume_rejects_state_without_resumable_services(self) -> None:
output = StringIO()
with (
patch.object(engine, "_try_load_existing_state", return_value=state),
patch.object(engine, "_state_has_resumable_services", return_value=False),
patch.object(engine, "_run_interactive_dashboard_loop", return_value=0) as loop_mock,
patch(
"envctl_engine.startup.resume_orchestrator.release_lifecycle_operation"
Expand Down
Loading
Loading