From 8aabec73b302131f86780cf0738b247bd851f4eb Mon Sep 17 00:00:00 2001 From: mightqxc Date: Thu, 26 Nov 2026 00:59:00 +0100 Subject: [PATCH 1/6] data carousel: enhance logging and return values in data carousel cleanup --- pandaserver/taskbuffer/DataCarousel.py | 18 ++++--- .../db_proxy_mods/data_carousel_module.py | 49 ++++++++++++++++--- 2 files changed, 52 insertions(+), 15 deletions(-) diff --git a/pandaserver/taskbuffer/DataCarousel.py b/pandaserver/taskbuffer/DataCarousel.py index ae7959907..c4c137778 100644 --- a/pandaserver/taskbuffer/DataCarousel.py +++ b/pandaserver/taskbuffer/DataCarousel.py @@ -3289,29 +3289,33 @@ def clean_up_requests( if n_deleted is None: tmp_log.warning("failed to delete done requests; skipped") else: - tmp_log.debug(f"deleted {n_deleted} done requests older than {done_age_limit_days} days or rule_unfound or remove_when_done") + tmp_log.debug( + f"deleted {n_deleted} done requests older than {done_age_limit_days} days or rule_unfound or remove_when_done: {sorted(done_requests_set)}" + ) if cancelled_requests_set: # cancelled requests n_deleted = self.taskBufferIF.delete_data_carousel_requests_JEDI(list(cancelled_requests_set)) if n_deleted is None: tmp_log.warning("failed to delete cancelled requests; skipped") else: - tmp_log.debug(f"deleted {n_deleted} cancelled requests") + tmp_log.debug(f"deleted {n_deleted} cancelled requests: {sorted(cancelled_requests_set)}") if retired_requests_set: # retired requests n_deleted = self.taskBufferIF.delete_data_carousel_requests_JEDI(list(retired_requests_set)) if n_deleted is None: tmp_log.warning("failed to delete retired requests; skipped") else: - tmp_log.debug(f"deleted {n_deleted} retired requests") + tmp_log.debug(f"deleted {n_deleted} retired requests: {sorted(retired_requests_set)}") else: tmp_log.debug("no terminated requests to delete; skipped") - # clean up outdated requests - ret_outdated = self.taskBufferIF.clean_up_data_carousel_requests_JEDI(time_limit_days=outdated_age_limit_days) - if ret_outdated is None: + # clean up outdated requests not related to any active task + outdated_request_ids = self.taskBufferIF.clean_up_data_carousel_requests_JEDI(time_limit_days=outdated_age_limit_days) + if outdated_request_ids is None: tmp_log.warning("failed to delete outdated requests; skipped") else: - tmp_log.debug(f"deleted {ret_outdated} outdated requests older than {outdated_age_limit_days} days") + tmp_log.debug( + f"deleted {len(outdated_request_ids)} outdated requests older than {outdated_age_limit_days} days and without active tasks: {outdated_request_ids}" + ) except Exception: tmp_log.error(f"got error ; {traceback.format_exc()}") diff --git a/pandaserver/taskbuffer/db_proxy_mods/data_carousel_module.py b/pandaserver/taskbuffer/db_proxy_mods/data_carousel_module.py index 891242faa..c37de622c 100644 --- a/pandaserver/taskbuffer/db_proxy_mods/data_carousel_module.py +++ b/pandaserver/taskbuffer/db_proxy_mods/data_carousel_module.py @@ -6,6 +6,7 @@ from pandaserver.config import panda_config from pandaserver.taskbuffer.DataCarousel import ( + FINAL_TASK_STATUSES, DataCarouselRequestSpec, DataCarouselRequestStatus, get_resubmit_request_spec, @@ -466,23 +467,53 @@ def delete_data_carousel_requests_JEDI(self, request_id_list: list[int]) -> int return None # clean up data carousel requests - def clean_up_data_carousel_requests_JEDI(self, time_limit_days: float = 30) -> int | None: + def clean_up_data_carousel_requests_JEDI(self, time_limit_days: float = 30) -> list[int] | None: + """ + Delete terminated requests which ended longer than time_limit_days ago and are not related to any active task + + Args: + time_limit_days (float): age limit in days since end_time of the request + + Returns: + list[int] | None : request IDs of the deleted requests, or None if failed + """ comment = " /* JediDBProxy.clean_up_data_carousel_requests_JEDI */" tmp_log = self.create_tagged_logger(comment) tmp_log.debug("start") try: # start transaction self.conn.begin() - # sql to delete terminated requests now_time = naive_utcnow() status_var_names_str, status_var_map = get_sql_IN_bind_variables(DataCarouselRequestStatus.final_statuses, prefix=":status") - sql_delete_req = ( - f"DELETE FROM {panda_config.schemaJEDI}.data_carousel_requests WHERE status IN ({status_var_names_str}) AND end_time<=:end_time_max " + task_status_var_names_str, task_status_var_map = get_sql_IN_bind_variables(FINAL_TASK_STATUSES, prefix=":task_status") + # condition that the request is not related to any active task + sql_no_active_task = ( + f"NOT EXISTS (SELECT 1 FROM {panda_config.schemaJEDI}.data_carousel_relations rel, {panda_config.schemaJEDI}.JEDI_Tasks t " + f"WHERE rel.request_id=req.request_id AND rel.task_id=t.jediTaskID AND t.status NOT IN ({task_status_var_names_str})) " + ) + # sql to query terminated requests old enough and without active tasks + sql_query_req = ( + f"SELECT req.request_id FROM {panda_config.schemaJEDI}.data_carousel_requests req " + f"WHERE req.status IN ({status_var_names_str}) AND req.end_time<=:end_time_max AND {sql_no_active_task}" ) var_map = {":end_time_max": now_time - datetime.timedelta(days=time_limit_days)} var_map.update(status_var_map) - self.cur.execute(sql_delete_req + comment, var_map) - ret_req: int = self.cur.rowcount + var_map.update(task_status_var_map) + self.cur.execute(sql_query_req + comment, var_map) + res = self.cur.fetchall() + # sql to delete a request; check conditions again in case it got related to an active task in the meantime + sql_delete_req = ( + f"DELETE FROM {panda_config.schemaJEDI}.data_carousel_requests req " + f"WHERE req.request_id=:request_id AND req.status IN ({status_var_names_str}) AND {sql_no_active_task}" + ) + deleted_request_ids = [] + for (request_id,) in res: + var_map = {":request_id": request_id} + var_map.update(status_var_map) + var_map.update(task_status_var_map) + self.cur.execute(sql_delete_req + comment, var_map) + if self.cur.rowcount: + deleted_request_ids.append(request_id) # sql to delete relations sql_delete_rel = ( f"DELETE FROM {panda_config.schemaJEDI}.data_carousel_relations rel " @@ -495,8 +526,10 @@ def clean_up_data_carousel_requests_JEDI(self, time_limit_days: float = 30) -> i if not self._commit(): raise RuntimeError("Commit error") # return - tmp_log.debug(f"cleaned up {ret_req} requests and {ret_rel} relations older than {time_limit_days} days") - return ret_req + tmp_log.debug( + f"cleaned up {len(deleted_request_ids)} requests and {ret_rel} relations older than {time_limit_days} days and without active tasks: {deleted_request_ids}" + ) + return deleted_request_ids except Exception: # roll back self._rollback() From 08d5013799ffab8228b2889b3bd92c487109d8a5 Mon Sep 17 00:00:00 2001 From: mightqxc Date: Thu, 26 Nov 2026 12:05:49 +0100 Subject: [PATCH 2/6] data carousel: add grace period of cleanup by last_used_time --- .../jedidog/AtlasDataCarouselWatchDog.py | 24 ++ pandaserver/taskbuffer/DataCarousel.py | 220 ++++++++++++++++-- .../db_proxy_mods/data_carousel_module.py | 81 +++++-- 3 files changed, 288 insertions(+), 37 deletions(-) diff --git a/pandajedi/jedidog/AtlasDataCarouselWatchDog.py b/pandajedi/jedidog/AtlasDataCarouselWatchDog.py index 9cd39d618..19663e386 100644 --- a/pandajedi/jedidog/AtlasDataCarouselWatchDog.py +++ b/pandajedi/jedidog/AtlasDataCarouselWatchDog.py @@ -26,6 +26,7 @@ StageDCRequests_LOCK_TIME_MINUTES = 5 CheckDCRequests_LOCK_TIME_MINUTES = 5 KeepRulesAlive_LOCK_TIME_MINUTES = 60 +UpdateRequestsUsage_LOCK_TIME_MINUTES = 60 CleanDCRequests_LOCK_TIME_MINUTES = 1440 RescuePendingTasks_LOCK_TIME_MINUTES = 120 @@ -123,6 +124,27 @@ def doKeepRulesAlive(self) -> None: errtype, errvalue = sys.exc_info()[:2] tmpLog.error(f"failed with {errtype} {errvalue} {traceback.format_exc()}") + def doUpdateRequestsUsage(self) -> None: + """ + Action to update the usage of DC requests (remove_when_done and last_used_time) according to their related tasks + """ + tmpLog = MsgWrapper(logger, " #ATM #KV doUpdateRequestsUsage") + tmpLog.debug("start") + try: + # watchdog lock + got_lock = self.get_process_lock("AtlasDataCarousDog.doUpdateReqUsage", timeLimit=UpdateRequestsUsage_LOCK_TIME_MINUTES) + if not got_lock: + tmpLog.debug("locked by another watchdog process. Skipped") + return + tmpLog.debug("got watchdog lock") + # update usage of requests + self.data_carousel_interface.update_requests_usage() + # done + tmpLog.debug("done") + except Exception: + errtype, errvalue = sys.exc_info()[:2] + tmpLog.error(f"failed with {errtype} {errvalue} {traceback.format_exc()}") + def doCleanDCRequests(self) -> None: """ Action to clean up old DC requests in DB table @@ -171,6 +193,8 @@ def doAction(self) -> Interaction.StatusCode: # get logger origTmpLog = MsgWrapper(logger) origTmpLog.debug("start") + # update usage of DC requests before cleaning them up + self.doUpdateRequestsUsage() # clean up old DC requests self.doCleanDCRequests() # keep staging rules alive diff --git a/pandaserver/taskbuffer/DataCarousel.py b/pandaserver/taskbuffer/DataCarousel.py index c4c137778..ea7e72b69 100644 --- a/pandaserver/taskbuffer/DataCarousel.py +++ b/pandaserver/taskbuffer/DataCarousel.py @@ -85,6 +85,12 @@ STAGING_LIFETIME_DAYS = 15 DONE_LIFETIME_DAYS = 30 +# default grace period in days to keep a done request (and its DDM rule) after the last related task ended; overridden by config LAST_USED_GRACE_DAYS +DEFAULT_LAST_USED_GRACE_DAYS = 15 + +# margin in days of DDM rule lifetime beyond the grace period after last used, to cover the interval of clean-up (once a day by watchdog) +LAST_USED_GRACE_RULE_MARGIN_DAYS = 1 + # DDM rule refresh hard lifetime limits (refresh only if lifetime within the range) TO_REFRESH_MAX_LIFETIME_DAYS = 7 TO_REFRESH_MIN_LIFETIME_HOURS = 2 @@ -178,7 +184,10 @@ def parameter_map(self) -> dict[str, Any]: "to_pin" (bool): whether to pin the dataset "to_backfill" (bool): whether the request is to backfill (all its active tasks have data_carousel_backfill), queued with lowest priority "suggested_dst_list" (list[str]): list of suggested destination RSEs - "remove_when_done" (bool): remove request and DDM rule asap when request done to save disk space + "remove_when_done" (bool): remove request and DDM rule asap when request done and all related tasks ended, to save disk space ; + kept updated to be True if any active task of the request has task parameter remove_rule_when_done + "last_used_time" (str): time in ISO format when the request was last used: updated to now periodically while having active tasks, + and to when the last related task ended after all related tasks ended ; the request is kept for a grace period after it "task_id": (int): task_id of the task which initiates the request "init_task_gshare": (str): (deprecated) original gshare of the task which initiates the request, for statistics "task_gshare": (str): original gshare of the task which initiates the request, for statistics @@ -480,6 +489,8 @@ def __init__(self, taskbufferIF: "TaskBuffer", *args: Any, **kwargs: Any) -> Non self._last_update_ts_dict: dict[str, datetime | None] = {} # cache of task params map per task ID; task params do not change after task submission self._task_params_cache: dict[int, dict[str, Any]] = {} + # cache of task params map per task ID for update_requests_usage + self._usage_task_params_cache: dict[int, dict[str, Any]] = {} # full pid self.full_pid = f"{socket.getfqdn().split('.')[0]}-{os.getpgrp()}-{os.getpid()}" # refresh @@ -1745,17 +1756,20 @@ def _refill_total_files_and_size(self, dc_req_spec: DataCarouselRequestSpec) -> tmp_log.error(f"got error ; {traceback.format_exc()}") return False - def _get_task_params_map(self, task_id: int) -> dict[str, Any] | None: + def _get_task_params_map(self, task_id: int, cache: dict[int, dict[str, Any]] | None = None) -> dict[str, Any] | None: """ Get task params map of a task, cached since task params do not change after task submission Args: task_id (int): JEDI task ID + cache (dict|None): cache of task params map per task ID to use; if None, use the default one Returns: dict | None : task params map, or None if failed """ - if (cached_task_params_map := self._task_params_cache.get(task_id)) is not None: + if cache is None: + cache = self._task_params_cache + if (cached_task_params_map := cache.get(task_id)) is not None: return cached_task_params_map tmp_log = LogWrapper(logger, f"_get_task_params_map task_id={task_id}") try: @@ -1768,18 +1782,20 @@ def _get_task_params_map(self, task_id: int) -> dict[str, Any] | None: except Exception: tmp_log.warning(f"failed to get task params ; {traceback.format_exc()}") return None - self._task_params_cache[task_id] = task_params_map + cache[task_id] = task_params_map return task_params_map - def _all_active_tasks_to_backfill(self, task_specs: list[JediTaskSpec]) -> bool: + def _all_active_tasks_have_task_param(self, task_specs: list[JediTaskSpec], param_name: str, cache: dict[int, dict[str, Any]] | None = None) -> bool: """ - Check whether there are active tasks and all of them have task parameter data_carousel_backfill + Check whether there are active tasks and all of them have the task parameter enabled Args: task_specs (list[JediTaskSpec]): tasks mapped to the request + param_name (str): name of the task parameter, e.g. data_carousel_backfill + cache (dict|None): cache of task params map per task ID to use; if None, use the default one Returns: - bool : True if there are active tasks and all of them are to backfill, False otherwise + bool : True if there are active tasks and all of them have the task parameter enabled, False otherwise """ has_active_task = False for task_spec in task_specs: @@ -1787,12 +1803,32 @@ def _all_active_tasks_to_backfill(self, task_specs: list[JediTaskSpec]) -> bool: continue if task_spec.jediTaskID is None: return False - task_params_map = self._get_task_params_map(task_spec.jediTaskID) - if task_params_map is None or not task_params_map.get("data_carousel_backfill"): + task_params_map = self._get_task_params_map(task_spec.jediTaskID, cache=cache) + if task_params_map is None or not task_params_map.get(param_name): return False has_active_task = True return has_active_task + def _any_active_task_has_task_param(self, task_specs: list[JediTaskSpec], param_name: str, cache: dict[int, dict[str, Any]] | None = None) -> bool: + """ + Check whether any active task has the task parameter enabled + + Args: + task_specs (list[JediTaskSpec]): tasks mapped to the request + param_name (str): name of the task parameter, e.g. remove_rule_when_done + cache (dict|None): cache of task params map per task ID to use; if None, use the default one + + Returns: + bool : True if any active task has the task parameter enabled, False otherwise + """ + for task_spec in task_specs: + if task_spec.status in FINAL_TASK_STATUSES or task_spec.jediTaskID is None: + continue + task_params_map = self._get_task_params_map(task_spec.jediTaskID, cache=cache) + if task_params_map is not None and task_params_map.get(param_name): + return True + return False + def _update_to_backfill(self, queued_requests: list[tuple[DataCarouselRequestSpec, list[JediTaskSpec]]]) -> None: """ Evaluate and update to_backfill of queued requests (except to_pin requests) according to their active tasks @@ -1809,7 +1845,7 @@ def _update_to_backfill(self, queued_requests: list[tuple[DataCarouselRequestSpe seen_task_ids.update(task_spec.jediTaskID for task_spec in task_specs if task_spec.jediTaskID is not None) if dc_req_spec.get_parameter("to_pin"): continue - to_backfill = self._all_active_tasks_to_backfill(task_specs) + to_backfill = self._all_active_tasks_have_task_param(task_specs, "data_carousel_backfill") if to_backfill: n_to_backfill += 1 if dc_req_spec.get_parameter("to_backfill") == to_backfill: @@ -2870,6 +2906,38 @@ def refresh_ddm_rule_of_request(self, dc_req_spec: DataCarouselRequestSpec, life # return return ret + def _get_last_used_grace_days(self) -> int | float: + """ + Get the grace period in days to keep a done request after its last related task ended + + Returns: + int | float : grace period in days, from config LAST_USED_GRACE_DAYS or default + """ + grace_days = self.taskBufferIF.getConfigValue("data_carousel", "LAST_USED_GRACE_DAYS", "jedi", "atlas") + if not isinstance(grace_days, (int, float)) or grace_days < 0: + return DEFAULT_LAST_USED_GRACE_DAYS + return grace_days + + def _get_last_used_time(self, dc_req_spec: DataCarouselRequestSpec) -> datetime | None: + """ + Get last_used_time of the request from its parameters + + Args: + dc_req_spec (DataCarouselRequestSpec): spec of the request + + Returns: + datetime | None : last_used_time, or None if not set or invalid + """ + last_used_time_str = dc_req_spec.get_parameter("last_used_time") + if not last_used_time_str: + return None + try: + return datetime.fromisoformat(last_used_time_str) + except ValueError: + tmp_log = LogWrapper(logger, f"_get_last_used_time request_id={dc_req_spec.request_id}") + tmp_log.warning(f"got invalid last_used_time={last_used_time_str} ; ignored") + return None + def keep_alive_ddm_rules(self, by: str = "watchdog") -> None: """ Keep alive DDM rules of requests of active tasks; also check all requests if their DDM rules are valid @@ -2886,6 +2954,8 @@ def keep_alive_ddm_rules(self, by: str = "watchdog") -> None: return all_requests_map, _ = all_requests active_tasked_requests_map, _ = active_tasked_requests + # grace period after last used, got when needed + grace_days = None for dc_req_spec in all_requests_map.values(): try: if dc_req_spec.status not in [DataCarouselRequestStatus.staging, DataCarouselRequestStatus.done]: @@ -2914,12 +2984,101 @@ def keep_alive_ddm_rules(self, by: str = "watchdog") -> None: pass else: # requests of non-active tasks; check if the rule is valid - is_valid, ddm_rule_id, _ = self._check_ddm_rule_of_request(dc_req_spec, by=by) + is_valid, ddm_rule_id, the_rule = self._check_ddm_rule_of_request(dc_req_spec, by=by) + # done requests within grace period after last used ; keep the rule alive until the grace period ends + if ( + is_valid + and ddm_rule_id + and the_rule + and dc_req_spec.status == DataCarouselRequestStatus.done + and not dc_req_spec.get_parameter("remove_when_done") + and (last_used_time := self._get_last_used_time(dc_req_spec)) is not None + ): + if grace_days is None: + grace_days = self._get_last_used_grace_days() + now_time = naive_utcnow() + grace_end_time = last_used_time + timedelta(days=grace_days) + rule_expiration_time = the_rule.get("expires_at") + if grace_end_time > now_time and rule_expiration_time is not None and rule_expiration_time < grace_end_time: + # rule to expire before the end of grace period ; extend it to cover the grace period with margin + lifetime_sec = int((grace_end_time + timedelta(days=LAST_USED_GRACE_RULE_MARGIN_DAYS) - now_time).total_seconds()) + if self._refresh_ddm_rule(ddm_rule_id, lifetime_sec): + tmp_log.debug( + f"request_id={dc_req_spec.request_id} status={dc_req_spec.status} ddm_rule_id={ddm_rule_id} " + f"refreshed lifetime to be {lifetime_sec / 86400:.2f} days long to cover grace period after last_used_time={last_used_time}" + ) # if not is_valid: # tmp_log.warning(f"ddm_rule_id={ddm_rule_id} rule not valid") except Exception: tmp_log.error(f"request_id={dc_req_spec.request_id} got error ; {traceback.format_exc()}") + def update_requests_usage(self, by: str = "watchdog") -> None: + """ + Update the usage of staging and done requests according to their related tasks: + remove_when_done : if the request has active tasks, True if any of them has task parameter remove_rule_when_done ; unchanged if no active task + last_used_time : now if the request has active tasks ; if all related tasks ended, the latest end time of them + + Args: + by (str): annotation of the caller of this method; default is "watchdog" + """ + tmp_log = LogWrapper(logger, f"update_requests_usage by={by}") + requests_with_tasks = self.taskBufferIF.get_data_carousel_requests_with_tasks_JEDI([DataCarouselRequestStatus.staging, DataCarouselRequestStatus.done]) + if requests_with_tasks is None: + tmp_log.warning("failed to query requests ; skipped") + return + n_updated = 0 + seen_task_ids: set[int] = set() + now_time_str = naive_utcnow().replace(microsecond=0).isoformat() + for dc_req_spec, task_specs in requests_with_tasks: + try: + params_to_update: dict[str, Any] = {} + # active tasks and latest end time of ended tasks + has_active_task = False + latest_end_time = None + for task_spec in task_specs: + if task_spec.status not in FINAL_TASK_STATUSES: + has_active_task = True + if task_spec.jediTaskID is not None: + seen_task_ids.add(task_spec.jediTaskID) + elif task_spec.endTime is not None and (latest_end_time is None or task_spec.endTime > latest_end_time): + latest_end_time = task_spec.endTime + if has_active_task: + # still used by active tasks + params_to_update["last_used_time"] = now_time_str + # decide remove_when_done by active tasks + remove_when_done = self._any_active_task_has_task_param(task_specs, "remove_rule_when_done", cache=self._usage_task_params_cache) + if bool(dc_req_spec.get_parameter("remove_when_done")) != remove_when_done: + params_to_update["remove_when_done"] = remove_when_done + elif latest_end_time is not None: + # all related tasks ended ; last used when the last task ended + last_used_time_str = latest_end_time.isoformat() + if dc_req_spec.get_parameter("last_used_time") != last_used_time_str: + params_to_update["last_used_time"] = last_used_time_str + if not params_to_update: + # unchanged + continue + # update DB + with self.request_lock(dc_req_spec.request_id) as locked_spec: + if not locked_spec: + # not getting lock; skip + tmp_log.warning(f"request_id={dc_req_spec.request_id} did not get lock; skipped") + continue + locked_spec.update_parameters(params_to_update) + if self.taskBufferIF.update_data_carousel_request_JEDI(locked_spec): + n_updated += 1 + if not has_active_task or "remove_when_done" in params_to_update: + # not to log the routine refresh of last_used_time of requests with active tasks + tmp_log.debug(f"request_id={dc_req_spec.request_id} status={locked_spec.status} updated DB with {params_to_update}") + else: + tmp_log.error(f"request_id={dc_req_spec.request_id} failed to update DB ; skipped") + except Exception: + tmp_log.error(f"request_id={dc_req_spec.request_id} got error ; {traceback.format_exc()}") + # clean up cache of tasks not active anymore + for task_id in list(self._usage_task_params_cache): + if task_id not in seen_task_ids: + del self._usage_task_params_cache[task_id] + tmp_log.debug(f"checked {len(requests_with_tasks)} requests ; updated {n_updated} requests in DB") + def _update_staged_files(self, dc_req_spec: DataCarouselRequestSpec, task_id_list: list[int] | None = None) -> bool | None: """ Update status of files in DB Jedi_Dataset_Contents for a request done staging @@ -3199,18 +3358,26 @@ def _get_orphan_requests(self) -> list[DataCarouselRequestSpec] | None: return None def clean_up_requests( - self, done_age_limit_days: int | float = DONE_LIFETIME_DAYS, outdated_age_limit_days: int | float = DONE_LIFETIME_DAYS, by: str = "watchdog" + self, + done_age_limit_days: int | float = DONE_LIFETIME_DAYS, + outdated_age_limit_days: int | float = DONE_LIFETIME_DAYS, + last_used_grace_days: int | float | None = None, + by: str = "watchdog", ) -> None: """ Clean up terminated and outdated requests Args: - done_age_limit_days (int|float): age limit in days for requests done and without active tasks - outdated_age_limit_days (int|float): age limit in days for outdated requests + done_age_limit_days (int|float): age limit in days since end_time for requests done and without active tasks + outdated_age_limit_days (int|float): age limit in days for outdated requests without tasks + last_used_grace_days (int|float|None): grace period in days since last_used_time for requests done and without active tasks; if None, from config LAST_USED_GRACE_DAYS or default by (str): annotation of the caller of this method; default is "watchdog" """ tmp_log = LogWrapper(logger, "clean_up_requests") try: + # grace period after last used + if last_used_grace_days is None: + last_used_grace_days = self._get_last_used_grace_days() # initialize done_requests_set = set() cancelled_requests_set = set() @@ -3238,13 +3405,17 @@ def clean_up_requests( # the request is also mapped to some active task, not to be cleaned up; skipped continue dc_req_spec = terminated_tasks_requests_map[request_id] - if dc_req_spec.status == DataCarouselRequestStatus.done and ( - (dc_req_spec.end_time and dc_req_spec.end_time < now_time - timedelta(days=done_age_limit_days)) - or dc_req_spec.get_parameter("rule_unfound") - or dc_req_spec.get_parameter("remove_when_done") - ): - # requests done, and old enough or DDM rule not found or to remove when done; to clean up - done_requests_set.add(request_id) + if dc_req_spec.status == DataCarouselRequestStatus.done: + # requests done ; to clean up if DDM rule not found or to remove when done, or both old enough and not used within grace period + to_clean_up = False + if dc_req_spec.get_parameter("rule_unfound") or dc_req_spec.get_parameter("remove_when_done"): + to_clean_up = True + elif dc_req_spec.end_time and dc_req_spec.end_time < now_time - timedelta(days=done_age_limit_days): + last_used_time = self._get_last_used_time(dc_req_spec) + if last_used_time is None or last_used_time < now_time - timedelta(days=last_used_grace_days): + to_clean_up = True + if to_clean_up: + done_requests_set.add(request_id) elif dc_req_spec.status == DataCarouselRequestStatus.queued: # requests queued while related tasks all terminated; to cancel (to clean up in next cycle) self.cancel_request(dc_req_spec, by=by, reason="queued_while_all_tasks_ended") @@ -3290,7 +3461,8 @@ def clean_up_requests( tmp_log.warning("failed to delete done requests; skipped") else: tmp_log.debug( - f"deleted {n_deleted} done requests older than {done_age_limit_days} days or rule_unfound or remove_when_done: {sorted(done_requests_set)}" + f"deleted {n_deleted} done requests older than {done_age_limit_days} days and last used over {last_used_grace_days} days ago, " + f"or rule_unfound or remove_when_done: {sorted(done_requests_set)}" ) if cancelled_requests_set: # cancelled requests @@ -3308,13 +3480,13 @@ def clean_up_requests( tmp_log.debug(f"deleted {n_deleted} retired requests: {sorted(retired_requests_set)}") else: tmp_log.debug("no terminated requests to delete; skipped") - # clean up outdated requests not related to any active task + # clean up outdated requests not related to any task outdated_request_ids = self.taskBufferIF.clean_up_data_carousel_requests_JEDI(time_limit_days=outdated_age_limit_days) if outdated_request_ids is None: tmp_log.warning("failed to delete outdated requests; skipped") else: tmp_log.debug( - f"deleted {len(outdated_request_ids)} outdated requests older than {outdated_age_limit_days} days and without active tasks: {outdated_request_ids}" + f"deleted {len(outdated_request_ids)} outdated requests older than {outdated_age_limit_days} days and without tasks: {outdated_request_ids}" ) except Exception: tmp_log.error(f"got error ; {traceback.format_exc()}") diff --git a/pandaserver/taskbuffer/db_proxy_mods/data_carousel_module.py b/pandaserver/taskbuffer/db_proxy_mods/data_carousel_module.py index c37de622c..a5bcb4701 100644 --- a/pandaserver/taskbuffer/db_proxy_mods/data_carousel_module.py +++ b/pandaserver/taskbuffer/db_proxy_mods/data_carousel_module.py @@ -6,7 +6,6 @@ from pandaserver.config import panda_config from pandaserver.taskbuffer.DataCarousel import ( - FINAL_TASK_STATUSES, DataCarouselRequestSpec, DataCarouselRequestStatus, get_resubmit_request_spec, @@ -253,6 +252,64 @@ def get_data_carousel_queued_requests_JEDI(self) -> list[tuple[DataCarouselReque self.dump_error_message(tmp_log) return None + # get data carousel requests with their related tasks + def get_data_carousel_requests_with_tasks_JEDI(self, status_list: list[str]) -> list[tuple[DataCarouselRequestSpec, list[JediTaskSpec]]] | None: + """ + Get data carousel requests in given statuses with their related tasks + + Args: + status_list (list[str]): statuses of requests to get + + Returns: + list | None : list of tuples in form of (request_spec, [task_spec, ...]) where task specs have jediTaskID, status and endTime (stateChangeTime if endTime is null) ; None if failed + """ + comment = " /* JediDBProxy.get_data_carousel_requests_with_tasks_JEDI */" + tmp_log = self.create_tagged_logger(comment) + tmp_log.debug("start") + try: + # start transaction + self.conn.begin() + status_var_names_str, status_var_map = get_sql_IN_bind_variables(status_list, prefix=":status") + # sql to query requests + sql_query_req = f"SELECT {DataCarouselRequestSpec.columnNames()} FROM {panda_config.schemaJEDI}.data_carousel_requests WHERE status IN ({status_var_names_str}) " + self.cur.execute(sql_query_req + comment, status_var_map) + res_list = self.cur.fetchall() + request_spec_map = {} + for res in res_list: + dc_req_spec = DataCarouselRequestSpec() + dc_req_spec.pack(res) + request_spec_map[dc_req_spec.request_id] = dc_req_spec + # sql to query related tasks of these requests + sql_query_tasks = ( + f"SELECT rel.request_id, t.jediTaskID, t.status, COALESCE(t.endTime, t.stateChangeTime) " + f"FROM {panda_config.schemaJEDI}.data_carousel_relations rel, {panda_config.schemaJEDI}.data_carousel_requests req, {panda_config.schemaJEDI}.JEDI_Tasks t " + f"WHERE rel.request_id=req.request_id AND rel.task_id=t.jediTaskID AND req.status IN ({status_var_names_str}) " + ) + self.cur.execute(sql_query_tasks + comment, status_var_map) + res_tasks = self.cur.fetchall() + task_specs_map: dict[int, list[JediTaskSpec]] = {} + for request_id, task_id, task_status, end_time in res_tasks: + task_spec = JediTaskSpec() + task_spec.jediTaskID = task_id + task_spec.status = task_status + task_spec.endTime = end_time + task_specs_map.setdefault(request_id, []).append(task_spec) + # commit + if not self._commit(): + raise RuntimeError("Commit error") + # return + ret_list = [] + for request_id, dc_req_spec in request_spec_map.items(): + ret_list.append((dc_req_spec, task_specs_map.get(request_id, []))) + tmp_log.debug(f"got {len(ret_list)} requests in {status_list}") + return ret_list + except Exception: + # roll back + self._rollback() + # error + self.dump_error_message(tmp_log) + return None + # get data carousel requests of tasks by task status def get_data_carousel_requests_by_task_status_JEDI( self, status_filter_list: list[str] | None = None, status_exclusion_list: list[str] | None = None @@ -469,7 +526,8 @@ def delete_data_carousel_requests_JEDI(self, request_id_list: list[int]) -> int # clean up data carousel requests def clean_up_data_carousel_requests_JEDI(self, time_limit_days: float = 30) -> list[int] | None: """ - Delete terminated requests which ended longer than time_limit_days ago and are not related to any active task + Delete terminated requests which ended longer than time_limit_days ago and are not related to any task + Requests related to tasks are cleaned up by clean_up_requests of DataCarousel according to their tasks Args: time_limit_days (float): age limit in days since end_time of the request @@ -485,32 +543,29 @@ def clean_up_data_carousel_requests_JEDI(self, time_limit_days: float = 30) -> l self.conn.begin() now_time = naive_utcnow() status_var_names_str, status_var_map = get_sql_IN_bind_variables(DataCarouselRequestStatus.final_statuses, prefix=":status") - task_status_var_names_str, task_status_var_map = get_sql_IN_bind_variables(FINAL_TASK_STATUSES, prefix=":task_status") - # condition that the request is not related to any active task - sql_no_active_task = ( + # condition that the request is not related to any task + sql_no_task = ( f"NOT EXISTS (SELECT 1 FROM {panda_config.schemaJEDI}.data_carousel_relations rel, {panda_config.schemaJEDI}.JEDI_Tasks t " - f"WHERE rel.request_id=req.request_id AND rel.task_id=t.jediTaskID AND t.status NOT IN ({task_status_var_names_str})) " + f"WHERE rel.request_id=req.request_id AND rel.task_id=t.jediTaskID) " ) - # sql to query terminated requests old enough and without active tasks + # sql to query terminated requests old enough and without tasks sql_query_req = ( f"SELECT req.request_id FROM {panda_config.schemaJEDI}.data_carousel_requests req " - f"WHERE req.status IN ({status_var_names_str}) AND req.end_time<=:end_time_max AND {sql_no_active_task}" + f"WHERE req.status IN ({status_var_names_str}) AND req.end_time<=:end_time_max AND {sql_no_task}" ) var_map = {":end_time_max": now_time - datetime.timedelta(days=time_limit_days)} var_map.update(status_var_map) - var_map.update(task_status_var_map) self.cur.execute(sql_query_req + comment, var_map) res = self.cur.fetchall() - # sql to delete a request; check conditions again in case it got related to an active task in the meantime + # sql to delete a request; check conditions again in case it got related to a task in the meantime sql_delete_req = ( f"DELETE FROM {panda_config.schemaJEDI}.data_carousel_requests req " - f"WHERE req.request_id=:request_id AND req.status IN ({status_var_names_str}) AND {sql_no_active_task}" + f"WHERE req.request_id=:request_id AND req.status IN ({status_var_names_str}) AND {sql_no_task}" ) deleted_request_ids = [] for (request_id,) in res: var_map = {":request_id": request_id} var_map.update(status_var_map) - var_map.update(task_status_var_map) self.cur.execute(sql_delete_req + comment, var_map) if self.cur.rowcount: deleted_request_ids.append(request_id) @@ -527,7 +582,7 @@ def clean_up_data_carousel_requests_JEDI(self, time_limit_days: float = 30) -> l raise RuntimeError("Commit error") # return tmp_log.debug( - f"cleaned up {len(deleted_request_ids)} requests and {ret_rel} relations older than {time_limit_days} days and without active tasks: {deleted_request_ids}" + f"cleaned up {len(deleted_request_ids)} requests and {ret_rel} relations older than {time_limit_days} days and without tasks: {deleted_request_ids}" ) return deleted_request_ids except Exception: From 7dbb6cee147722d10e0ad8e83dece3f8ad89b715 Mon Sep 17 00:00:00 2001 From: mightqxc Date: Thu, 26 Nov 2026 12:18:38 +0100 Subject: [PATCH 3/6] data carousel: refactor --- pandaserver/taskbuffer/DataCarousel.py | 162 +++++++++++++------------ 1 file changed, 82 insertions(+), 80 deletions(-) diff --git a/pandaserver/taskbuffer/DataCarousel.py b/pandaserver/taskbuffer/DataCarousel.py index ea7e72b69..092d98d5c 100644 --- a/pandaserver/taskbuffer/DataCarousel.py +++ b/pandaserver/taskbuffer/DataCarousel.py @@ -489,8 +489,8 @@ def __init__(self, taskbufferIF: "TaskBuffer", *args: Any, **kwargs: Any) -> Non self._last_update_ts_dict: dict[str, datetime | None] = {} # cache of task params map per task ID; task params do not change after task submission self._task_params_cache: dict[int, dict[str, Any]] = {} - # cache of task params map per task ID for update_requests_usage - self._usage_task_params_cache: dict[int, dict[str, Any]] = {} + # task IDs still needed in the cache of task params map, per consumer + self._task_params_cache_seen_map: dict[str, set[int]] = {} # full pid self.full_pid = f"{socket.getfqdn().split('.')[0]}-{os.getpgrp()}-{os.getpid()}" # refresh @@ -1756,20 +1756,17 @@ def _refill_total_files_and_size(self, dc_req_spec: DataCarouselRequestSpec) -> tmp_log.error(f"got error ; {traceback.format_exc()}") return False - def _get_task_params_map(self, task_id: int, cache: dict[int, dict[str, Any]] | None = None) -> dict[str, Any] | None: + def _get_task_params_map(self, task_id: int) -> dict[str, Any] | None: """ Get task params map of a task, cached since task params do not change after task submission Args: task_id (int): JEDI task ID - cache (dict|None): cache of task params map per task ID to use; if None, use the default one Returns: dict | None : task params map, or None if failed """ - if cache is None: - cache = self._task_params_cache - if (cached_task_params_map := cache.get(task_id)) is not None: + if (cached_task_params_map := self._task_params_cache.get(task_id)) is not None: return cached_task_params_map tmp_log = LogWrapper(logger, f"_get_task_params_map task_id={task_id}") try: @@ -1782,20 +1779,34 @@ def _get_task_params_map(self, task_id: int, cache: dict[int, dict[str, Any]] | except Exception: tmp_log.warning(f"failed to get task params ; {traceback.format_exc()}") return None - cache[task_id] = task_params_map + self._task_params_cache[task_id] = task_params_map return task_params_map - def _all_active_tasks_have_task_param(self, task_specs: list[JediTaskSpec], param_name: str, cache: dict[int, dict[str, Any]] | None = None) -> bool: + def _prune_task_params_cache(self, consumer: str, seen_task_ids: set[int]) -> None: """ - Check whether there are active tasks and all of them have the task parameter enabled + Record the task IDs still needed by a consumer of the cache of task params map, and drop the tasks needed by no consumer + + Args: + consumer (str): name of the consumer, e.g. the calling method + seen_task_ids (set[int]): task IDs the consumer saw in its latest run + """ + self._task_params_cache_seen_map[consumer] = seen_task_ids + needed_task_ids: set[int] = set() + for task_ids in self._task_params_cache_seen_map.values(): + needed_task_ids |= task_ids + for task_id in list(self._task_params_cache): + if task_id not in needed_task_ids: + del self._task_params_cache[task_id] + + def _all_active_tasks_to_backfill(self, task_specs: list[JediTaskSpec]) -> bool: + """ + Check whether there are active tasks and all of them have task parameter data_carousel_backfill Args: task_specs (list[JediTaskSpec]): tasks mapped to the request - param_name (str): name of the task parameter, e.g. data_carousel_backfill - cache (dict|None): cache of task params map per task ID to use; if None, use the default one Returns: - bool : True if there are active tasks and all of them have the task parameter enabled, False otherwise + bool : True if there are active tasks and all of them are to backfill, False otherwise """ has_active_task = False for task_spec in task_specs: @@ -1803,32 +1814,12 @@ def _all_active_tasks_have_task_param(self, task_specs: list[JediTaskSpec], para continue if task_spec.jediTaskID is None: return False - task_params_map = self._get_task_params_map(task_spec.jediTaskID, cache=cache) - if task_params_map is None or not task_params_map.get(param_name): + task_params_map = self._get_task_params_map(task_spec.jediTaskID) + if task_params_map is None or not task_params_map.get("data_carousel_backfill"): return False has_active_task = True return has_active_task - def _any_active_task_has_task_param(self, task_specs: list[JediTaskSpec], param_name: str, cache: dict[int, dict[str, Any]] | None = None) -> bool: - """ - Check whether any active task has the task parameter enabled - - Args: - task_specs (list[JediTaskSpec]): tasks mapped to the request - param_name (str): name of the task parameter, e.g. remove_rule_when_done - cache (dict|None): cache of task params map per task ID to use; if None, use the default one - - Returns: - bool : True if any active task has the task parameter enabled, False otherwise - """ - for task_spec in task_specs: - if task_spec.status in FINAL_TASK_STATUSES or task_spec.jediTaskID is None: - continue - task_params_map = self._get_task_params_map(task_spec.jediTaskID, cache=cache) - if task_params_map is not None and task_params_map.get(param_name): - return True - return False - def _update_to_backfill(self, queued_requests: list[tuple[DataCarouselRequestSpec, list[JediTaskSpec]]]) -> None: """ Evaluate and update to_backfill of queued requests (except to_pin requests) according to their active tasks @@ -1845,7 +1836,7 @@ def _update_to_backfill(self, queued_requests: list[tuple[DataCarouselRequestSpe seen_task_ids.update(task_spec.jediTaskID for task_spec in task_specs if task_spec.jediTaskID is not None) if dc_req_spec.get_parameter("to_pin"): continue - to_backfill = self._all_active_tasks_have_task_param(task_specs, "data_carousel_backfill") + to_backfill = self._all_active_tasks_to_backfill(task_specs) if to_backfill: n_to_backfill += 1 if dc_req_spec.get_parameter("to_backfill") == to_backfill: @@ -1871,9 +1862,7 @@ def _update_to_backfill(self, queued_requests: list[tuple[DataCarouselRequestSpe except Exception: tmp_log.error(f"request_id={dc_req_spec.request_id} got error ; {traceback.format_exc()}") # clean up cache of tasks not mapped to queued requests anymore - for task_id in list(self._task_params_cache): - if task_id not in seen_task_ids: - del self._task_params_cache[task_id] + self._prune_task_params_cache("_update_to_backfill", seen_task_ids) tmp_log.debug(f"got {n_to_backfill} requests to backfill ; updated {n_updated} requests in DB") def submit_data_carousel_requests( @@ -2918,26 +2907,59 @@ def _get_last_used_grace_days(self) -> int | float: return DEFAULT_LAST_USED_GRACE_DAYS return grace_days - def _get_last_used_time(self, dc_req_spec: DataCarouselRequestSpec) -> datetime | None: + def _get_grace_end_time(self, dc_req_spec: DataCarouselRequestSpec, grace_days: int | float) -> datetime | None: """ - Get last_used_time of the request from its parameters + Get the end of the grace period of the request, i.e. last_used_time in its parameters plus grace_days Args: dc_req_spec (DataCarouselRequestSpec): spec of the request + grace_days (int|float): grace period in days after last used Returns: - datetime | None : last_used_time, or None if not set or invalid + datetime | None : end time of the grace period, or None if last_used_time not set or invalid """ last_used_time_str = dc_req_spec.get_parameter("last_used_time") if not last_used_time_str: return None try: - return datetime.fromisoformat(last_used_time_str) + return datetime.fromisoformat(last_used_time_str) + timedelta(days=grace_days) except ValueError: - tmp_log = LogWrapper(logger, f"_get_last_used_time request_id={dc_req_spec.request_id}") + tmp_log = LogWrapper(logger, f"_get_grace_end_time request_id={dc_req_spec.request_id}") tmp_log.warning(f"got invalid last_used_time={last_used_time_str} ; ignored") return None + def _extend_rule_for_grace_period(self, dc_req_spec: DataCarouselRequestSpec, ddm_rule_id: str, the_rule: dict[str, Any], grace_days: int | float) -> bool: + """ + Extend the DDM rule of a done request without active tasks to cover its grace period after last used (with margin), if the rule expires earlier + + Args: + dc_req_spec (DataCarouselRequestSpec): spec of the request + ddm_rule_id (str): DDM rule ID of the request + the_rule (dict): DDM rule data + grace_days (int|float): grace period in days after last used + + Returns: + bool : True if the rule was extended, False otherwise + """ + if dc_req_spec.status != DataCarouselRequestStatus.done or dc_req_spec.get_parameter("remove_when_done"): + # not to be kept for grace period + return False + grace_end_time = self._get_grace_end_time(dc_req_spec, grace_days) + now_time = naive_utcnow() + if grace_end_time is None or grace_end_time <= now_time: + # no grace period or grace period over + return False + rule_expiration_time = the_rule.get("expires_at") + if rule_expiration_time is None or rule_expiration_time >= grace_end_time: + # rule lifetime long enough + return False + lifetime_sec = int((grace_end_time + timedelta(days=LAST_USED_GRACE_RULE_MARGIN_DAYS) - now_time).total_seconds()) + if not self._refresh_ddm_rule(ddm_rule_id, lifetime_sec): + return False + tmp_log = LogWrapper(logger, f"_extend_rule_for_grace_period request_id={dc_req_spec.request_id}") + tmp_log.debug(f"ddm_rule_id={ddm_rule_id} refreshed lifetime to be {lifetime_sec / 86400:.2f} days long to cover grace period until {grace_end_time}") + return True + def keep_alive_ddm_rules(self, by: str = "watchdog") -> None: """ Keep alive DDM rules of requests of active tasks; also check all requests if their DDM rules are valid @@ -2954,8 +2976,8 @@ def keep_alive_ddm_rules(self, by: str = "watchdog") -> None: return all_requests_map, _ = all_requests active_tasked_requests_map, _ = active_tasked_requests - # grace period after last used, got when needed - grace_days = None + # grace period after last used + grace_days = self._get_last_used_grace_days() for dc_req_spec in all_requests_map.values(): try: if dc_req_spec.status not in [DataCarouselRequestStatus.staging, DataCarouselRequestStatus.done]: @@ -2985,28 +3007,9 @@ def keep_alive_ddm_rules(self, by: str = "watchdog") -> None: else: # requests of non-active tasks; check if the rule is valid is_valid, ddm_rule_id, the_rule = self._check_ddm_rule_of_request(dc_req_spec, by=by) - # done requests within grace period after last used ; keep the rule alive until the grace period ends - if ( - is_valid - and ddm_rule_id - and the_rule - and dc_req_spec.status == DataCarouselRequestStatus.done - and not dc_req_spec.get_parameter("remove_when_done") - and (last_used_time := self._get_last_used_time(dc_req_spec)) is not None - ): - if grace_days is None: - grace_days = self._get_last_used_grace_days() - now_time = naive_utcnow() - grace_end_time = last_used_time + timedelta(days=grace_days) - rule_expiration_time = the_rule.get("expires_at") - if grace_end_time > now_time and rule_expiration_time is not None and rule_expiration_time < grace_end_time: - # rule to expire before the end of grace period ; extend it to cover the grace period with margin - lifetime_sec = int((grace_end_time + timedelta(days=LAST_USED_GRACE_RULE_MARGIN_DAYS) - now_time).total_seconds()) - if self._refresh_ddm_rule(ddm_rule_id, lifetime_sec): - tmp_log.debug( - f"request_id={dc_req_spec.request_id} status={dc_req_spec.status} ddm_rule_id={ddm_rule_id} " - f"refreshed lifetime to be {lifetime_sec / 86400:.2f} days long to cover grace period after last_used_time={last_used_time}" - ) + # keep the rule alive until the grace period after last used ends + if is_valid and ddm_rule_id and the_rule: + self._extend_rule_for_grace_period(dc_req_spec, ddm_rule_id, the_rule, grace_days) # if not is_valid: # tmp_log.warning(f"ddm_rule_id={ddm_rule_id} rule not valid") except Exception: @@ -3032,21 +3035,25 @@ def update_requests_usage(self, by: str = "watchdog") -> None: for dc_req_spec, task_specs in requests_with_tasks: try: params_to_update: dict[str, Any] = {} - # active tasks and latest end time of ended tasks + # active tasks, whether any of them has remove_rule_when_done, and latest end time of ended tasks has_active_task = False + remove_when_done = False latest_end_time = None for task_spec in task_specs: if task_spec.status not in FINAL_TASK_STATUSES: has_active_task = True if task_spec.jediTaskID is not None: seen_task_ids.add(task_spec.jediTaskID) + if not remove_when_done: + task_params_map = self._get_task_params_map(task_spec.jediTaskID) + if task_params_map is not None and task_params_map.get("remove_rule_when_done"): + remove_when_done = True elif task_spec.endTime is not None and (latest_end_time is None or task_spec.endTime > latest_end_time): latest_end_time = task_spec.endTime if has_active_task: # still used by active tasks params_to_update["last_used_time"] = now_time_str - # decide remove_when_done by active tasks - remove_when_done = self._any_active_task_has_task_param(task_specs, "remove_rule_when_done", cache=self._usage_task_params_cache) + # remove_when_done decided by active tasks if bool(dc_req_spec.get_parameter("remove_when_done")) != remove_when_done: params_to_update["remove_when_done"] = remove_when_done elif latest_end_time is not None: @@ -3074,9 +3081,7 @@ def update_requests_usage(self, by: str = "watchdog") -> None: except Exception: tmp_log.error(f"request_id={dc_req_spec.request_id} got error ; {traceback.format_exc()}") # clean up cache of tasks not active anymore - for task_id in list(self._usage_task_params_cache): - if task_id not in seen_task_ids: - del self._usage_task_params_cache[task_id] + self._prune_task_params_cache("update_requests_usage", seen_task_ids) tmp_log.debug(f"checked {len(requests_with_tasks)} requests ; updated {n_updated} requests in DB") def _update_staged_files(self, dc_req_spec: DataCarouselRequestSpec, task_id_list: list[int] | None = None) -> bool | None: @@ -3361,7 +3366,6 @@ def clean_up_requests( self, done_age_limit_days: int | float = DONE_LIFETIME_DAYS, outdated_age_limit_days: int | float = DONE_LIFETIME_DAYS, - last_used_grace_days: int | float | None = None, by: str = "watchdog", ) -> None: """ @@ -3370,14 +3374,12 @@ def clean_up_requests( Args: done_age_limit_days (int|float): age limit in days since end_time for requests done and without active tasks outdated_age_limit_days (int|float): age limit in days for outdated requests without tasks - last_used_grace_days (int|float|None): grace period in days since last_used_time for requests done and without active tasks; if None, from config LAST_USED_GRACE_DAYS or default by (str): annotation of the caller of this method; default is "watchdog" """ tmp_log = LogWrapper(logger, "clean_up_requests") try: # grace period after last used - if last_used_grace_days is None: - last_used_grace_days = self._get_last_used_grace_days() + last_used_grace_days = self._get_last_used_grace_days() # initialize done_requests_set = set() cancelled_requests_set = set() @@ -3411,8 +3413,8 @@ def clean_up_requests( if dc_req_spec.get_parameter("rule_unfound") or dc_req_spec.get_parameter("remove_when_done"): to_clean_up = True elif dc_req_spec.end_time and dc_req_spec.end_time < now_time - timedelta(days=done_age_limit_days): - last_used_time = self._get_last_used_time(dc_req_spec) - if last_used_time is None or last_used_time < now_time - timedelta(days=last_used_grace_days): + grace_end_time = self._get_grace_end_time(dc_req_spec, last_used_grace_days) + if grace_end_time is None or grace_end_time < now_time: to_clean_up = True if to_clean_up: done_requests_set.add(request_id) From 5b8337b5b13e6d0d5676eec2b18eb31962b55b80 Mon Sep 17 00:00:00 2001 From: mightqxc Date: Thu, 26 Nov 2026 12:49:23 +0100 Subject: [PATCH 4/6] data carousel: unify grace period rul keep-alive, increase UpdateRequestsUsage lock time to 8 hours --- .../jedidog/AtlasDataCarouselWatchDog.py | 5 +- pandaserver/taskbuffer/DataCarousel.py | 118 +++++++++--------- .../db_proxy_mods/data_carousel_module.py | 10 +- 3 files changed, 67 insertions(+), 66 deletions(-) diff --git a/pandajedi/jedidog/AtlasDataCarouselWatchDog.py b/pandajedi/jedidog/AtlasDataCarouselWatchDog.py index 19663e386..e10e89494 100644 --- a/pandajedi/jedidog/AtlasDataCarouselWatchDog.py +++ b/pandajedi/jedidog/AtlasDataCarouselWatchDog.py @@ -26,7 +26,7 @@ StageDCRequests_LOCK_TIME_MINUTES = 5 CheckDCRequests_LOCK_TIME_MINUTES = 5 KeepRulesAlive_LOCK_TIME_MINUTES = 60 -UpdateRequestsUsage_LOCK_TIME_MINUTES = 60 +UpdateRequestsUsage_LOCK_TIME_MINUTES = 480 CleanDCRequests_LOCK_TIME_MINUTES = 1440 RescuePendingTasks_LOCK_TIME_MINUTES = 120 @@ -126,7 +126,8 @@ def doKeepRulesAlive(self) -> None: def doUpdateRequestsUsage(self) -> None: """ - Action to update the usage of DC requests (remove_when_done and last_used_time) according to their related tasks + Action to update the usage of DC requests (remove_when_done and last_used_time) according to their related tasks, + and keep alive DDM rules of done requests within grace period after last used """ tmpLog = MsgWrapper(logger, " #ATM #KV doUpdateRequestsUsage") tmpLog.debug("start") diff --git a/pandaserver/taskbuffer/DataCarousel.py b/pandaserver/taskbuffer/DataCarousel.py index 092d98d5c..b0bd850cc 100644 --- a/pandaserver/taskbuffer/DataCarousel.py +++ b/pandaserver/taskbuffer/DataCarousel.py @@ -2851,15 +2851,23 @@ def _check_ddm_rule_of_request( # return return is_valid, ddm_rule_id, the_rule - def refresh_ddm_rule_of_request(self, dc_req_spec: DataCarouselRequestSpec, lifetime_days: int, force_refresh: bool = False, by: str = "unknown") -> bool: + def refresh_ddm_rule_of_request( + self, + dc_req_spec: DataCarouselRequestSpec, + lifetime_days: int | None = None, + force_refresh: bool = False, + by: str = "unknown", + until_time: datetime | None = None, + ) -> bool: """ Refresh lifetime of the DDM rule of one request Args: dc_req_spec (DataCarouselRequestSpec): spec of the request - lifetime_days (int): lifetime in days to set - force_refresh (bool): force to refresh regardless of to_refresh max/min lifetime + lifetime_days (int|None): lifetime in days to set ; ignored if until_time is given + force_refresh (bool): force to refresh regardless of to_refresh max/min lifetime ; ignored if until_time is given by (str): annotation of the caller of this method; default is "watchdog" + until_time (datetime|None): if given, refresh only if the rule expires before until_time, to make it last until until_time Returns: bool : True for success, False otherwise @@ -2873,10 +2881,18 @@ def refresh_ddm_rule_of_request(self, dc_req_spec: DataCarouselRequestSpec, life # rule not valid; skipped tmp_log.error(f"ddm_rule_id={ddm_rule_id} rule not valid; skipped") return ret + now_time = naive_utcnow() + if until_time is not None: + # refresh only if the rule expires before until_time ; rule without expiration lasts long enough + if the_rule["expires_at"] and the_rule["expires_at"] < until_time: + ret = self._refresh_ddm_rule(ddm_rule_id, int((until_time - now_time).total_seconds())) + return ret + if lifetime_days is None: + tmp_log.error("neither lifetime_days nor until_time given ; skipped") + return ret # rule lifetime rule_lifetime = None if the_rule["expires_at"]: - now_time = naive_utcnow() rule_lifetime = the_rule["expires_at"] - now_time # trigger renewal if force_refresh or when lifetime within the range if ( @@ -2928,38 +2944,6 @@ def _get_grace_end_time(self, dc_req_spec: DataCarouselRequestSpec, grace_days: tmp_log.warning(f"got invalid last_used_time={last_used_time_str} ; ignored") return None - def _extend_rule_for_grace_period(self, dc_req_spec: DataCarouselRequestSpec, ddm_rule_id: str, the_rule: dict[str, Any], grace_days: int | float) -> bool: - """ - Extend the DDM rule of a done request without active tasks to cover its grace period after last used (with margin), if the rule expires earlier - - Args: - dc_req_spec (DataCarouselRequestSpec): spec of the request - ddm_rule_id (str): DDM rule ID of the request - the_rule (dict): DDM rule data - grace_days (int|float): grace period in days after last used - - Returns: - bool : True if the rule was extended, False otherwise - """ - if dc_req_spec.status != DataCarouselRequestStatus.done or dc_req_spec.get_parameter("remove_when_done"): - # not to be kept for grace period - return False - grace_end_time = self._get_grace_end_time(dc_req_spec, grace_days) - now_time = naive_utcnow() - if grace_end_time is None or grace_end_time <= now_time: - # no grace period or grace period over - return False - rule_expiration_time = the_rule.get("expires_at") - if rule_expiration_time is None or rule_expiration_time >= grace_end_time: - # rule lifetime long enough - return False - lifetime_sec = int((grace_end_time + timedelta(days=LAST_USED_GRACE_RULE_MARGIN_DAYS) - now_time).total_seconds()) - if not self._refresh_ddm_rule(ddm_rule_id, lifetime_sec): - return False - tmp_log = LogWrapper(logger, f"_extend_rule_for_grace_period request_id={dc_req_spec.request_id}") - tmp_log.debug(f"ddm_rule_id={ddm_rule_id} refreshed lifetime to be {lifetime_sec / 86400:.2f} days long to cover grace period until {grace_end_time}") - return True - def keep_alive_ddm_rules(self, by: str = "watchdog") -> None: """ Keep alive DDM rules of requests of active tasks; also check all requests if their DDM rules are valid @@ -2976,8 +2960,6 @@ def keep_alive_ddm_rules(self, by: str = "watchdog") -> None: return all_requests_map, _ = all_requests active_tasked_requests_map, _ = active_tasked_requests - # grace period after last used - grace_days = self._get_last_used_grace_days() for dc_req_spec in all_requests_map.values(): try: if dc_req_spec.status not in [DataCarouselRequestStatus.staging, DataCarouselRequestStatus.done]: @@ -3006,10 +2988,7 @@ def keep_alive_ddm_rules(self, by: str = "watchdog") -> None: pass else: # requests of non-active tasks; check if the rule is valid - is_valid, ddm_rule_id, the_rule = self._check_ddm_rule_of_request(dc_req_spec, by=by) - # keep the rule alive until the grace period after last used ends - if is_valid and ddm_rule_id and the_rule: - self._extend_rule_for_grace_period(dc_req_spec, ddm_rule_id, the_rule, grace_days) + is_valid, ddm_rule_id, _ = self._check_ddm_rule_of_request(dc_req_spec, by=by) # if not is_valid: # tmp_log.warning(f"ddm_rule_id={ddm_rule_id} rule not valid") except Exception: @@ -3020,6 +2999,7 @@ def update_requests_usage(self, by: str = "watchdog") -> None: Update the usage of staging and done requests according to their related tasks: remove_when_done : if the request has active tasks, True if any of them has task parameter remove_rule_when_done ; unchanged if no active task last_used_time : now if the request has active tasks ; if all related tasks ended, the latest end time of them + Also keep alive the DDM rules of done requests without active tasks (except remove_when_done) to cover the grace period after last used Args: by (str): annotation of the caller of this method; default is "watchdog" @@ -3030,8 +3010,11 @@ def update_requests_usage(self, by: str = "watchdog") -> None: tmp_log.warning("failed to query requests ; skipped") return n_updated = 0 + n_rules_refreshed = 0 seen_task_ids: set[int] = set() - now_time_str = naive_utcnow().replace(microsecond=0).isoformat() + now_time = naive_utcnow() + now_time_str = now_time.replace(microsecond=0).isoformat() + grace_days = self._get_last_used_grace_days() for dc_req_spec, task_specs in requests_with_tasks: try: params_to_update: dict[str, Any] = {} @@ -3061,28 +3044,43 @@ def update_requests_usage(self, by: str = "watchdog") -> None: last_used_time_str = latest_end_time.isoformat() if dc_req_spec.get_parameter("last_used_time") != last_used_time_str: params_to_update["last_used_time"] = last_used_time_str - if not params_to_update: - # unchanged - continue # update DB - with self.request_lock(dc_req_spec.request_id) as locked_spec: - if not locked_spec: - # not getting lock; skip - tmp_log.warning(f"request_id={dc_req_spec.request_id} did not get lock; skipped") - continue - locked_spec.update_parameters(params_to_update) - if self.taskBufferIF.update_data_carousel_request_JEDI(locked_spec): - n_updated += 1 - if not has_active_task or "remove_when_done" in params_to_update: - # not to log the routine refresh of last_used_time of requests with active tasks - tmp_log.debug(f"request_id={dc_req_spec.request_id} status={locked_spec.status} updated DB with {params_to_update}") - else: - tmp_log.error(f"request_id={dc_req_spec.request_id} failed to update DB ; skipped") + if params_to_update: + with self.request_lock(dc_req_spec.request_id) as locked_spec: + if not locked_spec: + # not getting lock; skip + tmp_log.warning(f"request_id={dc_req_spec.request_id} did not get lock; skipped") + continue + locked_spec.update_parameters(params_to_update) + if self.taskBufferIF.update_data_carousel_request_JEDI(locked_spec): + n_updated += 1 + if not has_active_task or "remove_when_done" in params_to_update: + # not to log the routine refresh of last_used_time of requests with active tasks + tmp_log.debug(f"request_id={dc_req_spec.request_id} status={locked_spec.status} updated DB with {params_to_update}") + else: + tmp_log.error(f"request_id={dc_req_spec.request_id} failed to update DB ; skipped") + # keep alive the DDM rule of done request without active tasks until the grace period after last used ends, with margin for the daily clean-up + if ( + not has_active_task + and latest_end_time is not None + and dc_req_spec.status == DataCarouselRequestStatus.done + and not dc_req_spec.get_parameter("remove_when_done") + ): + grace_end_time = latest_end_time + timedelta(days=grace_days) + if grace_end_time > now_time: + until_time = grace_end_time + timedelta(days=LAST_USED_GRACE_RULE_MARGIN_DAYS) + if self.refresh_ddm_rule_of_request(dc_req_spec, by=by, until_time=until_time): + n_rules_refreshed += 1 + tmp_log.debug( + f"request_id={dc_req_spec.request_id} ddm_rule_id={dc_req_spec.ddm_rule_id} refreshed lifetime until {until_time} to cover grace period" + ) except Exception: tmp_log.error(f"request_id={dc_req_spec.request_id} got error ; {traceback.format_exc()}") # clean up cache of tasks not active anymore self._prune_task_params_cache("update_requests_usage", seen_task_ids) - tmp_log.debug(f"checked {len(requests_with_tasks)} requests ; updated {n_updated} requests in DB") + tmp_log.debug( + f"checked {len(requests_with_tasks)} requests ; updated {n_updated} requests in DB ; refreshed {n_rules_refreshed} DDM rules for grace period" + ) def _update_staged_files(self, dc_req_spec: DataCarouselRequestSpec, task_id_list: list[int] | None = None) -> bool | None: """ diff --git a/pandaserver/taskbuffer/db_proxy_mods/data_carousel_module.py b/pandaserver/taskbuffer/db_proxy_mods/data_carousel_module.py index a5bcb4701..038002cb2 100644 --- a/pandaserver/taskbuffer/db_proxy_mods/data_carousel_module.py +++ b/pandaserver/taskbuffer/db_proxy_mods/data_carousel_module.py @@ -279,16 +279,18 @@ def get_data_carousel_requests_with_tasks_JEDI(self, status_list: list[str]) -> dc_req_spec = DataCarouselRequestSpec() dc_req_spec.pack(res) request_spec_map[dc_req_spec.request_id] = dc_req_spec - # sql to query related tasks of these requests + # sql to query related tasks of all requests ; tasks of requests not in request_spec_map are skipped sql_query_tasks = ( f"SELECT rel.request_id, t.jediTaskID, t.status, COALESCE(t.endTime, t.stateChangeTime) " - f"FROM {panda_config.schemaJEDI}.data_carousel_relations rel, {panda_config.schemaJEDI}.data_carousel_requests req, {panda_config.schemaJEDI}.JEDI_Tasks t " - f"WHERE rel.request_id=req.request_id AND rel.task_id=t.jediTaskID AND req.status IN ({status_var_names_str}) " + f"FROM {panda_config.schemaJEDI}.data_carousel_relations rel, {panda_config.schemaJEDI}.JEDI_Tasks t " + f"WHERE rel.task_id=t.jediTaskID " ) - self.cur.execute(sql_query_tasks + comment, status_var_map) + self.cur.execute(sql_query_tasks + comment, {}) res_tasks = self.cur.fetchall() task_specs_map: dict[int, list[JediTaskSpec]] = {} for request_id, task_id, task_status, end_time in res_tasks: + if request_id not in request_spec_map: + continue task_spec = JediTaskSpec() task_spec.jediTaskID = task_id task_spec.status = task_status From 9b63b90e4f08f94f1cff232850a4eada172c5c42 Mon Sep 17 00:00:00 2001 From: mightqxc Date: Thu, 26 Nov 2026 13:03:31 +0100 Subject: [PATCH 5/6] data carousel: enhance lock management --- pandaserver/taskbuffer/DataCarousel.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/pandaserver/taskbuffer/DataCarousel.py b/pandaserver/taskbuffer/DataCarousel.py index b0bd850cc..ed2e5bec8 100644 --- a/pandaserver/taskbuffer/DataCarousel.py +++ b/pandaserver/taskbuffer/DataCarousel.py @@ -790,6 +790,7 @@ def request_lock(self, request_id: int, lock_expiration_sec: int = 120) -> Gener # got_lock = None locked_spec = None + lock_start_time = None try: # try to update locked_by and lock_time sql_lock = ( @@ -814,9 +815,10 @@ def request_lock(self, request_id: int, lock_expiration_sec: int = 120) -> Gener got_lock = False tmp_log.debug("did not get lock; skipped") else: - # got the lock + # got the lock ; not to log as it is routine got_lock = True - tmp_log.debug("got lock") + lock_start_time = naive_utcnow() + # tmp_log.debug("got lock") if got_lock: # yield the updated request spec locked locked_spec = self.get_request_by_id(request_id) @@ -843,8 +845,11 @@ def request_lock(self, request_id: int, lock_expiration_sec: int = 120) -> Gener tmp_log.error("more than one requests updated to unlock; unexpected") elif row_count == 0: tmp_log.error("no request updated to unlock; skipped") - else: - tmp_log.debug("released lock") + elif lock_start_time is not None and (lock_held_sec := (naive_utcnow() - lock_start_time).total_seconds()) > lock_expiration_sec / 2: + # released the lock ; only to log when held so long that it could expire and be taken by others + tmp_log.warning(f"released lock held for {lock_held_sec:.1f} sec, over half of lock_expiration_sec={lock_expiration_sec}") + # else: + # tmp_log.debug("released lock") def _update_rses(self, time_limit_minutes: int | float = 30) -> None: """ From 5fafece878e13a6dd30c492604523d42e59198d7 Mon Sep 17 00:00:00 2001 From: mightqxc Date: Thu, 26 Nov 2026 13:54:59 +0100 Subject: [PATCH 6/6] data carousel: refactor to associate grace period and cleanup logic --- pandaserver/taskbuffer/DataCarousel.py | 94 +++++++++++++------------- 1 file changed, 48 insertions(+), 46 deletions(-) diff --git a/pandaserver/taskbuffer/DataCarousel.py b/pandaserver/taskbuffer/DataCarousel.py index ed2e5bec8..286b9f96c 100644 --- a/pandaserver/taskbuffer/DataCarousel.py +++ b/pandaserver/taskbuffer/DataCarousel.py @@ -2957,20 +2957,23 @@ def keep_alive_ddm_rules(self, by: str = "watchdog") -> None: by (str): annotation of the caller of this method; default is "watchdog" """ tmp_log = LogWrapper(logger, "keep_alive_ddm_rules") - # get all requests, and those of active tasks - all_requests = self.taskBufferIF.get_data_carousel_requests_by_task_status_JEDI() - active_tasked_requests = self.taskBufferIF.get_data_carousel_requests_by_task_status_JEDI(status_exclusion_list=FINAL_TASK_STATUSES) - if all_requests is None or active_tasked_requests is None: + # get staging and done requests with their related tasks + requests_with_tasks = self.taskBufferIF.get_data_carousel_requests_with_tasks_JEDI([DataCarouselRequestStatus.staging, DataCarouselRequestStatus.done]) + if requests_with_tasks is None: tmp_log.warning("failed to query requests ; skipped") return - all_requests_map, _ = all_requests - active_tasked_requests_map, _ = active_tasked_requests - for dc_req_spec in all_requests_map.values(): + for dc_req_spec, task_specs in requests_with_tasks: try: - if dc_req_spec.status not in [DataCarouselRequestStatus.staging, DataCarouselRequestStatus.done]: - # skip requests without need to keep rules alive + if not task_specs: + # requests without tasks ; skipped continue - if dc_req_spec.request_id in active_tasked_requests_map: + # whether with active tasks + has_active_task = False + for task_spec in task_specs: + if task_spec.status not in FINAL_TASK_STATUSES: + has_active_task = True + break + if has_active_task: # requests of active tasks; decide lifetime in days days = None if dc_req_spec.status == DataCarouselRequestStatus.staging: @@ -3387,39 +3390,44 @@ def clean_up_requests( done_requests_set = set() cancelled_requests_set = set() retired_requests_set = set() - # get requests of terminated and active tasks - terminated_tasks_requests = self.taskBufferIF.get_data_carousel_requests_by_task_status_JEDI(status_filter_list=FINAL_TASK_STATUSES) - active_tasks_requests = self.taskBufferIF.get_data_carousel_requests_by_task_status_JEDI(status_exclusion_list=FINAL_TASK_STATUSES) - if terminated_tasks_requests is None or active_tasks_requests is None: + # get requests with their related tasks + requests_with_tasks = self.taskBufferIF.get_data_carousel_requests_with_tasks_JEDI( + DataCarouselRequestStatus.active_statuses + DataCarouselRequestStatus.final_statuses + ) + if requests_with_tasks is None: tmp_log.warning("failed to query requests ; skipped") return - terminated_tasks_requests_map, terminated_tasks_relation_map = terminated_tasks_requests - active_tasks_requests_map, active_tasks_relation_map = active_tasks_requests now_time = naive_utcnow() - # set of requests of terminated tasks - request_ids_of_terminated_tasks = set() - for request_id_list in terminated_tasks_relation_map.values(): - request_ids_of_terminated_tasks |= set(request_id_list) - # set of requests of active tasks - request_ids_of_active_tasks = set() - for request_id_list in active_tasks_relation_map.values(): - request_ids_of_active_tasks |= set(request_id_list) - # loop over requests of terminated tasks - for request_id in request_ids_of_terminated_tasks: - if request_id in active_tasks_requests_map: - # the request is also mapped to some active task, not to be cleaned up; skipped + request_spec_map = {} + for dc_req_spec, task_specs in requests_with_tasks: + if not task_specs: + # requests without tasks ; handled as orphan or outdated requests below continue - dc_req_spec = terminated_tasks_requests_map[request_id] - if dc_req_spec.status == DataCarouselRequestStatus.done: - # requests done ; to clean up if DDM rule not found or to remove when done, or both old enough and not used within grace period - to_clean_up = False - if dc_req_spec.get_parameter("rule_unfound") or dc_req_spec.get_parameter("remove_when_done"): - to_clean_up = True - elif dc_req_spec.end_time and dc_req_spec.end_time < now_time - timedelta(days=done_age_limit_days): - grace_end_time = self._get_grace_end_time(dc_req_spec, last_used_grace_days) - if grace_end_time is None or grace_end_time < now_time: - to_clean_up = True - if to_clean_up: + request_id = dc_req_spec.request_id + request_spec_map[request_id] = dc_req_spec + is_done = dc_req_spec.status == DataCarouselRequestStatus.done + to_remove = dc_req_spec.get_parameter("rule_unfound") or dc_req_spec.get_parameter("remove_when_done") + if is_done and not to_remove: + grace_end_time = self._get_grace_end_time(dc_req_spec, last_used_grace_days) + if grace_end_time is not None and grace_end_time >= now_time: + # requests done and used within grace period ; not to clean up regardless of tasks + continue + # whether with active tasks + has_active_task = False + for task_spec in task_specs: + if task_spec.status not in FINAL_TASK_STATUSES: + has_active_task = True + break + if has_active_task: + if dc_req_spec.status == DataCarouselRequestStatus.staging and dc_req_spec.get_parameter("rule_unfound"): + # requests staging but DDM rule not found; to cancel + self.cancel_request(dc_req_spec, by=by, reason="rule_unfound") + # requests with active tasks not to be cleaned up + continue + # requests whose related tasks all ended + if is_done: + # requests done ; to clean up if DDM rule not found or to remove when done, or old enough (already not used within grace period) + if to_remove or (dc_req_spec.end_time and dc_req_spec.end_time < now_time - timedelta(days=done_age_limit_days)): done_requests_set.add(request_id) elif dc_req_spec.status == DataCarouselRequestStatus.queued: # requests queued while related tasks all terminated; to cancel (to clean up in next cycle) @@ -3433,12 +3441,6 @@ def clean_up_requests( elif dc_req_spec.status == DataCarouselRequestStatus.retired: # requests retired; to clean up retired_requests_set.add(request_id) - # loop over requests of active tasks to cancel bad ones - for request_id in request_ids_of_active_tasks: - dc_req_spec = active_tasks_requests_map[request_id] - if dc_req_spec.status == DataCarouselRequestStatus.staging and dc_req_spec.get_parameter("rule_unfound"): - # requests staging but DDM rule not found; to cancel - self.cancel_request(dc_req_spec, by=by, reason="rule_unfound") # cancel orphan requests orphan_requests = self._get_orphan_requests() if orphan_requests: @@ -3446,7 +3448,7 @@ def clean_up_requests( self.cancel_request(dc_req_spec, by=by, reason="orphan") # delete ddm rules of terminated requests of terminated tasks for request_id in done_requests_set | cancelled_requests_set | retired_requests_set: - dc_req_spec = terminated_tasks_requests_map[request_id] + dc_req_spec = request_spec_map[request_id] ddm_rule_id = dc_req_spec.ddm_rule_id if ddm_rule_id: try: