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/08/03 14:31:39 UTC

(tooling-trusted-releases) branch sbp updated (2b1566c4 -> c549bd60)

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


    from 2b1566c4 Set worker CPU quota as a new soft limit per task
     add 5b4be6d8 #1481 - show subproject summary on cards
     new c549bd60 Monitor the memory use of a worker process tree in its manager

The 1 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:
 atr/catalog_site.py                     |  74 +++++++++++-----
 atr/docs/resource-management.md         |   4 +-
 atr/manager.py                          |  62 +++++++++++++
 atr/templates/catalog_site/project.html |  26 +++++-
 tests/unit/test_manager_memory.py       | 151 ++++++++++++++++++++++++++++++++
 5 files changed, 290 insertions(+), 27 deletions(-)
 create mode 100644 tests/unit/test_manager_memory.py


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org


(tooling-trusted-releases) 01/01: Monitor the memory use of a worker process tree in its manager

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 c549bd60320285b415183973cdb1d00cf38f6915
Author: Sean B. Palmer <se...@miscoranda.com>
AuthorDate: Mon Aug 3 15:30:40 2026 +0100

    Monitor the memory use of a worker process tree in its manager
---
 atr/docs/resource-management.md   |   4 +-
 atr/manager.py                    |  62 ++++++++++++++++
 tests/unit/test_manager_memory.py | 151 ++++++++++++++++++++++++++++++++++++++
 3 files changed, 216 insertions(+), 1 deletion(-)

diff --git a/atr/docs/resource-management.md b/atr/docs/resource-management.md
index 3e4e1b8f..d16f4ded 100644
--- a/atr/docs/resource-management.md
+++ b/atr/docs/resource-management.md
@@ -27,7 +27,9 @@ The five main places where ATR consumes resources are: 1. the task system, 2. we
 
 ## Worker pool
 
-The manager ([`manager`](/ref/atr/manager.py)) tracks four to eight workers, each of which works on 8 to 16 tasks before exiting. Workers claim the oldest known task. The queue is global: there is no user quota, fairness, etc. Workers arm a soft CPU limit of 300 processor seconds at the start of every task, so the budget is per task rather than per worker lifetime; children inherit the limit, each with its own fresh accounting. The limit is enforced by the kernel as an uncaught SIGXCPU,  [...]
+The manager ([`manager`](/ref/atr/manager.py)) tracks four to eight workers, each of which works on 8 to 16 tasks before exiting. Workers claim the oldest known task. The queue is global: there is no user quota, fairness, etc. Workers arm a soft CPU limit of 300 processor seconds at the start of every task, so the budget is per task rather than per worker lifetime; children inherit the limit, each with its own fresh accounting. The limit is enforced by the kernel as an uncaught SIGXCPU,  [...]
+
+Each worker also runs a watchdog thread, polling every 500ms, which kills the worker's own process group when the resident memory of its process tree exceeds 3 GB. As a second layer, the manager samples each tracked worker's tree on its two second cycle and kills the group of any worker exceeding that limit by 20%. It records a task failure only when the task identified before measurement is still active when the verdict is written, and keeps tracking a worker that survives the kill to r [...]
 
 After 300s spent on a task, the manager fails it and SIGTERMs the worker. It does not confirm the effect, and does not send the SIGTERM to the worker's children. The manager drops the worker, replacing only when there are fewer than four, so four to eight is the tracked pool, not a cap on live processes: a worker that hasn't acted on its SIGTERM runs on beside the pool, may overwrite its failed verdict if it finishes, and may run another task twice via the untracked reset.
 
diff --git a/atr/manager.py b/atr/manager.py
index 0c6c8b29..80a7826d 100644
--- a/atr/manager.py
+++ b/atr/manager.py
@@ -25,7 +25,9 @@ import io
 import os
 import signal
 import sys
+from typing import Final
 
+import psutil
 import sqlalchemy
 import sqlalchemy.engine as engine
 import sqlmodel
@@ -40,6 +42,10 @@ import atr.util as util
 # Global debug flag to control worker process output capturing
 global_worker_debug: bool = False
 
+_KILL_WAIT_SECONDS: Final = 5.0
+
+_MEMORY_TERMINATE_LIMIT_BYTES: Final[int] = (constants.WORKER_MEMORY_LIMIT_BYTES * 6) // 5
+
 # Global worker manager instance
 # Can't use "StringClass" | None, must use Optional["StringClass"] for forward references
 global_worker_manager: WorkerManager | None = None
@@ -214,6 +220,10 @@ class WorkerManager:
                     log.info(f"Worker {pid} has exited")
                     continue
 
+                if await self.check_worker_memory(data, pid, worker):
+                    exited_workers.append(pid)
+                    continue
+
                 # Check if worker has been processing its task for too long
                 # This also stops tasks if they have indeed been running for too long
                 if await self.check_task_duration(data, pid, worker):
@@ -297,6 +307,40 @@ class WorkerManager:
             return False
         return await self.terminate_long_running_task(active_task, worker, active_task.id, pid, limit)
 
+    async def check_worker_memory(self, data: db.Session, pid: int, worker: WorkerProcess) -> bool:
+        active_task = None
+        try:
+            async with data.begin():
+                active_task = await data.task(pid=pid, status=sql.TaskStatus.ACTIVE).get()
+        except Exception as e:
+            log.error(f"Error checking active task for worker {pid}: {e}")
+        try:
+            rss = await asyncio.to_thread(_worker_tree_rss, pid)
+        except Exception as e:
+            log.error(f"Error sampling memory of worker {pid}: {e}")
+            return False
+        if rss <= _MEMORY_TERMINATE_LIMIT_BYTES:
+            return False
+        log.error(f"Worker {pid} process tree uses {rss} bytes of resident memory, terminating")
+        if active_task is not None:
+            status = task.BROKEN if (active_task.task_type in task.CHECK_TASK_TYPES) else task.FAILED
+            error = f"Task terminated because its worker used {rss} bytes of resident memory"
+            if not await task.finalise_failure(active_task.id, pid, error, status):
+                log.info(f"Task {active_task.id} was already finalised, killing worker {pid} without a verdict")
+        try:
+            os.killpg(pid, signal.SIGKILL)
+        except ProcessLookupError:
+            return True
+        try:
+            await asyncio.wait_for(worker.process.wait(), timeout=_KILL_WAIT_SECONDS)
+        except TimeoutError:
+            log.error(f"Worker {pid} did not exit after SIGKILL, keeping it tracked to retry")
+            return False
+        live_members = await asyncio.to_thread(_live_process_group_members, pid)
+        if live_members:
+            log.error(f"Worker {pid} exited after SIGKILL but its process group has live members: {live_members}")
+        return True
+
     async def pre_spawn_replacement(self, data: db.Session, pid: int, worker: WorkerProcess) -> None:
         if worker.pre_spawned:
             return
@@ -405,6 +449,24 @@ class WorkerManager:
             log.error(f"Error resetting broken tasks: {e}")
 
 
+def _live_process_group_members(pgid: int) -> list[int]:
+    members = []
+    for process in psutil.process_iter():
+        try:
+            if (os.getpgid(process.pid) == pgid) and (process.status() != psutil.STATUS_ZOMBIE):
+                members.append(process.pid)
+        except (OSError, psutil.Error):
+            continue
+    return members
+
+
+def _worker_tree_rss(pid: int) -> int:
+    try:
+        return util.process_tree_rss(psutil.Process(pid))
+    except psutil.NoSuchProcess:
+        return 0
+
+
 class WorkerProcess:
     """Interface to control a worker process."""
 
diff --git a/tests/unit/test_manager_memory.py b/tests/unit/test_manager_memory.py
new file mode 100644
index 00000000..12ba9267
--- /dev/null
+++ b/tests/unit/test_manager_memory.py
@@ -0,0 +1,151 @@
+# 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 asyncio
+import types
+import unittest.mock as mock
+
+import pytest
+
+import atr.manager as manager
+import atr.models.sql as sql
+
+
+class Begin:
+    async def __aenter__(self) -> None:
+        return None
+
+    async def __aexit__(self, *args: object) -> bool:
+        return False
+
+
+def test_live_process_group_members_excludes_zombies(monkeypatch: pytest.MonkeyPatch) -> None:
+    live = types.SimpleNamespace(pid=1000, status=mock.Mock(return_value=manager.psutil.STATUS_RUNNING))
+    zombie = types.SimpleNamespace(pid=1001, status=mock.Mock(return_value=manager.psutil.STATUS_ZOMBIE))
+    outside = types.SimpleNamespace(pid=1002, status=mock.Mock(return_value=manager.psutil.STATUS_RUNNING))
+    monkeypatch.setattr(manager.psutil, "process_iter", lambda: [live, zombie, outside])
+    monkeypatch.setattr(manager.os, "getpgid", lambda pid: 999 if (pid != 1002) else 1002)
+
+    assert manager._live_process_group_members(999) == [1000]
+
+
+async def test_memory_check_ignores_worker_under_limit(monkeypatch: pytest.MonkeyPatch) -> None:
+    monkeypatch.setattr(manager, "_worker_tree_rss", lambda pid: 1024)
+    killpg = mock.Mock()
+    monkeypatch.setattr("os.killpg", killpg)
+    worker_process = _worker_process()
+
+    terminated = await manager.WorkerManager().check_worker_memory(_data(None), 999, worker_process)
+
+    assert terminated is False
+    killpg.assert_not_called()
+
+
+async def test_memory_check_keeps_watching_unkillable_worker(monkeypatch: pytest.MonkeyPatch) -> None:
+    monkeypatch.setattr(manager, "_worker_tree_rss", lambda pid: manager._MEMORY_TERMINATE_LIMIT_BYTES + 1)
+    monkeypatch.setattr(manager, "_KILL_WAIT_SECONDS", 0.01)
+    killpg = mock.Mock()
+    monkeypatch.setattr("os.killpg", killpg)
+
+    async def hanging_wait() -> int:
+        await asyncio.sleep(60)
+        return 0
+
+    worker_process = types.SimpleNamespace(pid=999, process=types.SimpleNamespace(wait=hanging_wait))
+
+    terminated = await manager.WorkerManager().check_worker_memory(_data(None), 999, worker_process)
+
+    assert terminated is False
+    killpg.assert_called_once()
+
+
+async def test_memory_check_kills_without_verdict_when_task_already_finalised(
+    monkeypatch: pytest.MonkeyPatch,
+) -> None:
+    monkeypatch.setattr(manager, "_worker_tree_rss", lambda pid: manager._MEMORY_TERMINATE_LIMIT_BYTES + 1)
+    finalise = mock.AsyncMock(return_value=False)
+    monkeypatch.setattr("atr.tasks.task.finalise_failure", finalise)
+    killpg = mock.Mock()
+    monkeypatch.setattr("os.killpg", killpg)
+    worker_process = _worker_process()
+
+    terminated = await manager.WorkerManager().check_worker_memory(_data(_active_task()), 999, worker_process)
+
+    assert terminated is True
+    finalise.assert_awaited_once()
+    killpg.assert_called_once()
+
+
+async def test_memory_check_logs_live_group_members_after_worker_exits(monkeypatch: pytest.MonkeyPatch) -> None:
+    monkeypatch.setattr(manager, "_worker_tree_rss", lambda pid: manager._MEMORY_TERMINATE_LIMIT_BYTES + 1)
+    monkeypatch.setattr(manager, "_live_process_group_members", lambda pgid: [1000, 1001])
+    killpg = mock.Mock()
+    monkeypatch.setattr("os.killpg", killpg)
+    log_error = mock.Mock()
+    monkeypatch.setattr(manager.log, "error", log_error)
+    worker_process = _worker_process()
+
+    terminated = await manager.WorkerManager().check_worker_memory(_data(None), 999, worker_process)
+
+    assert terminated is True
+    log_error.assert_any_call("Worker 999 exited after SIGKILL but its process group has live members: [1000, 1001]")
+
+
+async def test_memory_check_terminates_idle_worker_over_limit(monkeypatch: pytest.MonkeyPatch) -> None:
+    monkeypatch.setattr(manager, "_worker_tree_rss", lambda pid: manager._MEMORY_TERMINATE_LIMIT_BYTES + 1)
+    finalise = mock.AsyncMock(return_value=True)
+    monkeypatch.setattr("atr.tasks.task.finalise_failure", finalise)
+    killpg = mock.Mock()
+    monkeypatch.setattr("os.killpg", killpg)
+    worker_process = _worker_process()
+
+    terminated = await manager.WorkerManager().check_worker_memory(_data(None), 999, worker_process)
+
+    assert terminated is True
+    finalise.assert_not_awaited()
+    killpg.assert_called_once()
+
+
+async def test_memory_check_terminates_worker_over_limit(monkeypatch: pytest.MonkeyPatch) -> None:
+    monkeypatch.setattr(manager, "_worker_tree_rss", lambda pid: manager._MEMORY_TERMINATE_LIMIT_BYTES + 1)
+    finalise = mock.AsyncMock(return_value=True)
+    monkeypatch.setattr("atr.tasks.task.finalise_failure", finalise)
+    killpg = mock.Mock()
+    monkeypatch.setattr("os.killpg", killpg)
+    worker_process = _worker_process()
+
+    terminated = await manager.WorkerManager().check_worker_memory(_data(_active_task()), 999, worker_process)
+
+    assert terminated is True
+    finalise.assert_awaited_once()
+    killpg.assert_called_once()
+    worker_process.process.wait.assert_awaited_once()
+
+
+def _active_task() -> sql.Task:
+    return sql.Task(
+        id=7, status=sql.TaskStatus.ACTIVE, task_type=sql.TaskType.COMPARE_SOURCE_TREES, task_args={}, asf_uid="alice"
+    )
+
+
+def _data(active_task: sql.Task | None) -> types.SimpleNamespace:
+    query = types.SimpleNamespace(get=mock.AsyncMock(return_value=active_task))
+    return types.SimpleNamespace(begin=lambda: Begin(), task=lambda **kwargs: query)
+
+
+def _worker_process() -> types.SimpleNamespace:
+    return types.SimpleNamespace(pid=999, process=types.SimpleNamespace(wait=mock.AsyncMock(return_value=-9)))


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org