You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tooling.apache.org by ar...@apache.org on 2026/07/22 11:23:39 UTC

(tooling-trusted-releases) branch arm updated: #1404 - move completed scheduled tasks to file logging and remove from database

This is an automated email from the ASF dual-hosted git repository.

alitheg pushed a commit to branch arm
in repository https://gitbox.apache.org/repos/asf/tooling-trusted-releases.git


The following commit(s) were added to refs/heads/arm by this push:
     new f67fc10f #1404 - move completed scheduled tasks to file logging and remove from database
f67fc10f is described below

commit f67fc10f918d62b8d24207150469dd404d9dfd0e
Author: Alastair McFarlane <ar...@apache.org>
AuthorDate: Wed Jul 22 12:23:03 2026 +0100

    #1404 - move completed scheduled tasks to file logging and remove from database
---
 atr/admin/__init__.py                   |   2 +-
 atr/config.py                           |   2 +
 atr/loggers.py                          |   2 +-
 atr/models/sql.py                       |  12 +++
 atr/tasks/__init__.py                   |   9 +-
 atr/worker.py                           |  81 ++++++++++++----
 scripts/purge_recurring_task_history.py | 167 ++++++++++++++++++++++++++++++++
 7 files changed, 245 insertions(+), 30 deletions(-)

diff --git a/atr/admin/__init__.py b/atr/admin/__init__.py
index 2970c675..8254fbd7 100644
--- a/atr/admin/__init__.py
+++ b/atr/admin/__init__.py
@@ -1915,7 +1915,7 @@ async def tasks_recent(_session: web.Committer, _tasks_recent: Literal["tasks/re
     page.h2["Scheduled tasks"]
     page.p[f"Found {util.plural(len(scheduled_tasks), 'task')}"]
 
-    if recent_tasks:
+    if scheduled_tasks:
         table = htm.Block(htpy.table, classes=".table.table-sm")
         table.thead(".table-dark")[
             htpy.tr[
diff --git a/atr/config.py b/atr/config.py
index ad509544..6a6ba8b9 100644
--- a/atr/config.py
+++ b/atr/config.py
@@ -127,6 +127,7 @@ class AppConfig:
     PERFORMANCE_LOG_FILE = os.path.join(STATE_DIR, "logs", "route-performance.log")
     REQUEST_LOG_FILE = os.path.join(STATE_DIR, "logs", "requests.log")
     RESOURCES_LOG_FILE = os.path.join(STATE_DIR, "logs", "resources.log")
+    TASK_LOG_FILE = os.path.join(STATE_DIR, "logs", "tasks.log")
 
     # Apache RAT configuration
     APACHE_RAT_JAR_PATH = decouple.config("APACHE_RAT_JAR_PATH", default=f"/opt/tools/apache-rat-{_RAT_VERSION}.jar")
@@ -267,6 +268,7 @@ def validate() -> None:
         (conf.AUTH_AUDIT_LOG_FILE, "AUTH_AUDIT_LOG_FILE"),
         (conf.PERFORMANCE_LOG_FILE, "PERFORMANCE_LOG_FILE"),
         (conf.RESOURCES_LOG_FILE, "RESOURCES_LOG_FILE"),
+        (conf.TASK_LOG_FILE, "TASK_LOG_FILE"),
     ]
     relative_paths = [
         (conf.SQLITE_DB_PATH, "SQLITE_DB_PATH"),
diff --git a/atr/loggers.py b/atr/loggers.py
index 071c44c7..90f4f78d 100644
--- a/atr/loggers.py
+++ b/atr/loggers.py
@@ -108,7 +108,7 @@ def _parse_json_event(
     _method_name: str,
     event_dict: structlog.types.EventDict,
 ) -> structlog.types.EventDict:
-    if event_dict.get("logger") not in ["atr.auth", "atr.storage.audit"]:
+    if event_dict.get("logger") not in ["atr.auth", "atr.storage.audit", "atr.tasks.log"]:
         return event_dict
     event = event_dict.get("event")
     if isinstance(event, str) and event.startswith("{"):
diff --git a/atr/models/sql.py b/atr/models/sql.py
index 4921fd28..fe63bab2 100644
--- a/atr/models/sql.py
+++ b/atr/models/sql.py
@@ -340,6 +340,18 @@ class TaskType(enum.StrEnum):
                 assert_never(self)
 
 
+# The recurring tasks reschedule themselves and carry no lasting per-run value,
+# so on success they are logged to a file and dropped rather than kept in the table
+RECURRING_TASK_TYPES: Final[frozenset[TaskType]] = frozenset(
+    {
+        TaskType.DISTRIBUTION_STATUS,
+        TaskType.MAINTENANCE,
+        TaskType.METADATA_UPDATE,
+        TaskType.WORKFLOW_STATUS,
+    }
+)
+
+
 class UserRole(enum.StrEnum):
     COMMITTEE_MEMBER = "committee_member"
     RELEASE_MANAGER = "release_manager"
diff --git a/atr/tasks/__init__.py b/atr/tasks/__init__.py
index 56b1a1a1..b8b1bd21 100644
--- a/atr/tasks/__init__.py
+++ b/atr/tasks/__init__.py
@@ -128,14 +128,7 @@ async def clear_scheduled(caller_data: db.Session | None = None) -> None:
         via = sql.validate_instrumented_attribute
 
         delete_stmt = sqlmodel.delete(sql.Task).where(
-            via(sql.Task.task_type).in_(
-                [
-                    sql.TaskType.MAINTENANCE,
-                    sql.TaskType.METADATA_UPDATE,
-                    sql.TaskType.WORKFLOW_STATUS,
-                    sql.TaskType.DISTRIBUTION_STATUS,
-                ]
-            ),
+            via(sql.Task.task_type).in_(sql.RECURRING_TASK_TYPES),
             via(sql.Task.status) == sql.TaskStatus.QUEUED,
             via(sql.Task.scheduled).is_not(None),
         )
diff --git a/atr/worker.py b/atr/worker.py
index 23ae8972..3da1e76c 100644
--- a/atr/worker.py
+++ b/atr/worker.py
@@ -25,6 +25,8 @@
 import asyncio
 import datetime
 import inspect
+import json
+import logging
 import os
 import resource
 import signal
@@ -55,6 +57,9 @@ _MEMORY_LIMIT_BYTES: Final = 3 * 1024 * 1024 * 1024
 # The ru_maxrss unit is bytes on macOS, and kilobytes on Linux
 _MAXRSS_KILOBYTES_DIVISOR: Final = 1024 if (sys.platform == "darwin") else 1
 
+# Successful recurring tasks are appended here as JSON lines instead of kept in the database
+_TASK_LOG_LOGGER: Final = "atr.tasks.log"
+
 # # Create tables if they don't exist
 # SQLModel.metadata.create_all(engine)
 
@@ -176,8 +181,6 @@ async def _notify_task_failure(
 
 
 def _setup_logging() -> None:
-    import logging
-
     import atr.config as config
     import atr.loggers as loggers
 
@@ -185,6 +188,7 @@ def _setup_logging() -> None:
 
     os.makedirs("logs", exist_ok=True)
     os.makedirs(os.path.dirname(conf.STORAGE_AUDIT_LOG_FILE), exist_ok=True)
+    os.makedirs(os.path.dirname(conf.TASK_LOG_FILE), exist_ok=True)
 
     shared_processors = loggers.shared_processors()
     output_handler = logging.FileHandler("logs/atr-worker.log")
@@ -201,6 +205,34 @@ def _setup_logging() -> None:
         shared_processors,
     )
 
+    # Completed recurring tasks
+    loggers.setup_dedicated_file_logger(
+        _TASK_LOG_LOGGER,
+        conf.TASK_LOG_FILE,
+        shared_processors,
+    )
+
+
+def _task_completed_log(record: dict[str, Any]) -> None:
+    logging.getLogger(_TASK_LOG_LOGGER).info(json.dumps(record, allow_nan=False))
+
+
+def _task_completed_record(
+    task_obj: sql.Task, result: results.Results | None, completed: datetime.datetime
+) -> dict[str, Any]:
+    return {
+        "id": task_obj.id,
+        "task_type": task_obj.task_type.value,
+        "status": task.COMPLETED.value,
+        "asf_uid": task_obj.asf_uid,
+        "added": task_obj.added.isoformat() if task_obj.added else None,
+        "started": task_obj.started.isoformat() if task_obj.started else None,
+        "completed": completed.isoformat(),
+        "task_args": task_obj.task_args,
+        "result": result.model_dump(mode="json") if (result is not None) else None,
+        "pid": task_obj.pid,
+    }
+
 
 def _task_failure_message(
     task_type: sql.TaskType,
@@ -365,29 +397,38 @@ async def _task_result_process(
 ) -> None:
     """Process and store task results in the database."""
     notify_args: tuple[str | None, sql.TaskType, str | None, str | None, str | None, str | None, str] | None = None
+    log_record: dict[str, Any] | None = None
+    completed = datetime.datetime.now(datetime.UTC)
     async with db.session() as data:
         async with data.begin():
             # Find the task by ID
             task_obj = await data.task(id=task_id).get()
             if task_obj:
-                # Update task properties
-                task_obj.status = status
-                task_obj.completed = datetime.datetime.now(datetime.UTC)
-                task_obj.result = task_results
-
-                if status == task.FAILED:
-                    normalised_error = ((error or "").strip()) or "unknown error"
-                    task_obj.error = normalised_error
-                    notify_args = (
-                        task_obj.asf_uid,
-                        task_obj.task_type,
-                        task_obj.project_key,
-                        task_obj.version_key,
-                        task_obj.revision_number,
-                        task_obj.primary_rel_path,
-                        normalised_error,
-                    )
-
+                if (status == task.COMPLETED) and (task_obj.task_type in sql.RECURRING_TASK_TYPES):
+                    # A successful recurring run leaves only a log line behind
+                    log_record = _task_completed_record(task_obj, task_results, completed)
+                    await data.delete(task_obj)
+                else:
+                    # Update task properties
+                    task_obj.status = status
+                    task_obj.completed = completed
+                    task_obj.result = task_results
+
+                    if status == task.FAILED:
+                        normalised_error = ((error or "").strip()) or "unknown error"
+                        task_obj.error = normalised_error
+                        notify_args = (
+                            task_obj.asf_uid,
+                            task_obj.task_type,
+                            task_obj.project_key,
+                            task_obj.version_key,
+                            task_obj.revision_number,
+                            task_obj.primary_rel_path,
+                            normalised_error,
+                        )
+
+    if log_record is not None:
+        _task_completed_log(log_record)
     if notify_args is not None:
         await _notify_task_failure(*notify_args)
 
diff --git a/scripts/purge_recurring_task_history.py b/scripts/purge_recurring_task_history.py
new file mode 100644
index 00000000..1d11f709
--- /dev/null
+++ b/scripts/purge_recurring_task_history.py
@@ -0,0 +1,167 @@
+# 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.
+
+"""
+Drop the completed recurring-task rows that predate the log-and-delete change.
+
+From #1404 onwards a recurring task logs a line and deletes itself on success, so
+only the historical backlog needs a one-off sweep. This deletes the completed rows
+for the four recurring types and VACUUMs to hand the freed pages back to the OS.
+Failed rows stay put - their errors are the reason we keep them.
+
+    PYTHONPATH=. uv run python3 scripts/purge_recurring_task_history.py            # dry run
+    PYTHONPATH=. uv run python3 scripts/purge_recurring_task_history.py --apply
+    PYTHONPATH=. uv run python3 scripts/purge_recurring_task_history.py --apply --log-first
+    PYTHONPATH=. uv run python3 scripts/purge_recurring_task_history.py --db /var/opt/atr-staging/database/atr.db
+
+The SQLAlchemy enum column stores the member name, so task_type/status are the
+uppercase names here, not their lowercase values.
+"""
+
+import argparse
+import json
+import sqlite3
+import sys
+from typing import Final
+
+# Mirrors sql.RECURRING_TASK_TYPES, as member names (how the column stores them)
+_RECURRING_NAMES: Final[tuple[str, ...]] = (
+    "DISTRIBUTION_STATUS",
+    "MAINTENANCE",
+    "METADATA_UPDATE",
+    "WORKFLOW_STATUS",
+)
+
+
+def main() -> None:
+    args = _parse_args()
+    connection = sqlite3.connect(args.db)
+    connection.isolation_level = None
+    connection.execute("PRAGMA foreign_keys=ON")
+    connection.execute("PRAGMA busy_timeout=5000")
+    try:
+        _purge(connection, apply=args.apply, log_first=args.log_first, log_file=args.log_file)
+    finally:
+        connection.close()
+
+
+def _purge(connection: sqlite3.Connection, apply: bool, log_first: bool, log_file: str) -> None:
+    counts = _counts(connection)
+    total = sum(counts.values())
+    for name in _RECURRING_NAMES:
+        print(f"  {name}: {counts.get(name, 0)} completed rows")
+    if total == 0:
+        print("Nothing to purge.")
+        return
+    if not apply:
+        print(f"Would delete {total} completed recurring rows. Re-run with --apply.")
+        return
+
+    if log_first:
+        written = _log_rows(connection, log_file)
+        print(f"Logged {written} rows to {log_file}")
+
+    pages_before = _page_count(connection)
+    deleted = _delete(connection)
+    connection.execute("VACUUM")
+    pages_after = _page_count(connection)
+    reclaimed = (pages_before - pages_after) * _page_size(connection)
+    print(f"Deleted {deleted} rows; VACUUM reclaimed {reclaimed / (1024 * 1024):.1f} MiB.")
+
+
+def _counts(connection: sqlite3.Connection) -> dict[str, int]:
+    placeholders = ", ".join("?" for _ in _RECURRING_NAMES)
+    rows = connection.execute(
+        f"SELECT task_type, COUNT(*) FROM task"
+        f" WHERE status = 'COMPLETED' AND task_type IN ({placeholders})"
+        f" GROUP BY task_type",
+        _RECURRING_NAMES,
+    ).fetchall()
+    return {row[0]: row[1] for row in rows}
+
+
+def _delete(connection: sqlite3.Connection) -> int:
+    placeholders = ", ".join("?" for _ in _RECURRING_NAMES)
+    connection.execute("BEGIN IMMEDIATE")
+    try:
+        cursor = connection.execute(
+            f"DELETE FROM task WHERE status = 'COMPLETED' AND task_type IN ({placeholders})",
+            _RECURRING_NAMES,
+        )
+        deleted = cursor.rowcount
+        connection.execute("COMMIT")
+    except Exception:
+        connection.execute("ROLLBACK")
+        raise
+    return deleted
+
+
+def _log_rows(connection: sqlite3.Connection, log_file: str) -> int:
+    placeholders = ", ".join("?" for _ in _RECURRING_NAMES)
+    rows = connection.execute(
+        f"SELECT id, task_type, asf_uid, added, started, completed, task_args, result, pid FROM task"
+        f" WHERE status = 'COMPLETED' AND task_type IN ({placeholders})",
+        _RECURRING_NAMES,
+    ).fetchall()
+    written = 0
+    with open(log_file, "a", encoding="utf-8") as handle:
+        for row in rows:
+            record = {
+                "id": row[0],
+                "task_type": row[1],
+                "status": "COMPLETED",
+                "asf_uid": row[2],
+                "added": row[3],
+                "started": row[4],
+                "completed": row[5],
+                "task_args": _maybe_json(row[6]),
+                "result": _maybe_json(row[7]),
+                "pid": row[8],
+            }
+            handle.write(json.dumps(record, allow_nan=False) + "\n")
+            written += 1
+    return written
+
+
+def _maybe_json(value: str | None) -> object:
+    if value is None:
+        return None
+    try:
+        return json.loads(value)
+    except (json.JSONDecodeError, TypeError):
+        return value
+
+
+def _page_count(connection: sqlite3.Connection) -> int:
+    return int(connection.execute("PRAGMA page_count").fetchone()[0])
+
+
+def _page_size(connection: sqlite3.Connection) -> int:
+    return int(connection.execute("PRAGMA page_size").fetchone()[0])
+
+
+def _parse_args() -> argparse.Namespace:
+    parser = argparse.ArgumentParser(description="Purge historical completed recurring-task rows.")
+    parser.add_argument("--db", default="state/database/atr.db", help="Path to the SQLite database.")
+    parser.add_argument("--apply", action="store_true", help="Delete the rows and VACUUM; otherwise only count.")
+    parser.add_argument("--log-first", action="store_true", help="Append the rows as JSON lines before deleting.")
+    parser.add_argument("--log-file", default="state/logs/tasks.log", help="Destination for --log-first.")
+    return parser.parse_args()
+
+
+if __name__ == "__main__":
+    sys.exit(main())


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