Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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: 1 addition & 1 deletion ci/infrastructure/projects.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def _image_builders():
#
# Bump on any change to the baked venv contents (_runtime_prebuilt_venvs) or
# the baked controller component (_praktika_controller_component).
recipe_version = "1.0.22"
recipe_version = "1.0.23"

return [
Components.create_awslinux_image_builder_config(
Expand Down
70 changes: 70 additions & 0 deletions ci/tests/test_pool_autoscaler.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,38 @@ def test_pool_autoscaler_builds_scheduled_lambda():
)


def test_pool_autoscaler_wires_eager_mode_from_runner_pool():
eager_pool = RunnerPool(
name="arm-eager",
instance_type="t4g.small",
vpc_name="praktika-ci",
scaling=RunnerPool.Scaling.Auto,
scale_mode=RunnerPool.ScaleMode.Eager,
size=0,
max_size=50,
)
gradual_pool = RunnerPool(
name="arm-gradual",
instance_type="t4g.small",
vpc_name="praktika-ci",
scaling=RunnerPool.Scaling.Auto,
size=0,
max_size=50,
)

autoscaler = PoolAutoscaler.from_pools([eager_pool, gradual_pool])
env = autoscaler.lambda_config.environments["POOLS_CONFIG_JSON"]
assert '"mode":"eager"' in env
assert '"mode":"gradual"' in env


def test_pool_autoscaler_rejects_unknown_mode():
import pytest

with pytest.raises(ValueError, match="unknown mode"):
PoolAutoscaler(pools=[PoolAutoscaler.Pool(name="arm", mode="turbo")])


def test_rate_expression_clamps_to_minute():
assert _rate_expression_for_seconds(0) == "rate(1 minute)"
assert _rate_expression_for_seconds(60) == "rate(1 minute)"
Expand Down Expand Up @@ -150,6 +182,44 @@ def test_calculate_desired_capacity_steps_by_30_percent_of_gap():
)


def test_calculate_desired_capacity_eager_closes_whole_gap_at_once():
# Eager mode provisions one instance per queued/in-flight task in a single
# invocation instead of the 30% ramp, capped only at max_size.
assert (
_calculate_desired_capacity(
current_desired=0,
max_size=1000,
visible_messages=100,
in_flight_messages=0,
mode="eager",
)
== 100
)
# Reserve sits on top of the per-task capacity, same as gradual mode.
assert (
_calculate_desired_capacity(
current_desired=2,
max_size=1000,
visible_messages=10,
in_flight_messages=5,
capacity_reserve=2,
mode="eager",
)
== 17
)
# Still capped at max_size and still scale-up only.
assert (
_calculate_desired_capacity(
current_desired=0,
max_size=5,
visible_messages=100,
in_flight_messages=0,
mode="eager",
)
== 5
)


def test_calculate_desired_capacity_never_scales_down():
assert (
_calculate_desired_capacity(
Expand Down
14 changes: 14 additions & 0 deletions praktika/hook_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,20 @@ def _build_pending_summary(cls, _workflow, config_job_running):
results.append(result)
summary_result = Result.create_new(_workflow.name, Result.Status.RUNNING, results=results)
summary_result.start_time = Utils.timestamp()
# Job dependency graph (job name -> list of jobs it needs to finish),
# kept on the summary ext so the report timeline can show it on hover.
# Lives on the summary (not per-job rows, which get replaced as jobs
# complete), so it survives every subsequent report update. Use the
# parsed workflow `needs` (resolved to job names) rather than the raw
# `requires`, which lists artifact names — those would never match a
# timeline row.
parsed_jobs = WorkflowConfigParser(_workflow).parse().workflow_yaml_config.job_to_config
job_requires = {
job.name: list(parsed_jobs[job.name].needs)
for job in _workflow.jobs
if job.name in parsed_jobs
}
summary_result.add_ext_key_value("job_requires", job_requires)
info = Info()
report_url_current_sha = info.get_report_url(latest=False)
summary_result.add_ext_key_value("pr_title", info.pr_title).add_ext_key_value("git_branch", info.git_branch).add_ext_key_value("report_url", report_url_current_sha).add_ext_key_value(
Expand Down
6 changes: 5 additions & 1 deletion praktika/html_prepare.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,12 @@ def prepare(cls, is_test):

compressed_file = Utils.compress_gz(page_file)

page_name = Settings.get_report_page_name()
if is_test:
page_name = page_name.removesuffix(".html") + "_test.html"

S3.copy_file_to_s3(
s3_path=str(Path(Settings.S3_REPORT_BUCKET) / Path(page_file).name),
s3_path=str(Path(Settings.S3_REPORT_BUCKET) / page_name),
local_path=compressed_file,
content_type="text/html",
content_encoding="gzip",
Expand Down
5 changes: 2 additions & 3 deletions praktika/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import os
import traceback
import urllib.parse
from pathlib import Path
from typing import Optional

from .settings import Settings
Expand Down Expand Up @@ -263,7 +262,7 @@ def get_specific_report_url(
path = path.replace(bucket, endpoint)
break
workflow_name = workflow_name or self.env.WORKFLOW_NAME
res = f"https://{path}/{Path(Settings.HTML_PAGE_FILE).name}?{ref_param}&sha={sha}&name_0={urllib.parse.quote(workflow_name, safe='')}"
res = f"https://{path}/{Settings.get_report_page_name()}?{ref_param}&sha={sha}&name_0={urllib.parse.quote(workflow_name, safe='')}"
if job_name:
res += f"&name_1={urllib.parse.quote(job_name, safe='')}"
return res
Expand All @@ -282,7 +281,7 @@ def get_specific_report_url_static(pr_number, branch, sha, job_name, workflow_na
if bucket in path:
path = path.replace(bucket, endpoint)
break
res = f"https://{path}/{Path(Settings.HTML_PAGE_FILE).name}?{ref_param}&sha={sha}&name_0={urllib.parse.quote(workflow_name, safe='')}"
res = f"https://{path}/{Settings.get_report_page_name()}?{ref_param}&sha={sha}&name_0={urllib.parse.quote(workflow_name, safe='')}"
if job_name:
res += f"&name_1={urllib.parse.quote(job_name, safe='')}"
return res
Expand Down
29 changes: 29 additions & 0 deletions praktika/infrastructure/native/image_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,28 @@ def _write_file_from_base64(path: str, content: str) -> str:
return f"printf '%s' '{payload}' | base64 -d > {path}"


# Relax ext4 fsync cost on the runner root fs (~10x faster fsync, measured).
# Set as superblock DEFAULT mount options via tune2fs so they apply on the next
# boot of every instance from this AMI (root fstab uses `defaults`), no boot hook:
# - journal_data_writeback: still journal metadata, but stop forcing file DATA
# to disk ahead of it. Can't be weakened on a mounted root, hence build time.
# - nobarrier: stop the device cache flush on every journal commit (the durable
# EBS round-trip that dominates fsync); fsync returns once the write is acked.
# Durability trade-off (journal/data lost or stale on unclean power loss) is safe
# ONLY for disposable, single-tenant, never-resurrected hosts. These recipes bake
# RUNNER AMIs exclusively: a crashed runner is terminated and replaced, its job
# re-run, artifacts live in S3. NOT for stateful hosts (e.g. the CIDB server).
_ROOT_FAST_MOUNT_COMMAND = (
'case "$(findmnt -no FSTYPE /)" in '
'ext2|ext3|ext4) tune2fs -o journal_data_writeback,nobarrier "$(findmnt -no SOURCE /)" ;; '
'*) ;; '
'esac'
)


def _setup_component(name: str, *, with_docker: bool):
commands = [
_ROOT_FAST_MOUNT_COMMAND,
Comment thread
praktika-gh[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
# AL2023 ships curl-minimal, but Git-related dependencies can require
# full curl. Allow dnf to replace the minimal package so Python does
# not get skipped by a curl/curl-minimal solver conflict.
Expand Down Expand Up @@ -46,6 +66,7 @@ def _setup_component(name: str, *, with_docker: bool):

def _ubuntu_setup_component(name: str, *, with_docker: bool):
commands = [
_ROOT_FAST_MOUNT_COMMAND,
"export DEBIAN_FRONTEND=noninteractive",
# Stop stock Ubuntu background apt/snap upgrades from holding the dpkg
# lock -- both during this build (racing our own apt-get) and, once the
Expand Down Expand Up @@ -427,6 +448,14 @@ def _image_test_component(
"python3.12 -m pip --version",
"python3.12 -m pip show praktika-controller",
'python3.12 -c "import boto3, jwt, cryptography, requests"',
# Fast-mount flags from _ROOT_FAST_MOUNT_COMMAND must be baked into the
# root fs superblock of this AMI. We read them back with `tune2fs -l`
# rather than `findmnt`/`/proc/mounts`: ext4 omits any mount option that
# equals the superblock default from the live options string, so a
# successful bake makes these invisible there. `tune2fs -l` lists them
# literally on the "Default mount options" line.
'tune2fs -l "$(findmnt -no SOURCE /)" | grep -i "^Default mount options:" | grep -q journal_data_writeback',
'tune2fs -l "$(findmnt -no SOURCE /)" | grep -i "^Default mount options:" | grep -q nobarrier',
]
if with_docker:
commands.extend(
Expand Down
33 changes: 25 additions & 8 deletions praktika/infrastructure/native/lambda_pool_autoscaler.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@
# both sides (see praktika.orchestrator.throttle.CAPACITY_S3_KEY).
CAPACITY_S3_KEY = "pool_capacity.json"

# Scale-up pacing modes a pool can request (see _calculate_desired_capacity).
# Mirrored by RunnerPool.ScaleMode on the config side; new strategies get added
# here and there without changing the pool-config wire shape.
SCALE_MODE_GRADUAL = "gradual" # default: close ~30% of the outstanding gap/min
SCALE_MODE_EAGER = "eager" # close the whole gap at once (one instance per task)

# S3 key prefix (under the project artifact bucket) where this autoscaler
# publishes each ASG's current target AMI. Must match the consumer side in
# bootstrap/src/praktika_controller/common.py (AMI_TARGET_S3_PREFIX). Runners
Expand Down Expand Up @@ -83,6 +89,7 @@ def _calculate_desired_capacity(
visible_messages: int,
in_flight_messages: int,
capacity_reserve: int = 0,
mode: str = SCALE_MODE_GRADUAL,
) -> int:
# Scheduled autoscaling is scale-up only. Scale-in is owned by the VMs
# themselves after they observe sustained queue idleness from inside the
Expand All @@ -96,15 +103,22 @@ def _calculate_desired_capacity(
if target_work_capacity <= current_work_capacity:
return min(max_size, max(current_desired, capacity_reserve))

# Grow toward the target by max(30% of the OUTSTANDING gap, 1) per
# invocation (the schedule fires once a minute). The gap is backlog not yet
# covered by current_desired, which already includes instances we requested
# on earlier runs but that are still booting. Stepping off the gap (rather
# than the raw backlog) means each minute decelerates as pending capacity
# ramps up, instead of slamming in another big batch for a backlog that is
# already being provisioned for and just hasn't been picked up yet.
# Grow toward the target. In the default (dampened) mode step by
# max(30% of the OUTSTANDING gap, 1) per invocation (the schedule fires once
# a minute). The gap is backlog not yet covered by current_desired, which
# already includes instances we requested on earlier runs but that are still
# booting. Stepping off the gap (rather than the raw backlog) means each
# minute decelerates as pending capacity ramps up, instead of slamming in
# another big batch for a backlog that is already being provisioned for and
# just hasn't been picked up yet.
#
# In eager mode we close the whole gap in one invocation — one instance per
# queued/in-flight task, capped only by max_size. This is for pools that must
# minimize queue latency and are willing to pay for the transient
# over-provisioning while the batch boots (the backlog is still counted as
# outstanding until a runner picks each job up).
gap = target_work_capacity - current_work_capacity
step = max(1, math.ceil(gap * 0.3))
step = gap if mode == SCALE_MODE_EAGER else max(1, math.ceil(gap * 0.3))
new_work_capacity = min(target_work_capacity, current_work_capacity + step)
target_capacity = min(max_size, capacity_reserve + new_work_capacity)
if target_capacity <= current_desired:
Expand All @@ -131,6 +145,7 @@ def lambda_handler(event, context):
queue_name = str(pool.get("queue_name") or pool_name)
asg_name = str(pool.get("asg_name") or pool_name)
capacity_reserve = max(0, int(pool.get("capacity_reserve") or 0))
mode = str(pool.get("mode") or SCALE_MODE_GRADUAL)

# A single pool whose SQS queue or ASG is missing (e.g. not deployed
# yet, renamed, or not covered by this role's IAM scope) must not abort
Expand Down Expand Up @@ -180,6 +195,7 @@ def lambda_handler(event, context):
visible_messages=visible_messages,
in_flight_messages=in_flight_messages,
capacity_reserve=capacity_reserve,
mode=mode,
)
# Defensive clamp: even if future _calculate_desired_capacity changes,
# this autoscaler must never scale a pool down. VM self-termination is
Expand Down Expand Up @@ -217,6 +233,7 @@ def lambda_handler(event, context):
"current_desired": current_desired,
"max_size": max_size,
"capacity_reserve": capacity_reserve,
"mode": mode,
"new_desired": new_desired,
"scaled": scaled,
}
Expand Down
21 changes: 20 additions & 1 deletion praktika/infrastructure/native/pool_autoscaler.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,15 @@
from praktika.settings import Settings

from . import iam_scope
from .lambda_pool_autoscaler import CAPACITY_S3_KEY
from .lambda_pool_autoscaler import (
CAPACITY_S3_KEY,
SCALE_MODE_EAGER,
SCALE_MODE_GRADUAL,
)

# Valid scale-up modes a pool can request; validated at config build time so a
# typo fails the deploy rather than silently falling back at runtime.
_SCALE_MODES = frozenset({SCALE_MODE_GRADUAL, SCALE_MODE_EAGER})

# S3 key prefix (under the project artifact bucket) where this autoscaler
# publishes each ASG's target AMI for its runners to read. Must match
Expand All @@ -31,6 +39,9 @@ class Pool:
queue_name: str = ""
asg_name: str = ""
capacity_reserve: int = 0
# Scale-up pacing: "gradual" (default 30%/min ramp) or "eager" (close the
# whole backlog gap in one invocation). See lambda_pool_autoscaler.
mode: str = SCALE_MODE_GRADUAL
ext: Dict[str, Any] = field(default_factory=dict)

name: str = "pool-autoscaler"
Expand All @@ -53,6 +64,12 @@ def __post_init__(self):
raise ValueError(
f"PoolAutoscaler pool {pool.name!r} has negative capacity_reserve"
)
pool.mode = pool.mode or SCALE_MODE_GRADUAL
if pool.mode not in _SCALE_MODES:
raise ValueError(
f"PoolAutoscaler pool {pool.name!r} has unknown mode "
f"{pool.mode!r}; expected one of {sorted(_SCALE_MODES)}"
)

pool_config_json = json.dumps(
[
Expand All @@ -61,6 +78,7 @@ def __post_init__(self):
"queue_name": pool.queue_name,
"asg_name": pool.asg_name,
"capacity_reserve": pool.capacity_reserve,
"mode": pool.mode,
}
for pool in self.pools
],
Expand Down Expand Up @@ -188,6 +206,7 @@ def from_pools(
queue_name=getattr(getattr(pool, "queue", None), "name", ""),
asg_name=getattr(getattr(pool, "autoscaling_group", None), "name", ""),
capacity_reserve=getattr(pool, "capacity_reserve", 0),
mode=getattr(pool, "scale_mode", SCALE_MODE_GRADUAL),
)
for pool in pools
if getattr(pool, "scaling", "") == "auto"
Expand Down
15 changes: 15 additions & 0 deletions praktika/infrastructure/native/runner_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -350,11 +350,22 @@ class Scaling:
Disabled = "disabled"
Auto = "auto"

class ScaleMode:
# How an auto-scaled pool paces scale-up (ignored when scaling is
# Disabled). Gradual closes ~30% of the outstanding backlog gap per
# autoscaler tick; Eager provisions one instance per queued/in-flight
# task at once, trading transient over-provisioning for lowest queue
# latency. See native.lambda_pool_autoscaler._calculate_desired_capacity.
Gradual = "gradual"
Eager = "eager"

name: str
instance_type: str
scaling: str
size: int
max_size: int
# Scale-up pacing for auto-scaled pools; ignored when scaling is Disabled.
scale_mode: str = ScaleMode.Gradual
Comment thread
praktika-gh[bot] marked this conversation as resolved.
Resolved
vpc_name: str = ""
ami_id: str = "" # resolved at deploy time via SSM if empty
image_builder: ImageBuilder.Config | None = None
Expand Down Expand Up @@ -405,6 +416,10 @@ def __post_init__(self):
f"RunnerPool scaling={self.scaling!r} is not supported; "
f"use Scaling.Disabled or Scaling.Auto"
)
assert self.scale_mode in (self.ScaleMode.Gradual, self.ScaleMode.Eager), (
f"RunnerPool scale_mode={self.scale_mode!r} is not supported; "
f"use ScaleMode.Gradual or ScaleMode.Eager"
)
min_size = 0 if self.scaling == self.Scaling.Auto else 1
assert self.size >= min_size, (
f"size={self.size} is invalid for scaling={self.scaling!r}; "
Expand Down
Loading