You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tooling.apache.org by sb...@apache.org on 2026/07/03 15:36:58 UTC
(tooling-trusted-releases) branch sbp updated (8ef0d679 -> bbe6c325)
This is an automated email from the ASF dual-hosted git repository.
sbp pushed a change to branch sbp
in repository https://gitbox.apache.org/repos/asf/tooling-trusted-releases.git
discard 8ef0d679 Prefork task workers and stagger how many tasks they accept
add 208aea4e #1363 - send email when release is announced or picked up by the SVN watcher
new f8e50f58 Prefork task workers and stagger how many tasks they accept
new bbe6c325 Check action payload values as well as keys
This update added new revisions after undoing existing revisions.
That is to say, some revisions that were in the old version of the
branch are not in the new version. This situation occurs
when a user --force pushes a change and generates a repository
containing something like this:
* -- * -- B -- O -- O -- O (8ef0d679)
\
N -- N -- N refs/heads/sbp (bbe6c325)
You should already have received notification emails for all of the O
revisions, and so the following emails describe only the N revisions
from the common base, B.
Any revisions marked "omit" are not gone; other references still
refer to them. Any revisions marked "discard" are gone forever.
The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.github/workflows/build.yml | 1 +
atr/construct.py | 50 +++++++---
atr/storage/__init__.py | 7 ++
atr/storage/writers/announce.py | 14 +++
atr/storage/writers/release.py | 18 +++-
atr/tasks/gha.py | 41 ++++----
atr/tasks/message.py | 76 +++++++++------
tests/contract/jqbody.py | 112 ++++++++++++++++++++++
tests/contract/test_actions_contract.py | 97 ++++++++-----------
tests/contract/test_actions_conventions.py | 145 +++++++++++++++++++++++++++++
10 files changed, 447 insertions(+), 114 deletions(-)
create mode 100644 tests/contract/jqbody.py
create mode 100644 tests/contract/test_actions_conventions.py
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org
(tooling-trusted-releases) 02/02: Check action payload values as well as keys
Posted by sb...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sbp pushed a commit to branch sbp
in repository https://gitbox.apache.org/repos/asf/tooling-trusted-releases.git
commit bbe6c325d7758bf5c64f0d809eb4ea08105c9e14
Author: Sean B. Palmer <se...@miscoranda.com>
AuthorDate: Fri Jul 3 16:35:54 2026 +0100
Check action payload values as well as keys
---
.github/workflows/build.yml | 1 +
atr/tasks/gha.py | 41 ++++----
tests/contract/jqbody.py | 112 ++++++++++++++++++++++
tests/contract/test_actions_contract.py | 97 ++++++++-----------
tests/contract/test_actions_conventions.py | 145 +++++++++++++++++++++++++++++
5 files changed, 323 insertions(+), 73 deletions(-)
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 85adfea5..d86bbf43 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -55,6 +55,7 @@ jobs:
ref: main
path: tooling-actions
persist-credentials: false
+ fetch-depth: 0
- uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
with:
python-version: ${{ matrix.python-version }}
diff --git a/atr/tasks/gha.py b/atr/tasks/gha.py
index e9c0faa0..7577008a 100644
--- a/atr/tasks/gha.py
+++ b/atr/tasks/gha.py
@@ -41,6 +41,29 @@ _FAILED_STATUSES: Final[list[str]] = ["failure", "startup_failure"]
_TIMEOUT_S = 60
+def dispatch_workflow_and_payload(
+ task_args: args.DistributionWorkflow, task_id: int | None, unique_id: str
+) -> tuple[str, dict[str, Any]]:
+ sql_platform = sql.DistributionPlatform[task_args.platform]
+ workflow = f"distribute-{sql_platform.value.gh_slug}{'-stg' if task_args.staging else ''}.yml"
+ payload = {
+ "ref": "main",
+ "inputs": {
+ "atr-id": unique_id,
+ "asf-uid": task_args.asf_uid,
+ "task_id": task_id,
+ "project": str(task_args.project_key),
+ "phase": task_args.phase,
+ "version": str(task_args.version_key),
+ "distribution-owner-namespace": task_args.namespace,
+ "distribution-package": str(task_args.package),
+ "distribution-version": str(task_args.version),
+ # **task_args.arguments,
+ },
+ }
+ return workflow, payload
+
+
@checks.with_model(args.WorkflowStatusCheck)
async def status_check(task_args: args.WorkflowStatusCheck) -> results.DistributionWorkflowStatus:
"""Check remote workflow statuses."""
@@ -119,25 +142,9 @@ async def trigger_workflow(
unique_id = f"atr-dist-{task_args.name}-{uuid.uuid4()}"
project = task_args.project_key
try:
- sql_platform = sql.DistributionPlatform[task_args.platform]
+ workflow, payload = dispatch_workflow_and_payload(task_args, task_id, unique_id)
except KeyError:
_fail(f"Invalid platform: {task_args.platform}")
- workflow = f"distribute-{sql_platform.value.gh_slug}{'-stg' if task_args.staging else ''}.yml"
- payload = {
- "ref": "main",
- "inputs": {
- "atr-id": unique_id,
- "asf-uid": task_args.asf_uid,
- "task_id": task_id,
- "project": str(task_args.project_key),
- "phase": task_args.phase,
- "version": str(task_args.version_key),
- "distribution-owner-namespace": task_args.namespace,
- "distribution-package": str(task_args.package),
- "distribution-version": str(task_args.version),
- # **task_args.arguments,
- },
- }
headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {config.get().GITHUB_TOKEN}"}
log.info(
diff --git a/tests/contract/jqbody.py b/tests/contract/jqbody.py
new file mode 100644
index 00000000..53c93429
--- /dev/null
+++ b/tests/contract/jqbody.py
@@ -0,0 +1,112 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import json
+import re
+
+DYNAMIC = object()
+
+_BINDING_RE = re.compile(r"--(arg|argjson)\s+(\w+)\s+")
+_LITERAL_RE = re.compile(r"'(\{.*?\})'", re.DOTALL)
+_QUOTED_RE = re.compile(r'"((?:[^"\\]|\\.)*)"')
+_VAR_RE = re.compile(r'"\$(\w+)"|\$(\w+)')
+
+
+def parse_body(run):
+ if run.count("jq -n") != 1:
+ raise ValueError(f"expected one jq -n invocation, found {run.count('jq -n')}")
+ bindings = _bindings(run)
+ body = {}
+ for entry in _entries(_object_literal(run)):
+ field, _, value = entry.partition(":")
+ field = field.strip()
+ value = value.strip()
+ if value.startswith("$"):
+ if value[1:] not in bindings:
+ raise ValueError(f"no --arg or --argjson binding for {value}")
+ body[field] = bindings[value[1:]]
+ else:
+ body[field] = json.loads(value)
+ return body
+
+
+def steps(doc):
+ runs = doc.get("runs")
+ if isinstance(runs, dict):
+ steps_list = runs.get("steps")
+ return steps_list if isinstance(steps_list, list) else []
+ jobs = doc.get("jobs")
+ if isinstance(jobs, dict):
+ flat = []
+ for job in jobs.values():
+ if isinstance(job, dict):
+ job_steps = job.get("steps")
+ if isinstance(job_steps, list):
+ flat.extend(job_steps)
+ return flat
+ return []
+
+
+def _binding_value(kind, name, rest, run):
+ if kind == "argjson":
+ var_match = _VAR_RE.match(rest)
+ if var_match is None:
+ raise ValueError(f"--argjson {name} is not bound to a variable")
+ var = var_match.group(1) or var_match.group(2)
+ assignment = re.search(rf"^\s*{var}=(\S+)", run, re.MULTILINE)
+ if assignment is None:
+ raise ValueError(f"no assignment for {var} in the run block")
+ return json.loads(assignment.group(1))
+ if rest.startswith(('"$', "$")):
+ return DYNAMIC
+ if rest.startswith('"'):
+ quoted = _QUOTED_RE.match(rest)
+ if quoted is None:
+ raise ValueError(f"unterminated literal for --arg {name}")
+ return quoted.group(1)
+ return rest.split(None, 1)[0].rstrip("\\")
+
+
+def _bindings(run):
+ bindings = {}
+ for match in _BINDING_RE.finditer(run):
+ kind, name = match.group(1), match.group(2)
+ bindings[name] = _binding_value(kind, name, run[match.end() :], run)
+ return bindings
+
+
+def _entries(literal):
+ entries = []
+ current = []
+ quoted = False
+ for char in literal.strip()[1:-1]:
+ if char == '"':
+ quoted = not quoted
+ if (char == ",") and (not quoted):
+ entries.append("".join(current))
+ current = []
+ else:
+ current.append(char)
+ entries.append("".join(current))
+ return [entry.strip() for entry in entries if entry.strip()]
+
+
+def _object_literal(run):
+ literals = _LITERAL_RE.findall(run)
+ if len(literals) != 1:
+ raise ValueError(f"expected one jq object literal, found {len(literals)}")
+ return literals[0]
diff --git a/tests/contract/test_actions_contract.py b/tests/contract/test_actions_contract.py
index dcc0331c..fe367fb1 100644
--- a/tests/contract/test_actions_contract.py
+++ b/tests/contract/test_actions_contract.py
@@ -15,6 +15,7 @@
# specific language governing permissions and limitations
# under the License.
+import enum
import os
import pathlib
@@ -22,9 +23,17 @@ import pytest
import yaml
import atr.models.api as api
+import tests.contract.jqbody as jqbody
_ACTIONS_ENV = "TOOLING_ACTIONS_PATH"
+_FALLBACK_VALUES = {
+ "message": "message",
+ "project_key": "tooling",
+ "run_id": "12345",
+ "workflow": "distribute-mavencentral.yml",
+}
+
_STATIC_PAIRS = [
("upload-to-atr/action.yml", "/api/publisher/ssh/register", api.PublisherSshRegisterArgs),
("atr-distribute-test/action.yml", "/api/publisher/ssh/register", api.PublisherSshRegisterArgs),
@@ -56,47 +65,24 @@ def _contract_pairs():
return pairs
-def _field_names(literal):
- fields = set()
- for pair in literal[1:-1].split(","):
- name = pair.split(":", 1)[0].strip()
- if name:
- fields.add(name)
- return fields
-
-
-def _object_literals(run):
- literals = []
- i = 0
- while i < len(run):
- start = run.find("'", i)
- if start == -1:
- break
- end = run.find("'", start + 1)
- if end == -1:
- break
- literal = run[start + 1 : end]
- if literal.startswith("{") and literal.endswith("}"):
- literals.append(literal)
- i = end + 1
- return literals
-
-
-def _steps(doc):
- runs = doc.get("runs")
- if isinstance(runs, dict):
- steps = runs.get("steps")
- return steps if isinstance(steps, list) else []
- jobs = doc.get("jobs")
- if isinstance(jobs, dict):
- flat = []
- for job in jobs.values():
- if isinstance(job, dict):
- job_steps = job.get("steps")
- if isinstance(job_steps, list):
- flat.extend(job_steps)
- return flat
- return []
+def _representative(model, field):
+ info = model.model_fields[field]
+ extra = info.json_schema_extra if isinstance(info.json_schema_extra, dict) else {}
+ if "example" in extra:
+ return _stringy(extra["example"])
+ if "examples" in extra:
+ return _stringy(extra["examples"][0])
+ if field in _FALLBACK_VALUES:
+ return _FALLBACK_VALUES[field]
+ raise ValueError(f"no example or fallback for {model.__name__}.{field}")
+
+
+def _stringy(value):
+ if isinstance(value, enum.Enum):
+ return value.name
+ if isinstance(value, str):
+ return value
+ return str(value)
_PAIRS = _contract_pairs()
@@ -110,23 +96,22 @@ _PAIRS = _contract_pairs()
def test_action_contract(file, endpoint, model):
root = _actions_root()
doc = yaml.safe_load((root / file).read_text())
- occurrences = []
- for step in _steps(doc):
+ bodies = []
+ for step in jqbody.steps(doc):
if not isinstance(step, dict):
continue
run = step.get("run")
if not isinstance(run, str) or endpoint not in run:
continue
- fields = set()
- for literal in _object_literals(run):
- fields |= _field_names(literal)
- occurrences.append(fields)
- assert occurrences, f"no step in {file} posts to {endpoint}"
- model_fields = set(model.model_fields)
- required = {name for name, field in model.model_fields.items() if field.is_required()}
- for fields in occurrences:
- assert fields, f"step in {file} posts to {endpoint} but sends no jq object literal"
- extras = fields - model_fields
- assert not extras, f"{file} sends extra {sorted(extras)} not in {model.__name__}"
- missing = required - fields
- assert not missing, f"{file} omits required {sorted(missing)} for {model.__name__}"
+ bodies.append(jqbody.parse_body(run))
+ assert bodies, f"no step in {file} posts to {endpoint}"
+ for body in bodies:
+ concrete = {}
+ for field, value in body.items():
+ if value is not jqbody.DYNAMIC:
+ concrete[field] = value
+ elif field in model.model_fields:
+ concrete[field] = _representative(model, field)
+ else:
+ concrete[field] = "unexpected"
+ model.model_validate(concrete)
diff --git a/tests/contract/test_actions_conventions.py b/tests/contract/test_actions_conventions.py
new file mode 100644
index 00000000..4b65d654
--- /dev/null
+++ b/tests/contract/test_actions_conventions.py
@@ -0,0 +1,145 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import os
+import pathlib
+import re
+import subprocess
+
+import pytest
+import yaml
+
+import atr.jwtoken as jwtoken
+import atr.models.args as args
+import atr.models.sql as sql
+import atr.post.distribution as distribution
+import atr.tasks.gha as gha
+import tests.contract.jqbody as jqbody
+
+_ACTIONS = [
+ "atr-distribute-test/action.yml",
+ "record-atr-distribution/action.yml",
+ "release-on-atr/action.yml",
+ "upload-to-atr/action.yml",
+]
+_AUDIENCE_RE = re.compile(r'&audience=https://\$\{\w+\}/"')
+_JWT_MARKER = "ACTIONS_ID_TOKEN_REQUEST_URL"
+_PIN_RE = re.compile(r"apache/tooling-actions/upload-to-atr@([0-9a-f]{40})")
+
+
+def test_audience_format():
+ root = _actions_root()
+ assert jwtoken._GITHUB_OIDC_AUDIENCE.endswith("/")
+ checked = 0
+ for path in [root / action for action in _ACTIONS] + _distribute_workflows(root):
+ for step in jqbody.steps(yaml.safe_load(path.read_text())):
+ run = step.get("run") if isinstance(step, dict) else None
+ if (not isinstance(run, str)) or (_JWT_MARKER not in run):
+ continue
+ checked += 1
+ assert _AUDIENCE_RE.search(run), f"{path.name} builds a non-conforming OIDC audience URL"
+ assert checked
+
+
+def test_dispatch_contract():
+ root = _actions_root()
+ non_str = []
+ for platform, staging in _dispatch_cases():
+ task_args = args.DistributionWorkflow(
+ namespace="org.apache.example",
+ package="example",
+ version="0.0.1",
+ staging=staging,
+ project_key="example",
+ version_key="0.0.1",
+ phase="compose",
+ asf_uid="user",
+ committee_key="example",
+ platform=platform.name,
+ arguments={},
+ name="example-0.0.1",
+ )
+ workflow, payload = gha.dispatch_workflow_and_payload(task_args, 32, "atr-dist-example-0.0.1-x")
+ path = root / ".github/workflows" / workflow
+ assert path.is_file(), f"{workflow} missing from the actions checkout"
+ doc = yaml.safe_load(path.read_text())
+ declared = doc.get("on", doc.get(True, {}))["workflow_dispatch"]["inputs"]
+ sent = payload["inputs"]
+ extras = sorted(set(sent) - set(declared))
+ assert not extras, f"{workflow} does not declare dispatch inputs {extras}"
+ required = {name for name, spec in declared.items() if spec.get("required")}
+ missing = sorted(required - set(sent))
+ assert not missing, f"dispatch payload omits required {workflow} inputs {missing}"
+ non_str.extend(f"{workflow}: {name}={value!r}" for name, value in sent.items() if not isinstance(value, str))
+ assert non_str == [], f"dispatch input values must be strings: {non_str}"
+
+
+def test_pinned_upload_snippet_fresh():
+ source = (pathlib.Path(__file__).parents[2] / "atr/get/upload.py").read_text()
+ match = _PIN_RE.search(source)
+ assert match, "no pinned upload-to-atr SHA in atr/get/upload.py"
+ sha = match.group(1)
+ root = _actions_root()
+ if _git(root, "rev-parse", "--git-dir").returncode != 0:
+ pytest.skip("actions checkout is not a git repository")
+ if _git(root, "rev-parse", "--is-shallow-repository").stdout.strip() == "true":
+ pytest.skip("actions checkout is shallow")
+ assert _git(root, "cat-file", "-e", f"{sha}^{{commit}}").returncode == 0, f"pinned SHA {sha} not in actions history"
+ diff = _git(root, "diff", "--quiet", sha, "HEAD", "--", "upload-to-atr/")
+ assert diff.returncode == 0, f"upload-to-atr/ changed since pinned SHA {sha}"
+
+
+def test_run_name_is_atr_id():
+ for path in _distribute_workflows(_actions_root()):
+ doc = yaml.safe_load(path.read_text())
+ assert doc.get("run-name") == "${{ inputs.atr-id }}", f"{path.name} run-name breaks run discovery"
+
+
+def test_workflow_env_matches_filename():
+ mismatches = []
+ for path in _distribute_workflows(_actions_root()):
+ doc = yaml.safe_load(path.read_text())
+ values = []
+ for job in doc.get("jobs", {}).values():
+ if isinstance(job, dict) and ("WORKFLOW" in job.get("env", {})):
+ values.append(job["env"]["WORKFLOW"])
+ assert values, f"{path.name} sets no WORKFLOW env"
+ mismatches.extend(f"{path.name}: WORKFLOW={value}" for value in values if value != path.name)
+ assert mismatches == []
+
+
+def _actions_root():
+ return pathlib.Path(os.environ["TOOLING_ACTIONS_PATH"])
+
+
+def _dispatch_cases():
+ allowlists = ((distribution._AUTOMATED_PLATFORMS, False), (distribution._AUTOMATED_PLATFORMS_STAGE, True))
+ cases = []
+ for platforms, staging in allowlists:
+ for platform in platforms:
+ cases.append((sql.DistributionPlatform[platform.name], staging))
+ return cases
+
+
+def _distribute_workflows(root):
+ paths = sorted(root.glob(".github/workflows/distribute-*.yml"))
+ assert paths, "no distribute workflows in the actions checkout"
+ return paths
+
+
+def _git(root, *arguments):
+ return subprocess.run(["git", "-C", str(root), *arguments], capture_output=True, text=True, check=False)
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org
(tooling-trusted-releases) 01/02: Prefork task workers and stagger how many tasks they accept
Posted by sb...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sbp pushed a commit to branch sbp
in repository https://gitbox.apache.org/repos/asf/tooling-trusted-releases.git
commit f8e50f58d0053ed917b0b22f15287bcddc9deb0d
Author: Sean B. Palmer <se...@miscoranda.com>
AuthorDate: Fri Jul 3 16:25:12 2026 +0100
Prefork task workers and stagger how many tasks they accept
---
atr/constants.py | 3 +++
atr/manager.py | 57 +++++++++++++++++++++++++++++++++++++++++++++++++-----
atr/worker.py | 2 +-
playwright/test.py | 2 +-
4 files changed, 57 insertions(+), 7 deletions(-)
diff --git a/atr/constants.py b/atr/constants.py
index 5060759a..6f90b886 100644
--- a/atr/constants.py
+++ b/atr/constants.py
@@ -258,3 +258,6 @@ INACTIVITY_WARNING_DAYS: Final[int] = 80
# Fixed sub claim on JWTs minted from system PATs, and the UID we log for
# their actions. The minting admin is recorded separately in PAT.created_by.
SYSTEM_SERVICE_UID: Final[str] = "system"
+
+WORKER_MAX_TASKS_ENV: Final[str] = "ATR_WORKER_MAX_TASKS"
+WORKER_TASK_BUDGETS: Final[tuple[int, ...]] = (8, 14, 10, 16, 12)
diff --git a/atr/manager.py b/atr/manager.py
index 9d5ccec5..ea92d6e6 100644
--- a/atr/manager.py
+++ b/atr/manager.py
@@ -26,9 +26,11 @@ import os
import signal
import sys
+import sqlalchemy
import sqlalchemy.engine as engine
import sqlmodel
+import atr.constants as constants
import atr.db as db
import atr.log as log
import atr.models.sql as sql
@@ -48,15 +50,15 @@ class WorkerManager:
def __init__(
self,
min_workers: int = 4,
- max_workers: int = 8,
check_interval_seconds: float = 2.0,
max_task_seconds: float = 300.0,
):
self.min_workers = min_workers
- self.max_workers = max_workers
+ self.max_workers = 2 * min_workers
self.check_interval_seconds = check_interval_seconds
self.max_task_seconds = max_task_seconds
self.workers: dict[int, WorkerProcess] = {}
+ self.budget_index = 0
self.running = False
self.check_task: asyncio.Task | None = None
@@ -137,6 +139,10 @@ class WorkerManager:
python_path = env.get("PYTHONPATH", "")
env["PYTHONPATH"] = f"{project_root}:{python_path}" if python_path else project_root
+ budget = constants.WORKER_TASK_BUDGETS[self.budget_index % len(constants.WORKER_TASK_BUDGETS)]
+ self.budget_index += 1
+ env[constants.WORKER_MAX_TASKS_ENV] = str(budget)
+
# Get absolute path to worker script
worker_script = os.path.join(project_root, "atr", "worker.py")
@@ -168,10 +174,10 @@ class WorkerManager:
preexec_fn=os.setsid,
)
- worker = WorkerProcess(process, datetime.datetime.now(datetime.UTC))
+ worker = WorkerProcess(process, datetime.datetime.now(datetime.UTC), budget)
if worker.pid:
self.workers[worker.pid] = worker
- log.info(f"Started worker process {worker.pid}")
+ log.info(f"Started worker process {worker.pid} with task budget {budget}")
if global_worker_debug and log_file_path:
log.info(f"Worker {worker.pid} logs: {log_file_path}")
else:
@@ -211,6 +217,9 @@ class WorkerManager:
# This also stops tasks if they have indeed been running for too long
if await self.check_task_duration(data, pid, worker):
exited_workers.append(pid)
+ continue
+
+ await self.pre_spawn_replacement(data, pid, worker)
# Remove exited workers
for pid in exited_workers:
@@ -278,6 +287,42 @@ class WorkerManager:
# TODO: Return False here to avoid over-reporting errors
return False
+ async def pre_spawn_replacement(self, data: db.Session, pid: int, worker: WorkerProcess) -> None:
+ if worker.pre_spawned:
+ return
+ via = sql.validate_instrumented_attribute
+ try:
+ active_query = (
+ sqlmodel.select(sqlalchemy.func.count())
+ .select_from(sql.Task)
+ .where(
+ sql.Task.pid == pid,
+ sql.Task.status == sql.TaskStatus.ACTIVE,
+ via(sql.Task.started) >= worker.started,
+ )
+ )
+ active = (await data.execute(active_query)).scalar_one()
+ if not active:
+ return
+ finished_query = (
+ sqlmodel.select(sqlalchemy.func.count())
+ .select_from(sql.Task)
+ .where(
+ sql.Task.pid == pid,
+ via(sql.Task.status).in_([sql.TaskStatus.COMPLETED, sql.TaskStatus.FAILED]),
+ via(sql.Task.started) >= worker.started,
+ )
+ )
+ finished = (await data.execute(finished_query)).scalar_one()
+ except Exception as e:
+ log.error(f"Error counting processed tasks for worker {pid}: {e}")
+ return
+ if finished < (worker.budget - 1):
+ return
+ worker.pre_spawned = True
+ log.info(f"Worker {pid} started the last of its {worker.budget} tasks, spawning a replacement")
+ await self.spawn_worker()
+
async def maintain_worker_pool(self) -> None:
"""Ensure we maintain the minimum number of workers."""
current_count = len(self.workers)
@@ -350,10 +395,12 @@ class WorkerManager:
class WorkerProcess:
"""Interface to control a worker process."""
- def __init__(self, process: asyncio.subprocess.Process, started: datetime.datetime):
+ def __init__(self, process: asyncio.subprocess.Process, started: datetime.datetime, budget: int):
self.process = process
self.started = started
self.last_checked = started
+ self.budget = budget
+ self.pre_spawned = False
@property
def pid(self) -> int | None:
diff --git a/atr/worker.py b/atr/worker.py
index 2c23f9ff..2373767b 100644
--- a/atr/worker.py
+++ b/atr/worker.py
@@ -367,7 +367,7 @@ def _truncate_single_line(text: str | None, max_length: int) -> str:
async def _worker_loop_run() -> None:
"""Main worker loop."""
processed = 0
- max_to_process = 10
+ max_to_process = int(os.environ.get(constants.WORKER_MAX_TASKS_ENV, "10"))
while True:
log.clear_context()
try:
diff --git a/playwright/test.py b/playwright/test.py
index 0831b38d..4bccd6e7 100755
--- a/playwright/test.py
+++ b/playwright/test.py
@@ -388,7 +388,7 @@ def poll_for_tasks_completion(page: Page, project_key: str, version_key: str, re
polling_url = f"{ATR_BASE_URL}/admin/ongoing-tasks/{rev_path}"
logging.info(f"Polling URL: {polling_url}")
- max_wait_seconds = 60
+ max_wait_seconds = 120
poll_interval_seconds = 0.5
start_time = time.monotonic()
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org