diff --git a/pandaserver/api/v1/task_api.py b/pandaserver/api/v1/task_api.py index bb4452f17..da87ecc14 100644 --- a/pandaserver/api/v1/task_api.py +++ b/pandaserver/api/v1/task_api.py @@ -18,8 +18,10 @@ get_fqan, has_production_role, log_task_commands, + parse_utc_time, request_validation, ) +from pandaserver.config import panda_config from pandaserver.srvcore.CoreUtils import clean_user_id, make_reassign_comment from pandaserver.srvcore.panda_request import PandaRequest from pandaserver.taskbuffer import task_split_rules @@ -33,6 +35,9 @@ # only push a None check onto every handler without making any of them safer. global_task_buffer: TaskBuffer = None # type: ignore[assignment] +# most rows one get_job_rows or get_dataset_rows call returns. A task with more is cut there, and the answer says so +MAX_TASK_ROWS = 1000 + def init_task_buffer(task_buffer: TaskBuffer) -> None: """ @@ -1073,6 +1078,149 @@ def get_command_history(req: PandaRequest, task_id: int) -> dict[str, Any]: return generate_response(True, data=data) +@request_validation(_logger, secure=True, request_method="GET") +def get_job_rows(req: PandaRequest, task_id: int, since: str | None = None, after_panda_id: int | None = None) -> dict[str, Any]: + """ + Get the job rows of a task + + Gets the rows of the jobs of a task from jobsDefined4, jobsActive4, jobsArchived4 and the archive, with their number by + status. Requires a secure connection. + + jobsArchived4 and the archive are partitioned by day and by a few days on modificationTime, and the task is looked up + once in each of their partitions a window touches. The window starts at since, or at the creation of the task without + since, and ends at the database time. Both ends are moved out by 10 minutes for the clocks of the servers and then to + whole UTC days. A task that is not found and is given no since is read without a start, in every partition. A call + that would look up more partitions than the db_read_probe_budget of the server allows is refused, not cut short; a + later since lets it fit. + + The rows of all four tables are read by one statement, so a job moving between tables meanwhile is read once, and a + row the same in two tables is given once. The counts are read by a second statement, so a job that changes its status + in between may be counted under its new status. + + A task with more jobs than one call returns is read in pages: ask the next page with after_panda_id set to the last + PandaID of the page before, with the same since, until a page is not truncated. The pages are ordered over all four + tables, so a job moving between tables from one page to the next is still read once. + + API details: + HTTP Method: GET + Path: /v1/task/get_job_rows + + Args: + req(PandaRequest): internally generated request object + task_id(int): JEDI Task ID + since(str, optional): read the jobs modified at or after this time from jobsArchived4 and the archive, in UTC, + e.g. `2026-10-12 14:30:45` (ISO 8601 is accepted). Defaults to the creation of the task + after_panda_id(int, optional): return only the jobs with a larger PandaID, for the next page. Defaults to from the first + + Returns: + dict: The system response `{"success": success, "message": message, "data": data}`. + + Response data: + dict: The jobs of the task, and what tells how complete they are. + {"rows": [...], "truncated": bool, "max_rows": int, "after_panda_id": int or None, "counts": {str: int}, + "as_of": datetime, "since": datetime or None, "until": datetime, "retained_from": datetime or None, + "partitions": int, "probes": int, "budget": int} + - rows: one dict per job, ordered by PandaID and starting after after_panda_id, with PandaID, jobStatus, + jobSubStatus, creationTime, modificationTime, stateChangeTime, endTime, prodSourceLabel, currentPriority, + computingSite and attemptNr + - truncated, max_rows: whether the rows were cut at max_rows, the most a call returns; when cut, the next + page starts after the last PandaID of rows + - after_panda_id: the one given, or None + - counts: the number of jobs by jobStatus, every job in the window counted, whatever page this is and however + many rows were cut + - as_of: database time in UTC taken before the rows were read + - since, until: the window read on jobsArchived4 and the archive, after the widening. since is None when it + has no start + - retained_from: time from which the archive holds every row, or None when it cannot be told. Old partitions + are dropped, so jobs of a task older than this may be missing + - partitions, probes, budget: the partitions of the two tables the window touches, each table counted as at + least 1, the index lookups of the call, two for each table or partition, and the db_read_probe_budget + On failure, with the reason in the message, the reason as values: + - None: task_id is not an integer + - {"rejected": "invalid_window"}: since is not a time + - {"rejected": "probe_budget", "probes": int, "partitions": int, "budget": int}: the lookups exceed the budget + - {"error": str}: the database failed, with the error code (ORA-xxxxx, or the SQLSTATE on Postgres) + """ + tmp_logger = LogWrapper(_logger, f"get_job_rows < task_id={task_id} since={since} after_panda_id={after_panda_id} >") + tmp_logger.debug("Start") + + try: + task_id = int(task_id) + except ValueError: + tmp_logger.error("Failed due to invalid task_id") + return generate_response(False, message=MESSAGE_TASK_ID) + + since_time: datetime.datetime | None = None + if since: + try: + since_time = parse_utc_time(since) + except ValueError as e: + message = f"invalid since: {e}" + tmp_logger.debug(message) + return generate_response(False, message=message, data={"rejected": "invalid_window"}) + + success, message, data = global_task_buffer.get_task_job_rows(task_id, since_time, panda_config.db_read_probe_budget, MAX_TASK_ROWS, after_panda_id) + if not success: + tmp_logger.debug(f"Failed with {message}") + return generate_response(False, message=message, data=data) + + tmp_logger.debug(f"""Done with {len(data["rows"])} rows""") + return generate_response(True, data=data) + + +@request_validation(_logger, secure=True, request_method="GET") +def get_dataset_rows(req: PandaRequest, task_id: int, after_dataset_id: int | None = None) -> dict[str, Any]: + """ + Get the dataset rows of a task + + Gets the rows JEDI_Datasets holds for a task, with every column. Requires a secure connection. + + A task with more datasets than one call returns is read in pages: ask the next page with after_dataset_id set to the + last datasetID of the page before, until a page is not truncated. + + API details: + HTTP Method: GET + Path: /v1/task/get_dataset_rows + + Args: + req(PandaRequest): internally generated request object + task_id(int): JEDI Task ID + after_dataset_id(int, optional): return only the datasets with a larger datasetID, for the next page. Defaults to + from the first + + Returns: + dict: The system response `{"success": success, "message": message, "data": data}`. + + Response data: + dict: The datasets of the task. + {"rows": [...], "truncated": bool, "max_rows": int, "as_of": datetime} + - rows: one dict per dataset, ordered by datasetID and starting after after_dataset_id, with every column keyed + as JediDatasetSpec names it (jediTaskID, datasetID, datasetName, type, masterID, status, nFiles, ...), and + None for NULL. A task that is not found has none + - truncated, max_rows: whether the rows were cut at max_rows, the most a call returns; when cut, the next + page starts after the last datasetID of rows + - as_of: database time in UTC taken before the rows of this page were read + On failure, with the reason in the message: {"error": str} when the database failed, with the error code (ORA-xxxxx, + or the SQLSTATE on Postgres), and None otherwise. + """ + tmp_logger = LogWrapper(_logger, f"get_dataset_rows < task_id={task_id} after_dataset_id={after_dataset_id} >") + tmp_logger.debug("Start") + + try: + task_id = int(task_id) + except ValueError: + tmp_logger.error("Failed due to invalid task_id") + return generate_response(False, message=MESSAGE_TASK_ID) + + success, message, data = global_task_buffer.get_task_dataset_rows(task_id, MAX_TASK_ROWS, after_dataset_id) + if not success: + tmp_logger.debug(f"Failed with {message}") + return generate_response(False, message=message, data=data) + + tmp_logger.debug(f"""Done with {len(data["rows"])} rows""") + return generate_response(True, data=data) + + @request_validation(_logger, request_method="GET", secure=True) def get_details(req: PandaRequest, task_id: int, include_parameters: bool = False, include_status: bool = False) -> dict[str, Any]: """ diff --git a/pandaserver/api/v1/tests/task_api_tests.py b/pandaserver/api/v1/tests/task_api_tests.py index 649b78875..114acc712 100644 --- a/pandaserver/api/v1/tests/task_api_tests.py +++ b/pandaserver/api/v1/tests/task_api_tests.py @@ -296,6 +296,106 @@ def test_get_status_history(self) -> None: for row in output["data"]["rows"]: self.assertEqual(row["jediTaskID"], int(JEDI_TASK_ID)) + def test_get_job_rows(self) -> None: + url = f"{api_url_ssl}/task/get_job_rows" + print(f"Testing URL: {url}") + # a window of a few days fits the budget also where jobsArchived4 keeps years of daily partitions + since = (datetime.utcnow() - timedelta(days=3)).strftime("%Y-%m-%d %H:%M:%S") + data = {"task_id": JEDI_TASK_ID, "since": since} + status, output = self.http_client.get(url, data) + print(output) + self.assertEqual(status, 0) + self.assertTrue(output["success"]) + keys = {"rows", "truncated", "max_rows", "after_panda_id", "counts", "as_of", "since", "until", "retained_from", "partitions", "probes", "budget"} + self.assertEqual(set(output["data"]), keys) + self.assertIsNotNone(output["data"]["since"]) + self.assertLessEqual(output["data"]["probes"], output["data"]["budget"]) + columns = { + "PandaID", + "jobStatus", + "jobSubStatus", + "creationTime", + "modificationTime", + "stateChangeTime", + "endTime", + "prodSourceLabel", + "currentPriority", + "computingSite", + "attemptNr", + } + for row in output["data"]["rows"]: + self.assertEqual(set(row), columns) + if JEDI_TASK_ID == -1: + self.assertEqual(output["data"]["rows"], []) + self.assertEqual(output["data"]["counts"], {}) + + def test_get_job_rows_page(self) -> None: + url = f"{api_url_ssl}/task/get_job_rows" + print(f"Testing URL: {url}") + since = (datetime.utcnow() - timedelta(days=3)).strftime("%Y-%m-%d %H:%M:%S") + data = {"task_id": JEDI_TASK_ID, "since": since, "after_panda_id": 1} + status, output = self.http_client.get(url, data) + print(output) + self.assertEqual(status, 0) + self.assertTrue(output["success"]) + self.assertEqual(output["data"]["after_panda_id"], 1) + for row in output["data"]["rows"]: + self.assertGreater(row["PandaID"], 1) + + def test_get_job_rows_default_window(self) -> None: + url = f"{api_url_ssl}/task/get_job_rows" + print(f"Testing URL: {url}") + data = {"task_id": JEDI_TASK_ID} + status, output = self.http_client.get(url, data) + print(output) + self.assertEqual(status, 0) + if JEDI_TASK_ID == -1: + # an unknown task is read without a window, which the budget may refuse + if output["success"]: + self.assertIsNone(output["data"]["since"]) + else: + self.assertEqual(output["data"]["rejected"], "probe_budget") + else: + self.assertTrue(output["success"]) + self.assertIsNotNone(output["data"]["since"]) + + def test_get_job_rows_invalid_since(self) -> None: + url = f"{api_url_ssl}/task/get_job_rows" + print(f"Testing URL: {url}") + data = {"task_id": JEDI_TASK_ID, "since": "yesterday"} + status, output = self.http_client.get(url, data) + print(output) + self.assertEqual(status, 0) + self.assertFalse(output["success"]) + self.assertEqual(output["data"], {"rejected": "invalid_window"}) + + def test_get_dataset_rows(self) -> None: + url = f"{api_url_ssl}/task/get_dataset_rows" + print(f"Testing URL: {url}") + data = {"task_id": JEDI_TASK_ID} + status, output = self.http_client.get(url, data) + print(output) + self.assertEqual(status, 0) + self.assertTrue(output["success"]) + self.assertEqual(set(output["data"]), {"rows", "truncated", "max_rows", "as_of"}) + if JEDI_TASK_ID == -1: + self.assertEqual(output["data"]["rows"], []) + for row in output["data"]["rows"]: + self.assertEqual(row["jediTaskID"], int(JEDI_TASK_ID)) + self.assertIn("masterID", row) + + def test_get_dataset_rows_page(self) -> None: + url = f"{api_url_ssl}/task/get_dataset_rows" + print(f"Testing URL: {url}") + data = {"task_id": JEDI_TASK_ID, "after_dataset_id": 1} + status, output = self.http_client.get(url, data) + print(output) + self.assertEqual(status, 0) + self.assertTrue(output["success"]) + self.assertEqual(set(output["data"]), {"rows", "truncated", "max_rows", "as_of"}) + for row in output["data"]["rows"]: + self.assertGreater(row["datasetID"], 1) + def test_get_command_history(self) -> None: url = f"{api_url_ssl}/task/get_command_history" print(f"Testing URL: {url}") diff --git a/pandaserver/asyncprocess/db_read/compose.py b/pandaserver/asyncprocess/db_read/compose.py index 0e3faab9b..cff67b856 100644 --- a/pandaserver/asyncprocess/db_read/compose.py +++ b/pandaserver/asyncprocess/db_read/compose.py @@ -141,8 +141,6 @@ def bind(value: Any) -> str: order = [f"{expression_of.get(key.name) or _identifier(key.name)}{' DESC' if key.descending else ''}" for key in query.order_by] sql += " ORDER BY " + ",".join(order) # each clause starts with a space, which is what keeps a bind variable ending the one before apart from it - if backend == "postgres": - sql += f" LIMIT {query.limit + 1}" - else: - sql += f" FETCH FIRST {query.limit + 1} ROWS ONLY" + # standard SQL that Oracle and Postgres both take as it is + sql += f" FETCH FIRST {query.limit + 1} ROWS ONLY" return Statement(sql + STATEMENT_COMMENT, binds, tuple(names), query.limit) diff --git a/pandaserver/asyncprocess/tests/db_read_tests.py b/pandaserver/asyncprocess/tests/db_read_tests.py index a80162759..4fb4c4831 100644 --- a/pandaserver/asyncprocess/tests/db_read_tests.py +++ b/pandaserver/asyncprocess/tests/db_read_tests.py @@ -348,7 +348,7 @@ def test_grouped(self) -> None: self.assertEqual(oracle.names, ("jobstatus", "hour(modificationtime)", "count(*)", "min(pandaid)")) (postgres,) = self.compose(raw, "postgres") self.assertIn("date_trunc('hour',modificationtime)", postgres.sql) - self.assertTrue(postgres.sql.endswith(" LIMIT 1001" + STATEMENT_COMMENT)) + self.assertTrue(postgres.sql.endswith(" FETCH FIRST 1001 ROWS ONLY" + STATEMENT_COMMENT)) def test_postgres_conversion(self) -> None: # what WrappedCursor makes of the statement: one %s per bind variable, in order, and nothing else touched @@ -368,7 +368,7 @@ def test_postgres_conversion(self) -> None: sql, "SELECT date_trunc('day',modificationtime),COUNT(*) FROM ATLAS_PANDA.jobsActive4 " "WHERE pandaid IN (%s,%s) AND computingsite LIKE %s ESCAPE '!' AND modificationtime < %s " - "GROUP BY date_trunc('day',modificationtime) LIMIT 1001" + STATEMENT_COMMENT, + "GROUP BY date_trunc('day',modificationtime) FETCH FIRST 1001 ROWS ONLY" + STATEMENT_COMMENT, ) self.assertEqual(params, [[1, 2, "CERN!_1!%%", D0]]) diff --git a/pandaserver/taskbuffer/TaskBuffer.py b/pandaserver/taskbuffer/TaskBuffer.py index 2c863c5f7..774654fd7 100755 --- a/pandaserver/taskbuffer/TaskBuffer.py +++ b/pandaserver/taskbuffer/TaskBuffer.py @@ -2088,6 +2088,18 @@ def get_task_command_history(self, jedi_task_id: int) -> tuple[bool, str, dict[s with self.proxyPool.get() as proxy: return proxy.get_task_command_history(jedi_task_id) + # get the rows of the jobs of a task and their number by status + def get_task_job_rows( + self, jedi_task_id: int, since: datetime.datetime | None, probe_budget: int, max_rows: int, after_panda_id: int | None = None + ) -> tuple[bool, str, dict[str, Any]]: + with self.proxyPool.get() as proxy: + return proxy.get_task_job_rows(jedi_task_id, since, probe_budget, max_rows, after_panda_id) + + # get the rows of the datasets of a task + def get_task_dataset_rows(self, jedi_task_id: int, max_rows: int, after_dataset_id: int | None = None) -> tuple[bool, str, dict[str, Any]]: + with self.proxyPool.get() as proxy: + return proxy.get_task_dataset_rows(jedi_task_id, max_rows, after_dataset_id) + # reactivate task def reactivateTask(self, jediTaskID: int, keep_attempt_nr: bool = False, trigger_job_generation: bool = False) -> tuple[int | None, str]: with self.proxyPool.get() as proxy: diff --git a/pandaserver/taskbuffer/db_proxy_mods/task_standalone_module.py b/pandaserver/taskbuffer/db_proxy_mods/task_standalone_module.py index 2cb56a7e3..960e0bd53 100644 --- a/pandaserver/taskbuffer/db_proxy_mods/task_standalone_module.py +++ b/pandaserver/taskbuffer/db_proxy_mods/task_standalone_module.py @@ -33,6 +33,54 @@ from pandaserver.taskbuffer.JediTaskSpec import JediTaskSpec, is_msg_driven from pandaserver.taskbuffer.WorkQueue import WorkQueue +# columns of the jobs get_task_job_rows reads, spelled as in JobSpec +TASK_JOB_ROW_COLUMNS = ( + "PandaID", + "jobStatus", + "jobSubStatus", + "creationTime", + "modificationTime", + "stateChangeTime", + "endTime", + "prodSourceLabel", + "currentPriority", + "computingSite", + "attemptNr", +) + +# slack put on both ends of the window of get_task_job_rows before they are moved to whole UTC days. The +# creation of a task and the modificationTime of a job are written with the clock of a server, and the end +# of the window is the database time, so a job may have been modified a little before the task was made, +# by their clocks, or a little after the database time +TASK_JOB_ROWS_CLOCK_SLACK = datetime.timedelta(minutes=10) + + +def floor_to_day(time_stamp: datetime.datetime) -> datetime.datetime: + """ + Get the start of the day of a time. + + Args: + time_stamp(datetime): the time + + Returns: + datetime: midnight at the start of its day + """ + return time_stamp.replace(hour=0, minute=0, second=0, microsecond=0) + + +def ceil_to_day(time_stamp: datetime.datetime) -> datetime.datetime: + """ + Get the start of the day after a time, or the time itself when it is midnight. + + Args: + time_stamp(datetime): the time + + Returns: + datetime: the first midnight at or after the time + """ + floored = floor_to_day(time_stamp) + return floored if floored == time_stamp else floored + datetime.timedelta(days=1) + # Module class to define isolated task related methods class TaskStandaloneModule(BaseModule): @@ -5437,3 +5485,196 @@ def get_task_command_history(self, jedi_task_id: int) -> tuple[bool, str, dict[s self.dump_error_message(tmp_log) err_code = get_db_error_code(e) return False, f"database error {err_code}", {"error": err_code} + + # get the rows of the jobs of a task from the job tables and the archive + def get_task_job_rows( + self, jedi_task_id: int, since: datetime.datetime | None, probe_budget: int, max_rows: int, after_panda_id: int | None = None + ) -> tuple[bool, str, dict[str, Any]]: + """ + Get the rows of the jobs of a task in jobsDefined4, jobsActive4, jobsArchived4 and the archive (jobsArchived of + the archive schema), and their number by jobStatus. + + jobsArchived4 and the archive are partitioned on modificationTime and their jediTaskID indexes are local, so the + task is looked up once in each of their partitions that the window touches. The window is read on those two + tables only. It starts at since, or at the creation of the task when since is None, less a slack for the clocks + and down to the start of the day, and has no start when there is neither. It ends at the start of the day after + the database time plus the slack, which leaves out the partitions made ahead. A request costing more index + lookups than the budget is refused rather than cut short. + + The rows of every table are read by one statement, so a job moving between tables while it runs is read once, + and a row the same in two tables is given once. The counts are read by a second statement, so a job changing + its status between the two may be counted under its new status. + + A task with more jobs than max_rows is read in pages: each next page is asked with after_panda_id set to the + last PandaID of the page before, until a page is not truncated. The pages are ordered over all the tables, so + a job moving between tables from one page to the next is still read once. + + Args: + jedi_task_id(int): jediTaskID of the task + since(datetime): read the jobs modified at or after this time from jobsArchived4 and the archive, or None + for from the creation of the task + probe_budget(int): most index lookups the request may cost + max_rows(int): most rows to return + after_panda_id(int): return only the jobs with a larger PandaID, or None for from the first + + Returns: + bool: True if the rows were read + str: why not, when they were not + dict: when read, {"rows": [dict, ...], "truncated": bool, "max_rows": int, "after_panda_id": int or None, + "counts": {jobStatus: int}, "as_of": datetime, "since": datetime or None, "until": datetime, + "retained_from": datetime or None, "partitions": int, "probes": int, "budget": int}. rows are + ordered by PandaID with the columns in TASK_JOB_ROW_COLUMNS, start after after_panda_id, and are cut + at max_rows when truncated. counts hold every job in the window, whatever after_panda_id is and + however many rows were cut. as_of is the database time in UTC taken before the rows were read. + since and until are the window read. retained_from is the time from which the archive holds + every row. partitions is the number of partitions of the two tables the window touches, each table + counted as at least 1, and probes is the index lookups of both statements. When refused, + {"rejected": "probe_budget", "probes": int, "partitions": int, "budget": int}, and on a database + error {"error": } + """ + comment = " /* DBProxy.get_task_job_rows */" + tmp_log = self.create_tagged_logger(comment, f"jediTaskID={jedi_task_id} since={since} after_panda_id={after_panda_id}") + tmp_log.debug("start") + live_tables = [f"{panda_config.schemaPANDA}.jobsDefined4", f"{panda_config.schemaPANDA}.jobsActive4"] + archive_table = (panda_config.schemaPANDAARCH, "jobsArchived") + windowed_tables = [(panda_config.schemaPANDA, "jobsArchived4"), archive_table] + try: + self.conn.begin() + as_of = self.get_db_utc_now() + var_map: dict[str, Any] = {":jediTaskID": jedi_task_id} + if since is None: + self.cur.execute(f"SELECT creationDate FROM {panda_config.schemaJEDI}.JEDI_Tasks WHERE jediTaskID=:jediTaskID " + comment, var_map) + res = self.cur.fetchone() + if res is not None and res[0] is not None: + since = res[0] + window_start = floor_to_day(since - TASK_JOB_ROWS_CLOCK_SLACK) if since is not None else None + window_end = ceil_to_day(as_of + TASK_JOB_ROWS_CLOCK_SLACK) + # each table is looked up at least once, also when the window touches none of its partitions + n_partitions = 0 + retained_from = None + for owner, table_name in windowed_tables: + n_touched, table_retained_from = self.get_partition_window(owner, table_name, window_start, window_end) + n_partitions += max(n_touched, 1) + # jobs leave jobsArchived4 for the archive, so only the archive tells what is kept + if (owner, table_name) == archive_table: + retained_from = table_retained_from + # the rows and the counts each look up every table once + n_probes = 2 * (len(live_tables) + n_partitions) + if n_probes > probe_budget: + if not self._commit(): + raise RuntimeError("Commit error") + err_msg = f"2 statements x {len(live_tables) + n_partitions} lookups = {n_probes} index lookups exceed the budget of {probe_budget}" + tmp_log.debug(f"refused since {err_msg}") + return False, err_msg, {"rejected": "probe_budget", "probes": n_probes, "partitions": n_partitions, "budget": probe_budget} + # the conditions on the partition key are what lets the database skip partitions + window = "AND modificationTime<:until " + var_map[":until"] = window_end + if window_start is not None: + window += "AND modificationTime>=:since " + var_map[":since"] = window_start + tables = [(table, "") for table in live_tables] + [(f"{owner}.{table_name}", window) for owner, table_name in windowed_tables] + + def union(columns: str, page: str = "") -> str: + return "UNION ".join(f"SELECT {columns} FROM {table} WHERE jediTaskID=:jediTaskID {condition}{page}" for table, condition in tables) + + # a page is put on each table, where the index can start from it, and the counts take none + page = "" + rows_var_map = dict(var_map) + if after_panda_id is not None: + page = "AND PandaID>:after_panda_id " + rows_var_map[":after_panda_id"] = after_panda_id + columns = ",".join(TASK_JOB_ROW_COLUMNS) + sql = f"SELECT {columns} FROM ({union(columns, page)}) tmp_union ORDER BY PandaID " + # one row more than returned tells whether there are more + sql += f"FETCH FIRST {max_rows + 1} ROWS ONLY " + start_time = time.monotonic() + self.cur.arraysize = max_rows + 1 + self.cur.execute(sql + comment, rows_var_map) + res = self.cur.fetchall() + rows_time = time.monotonic() - start_time + truncated = len(res) > max_rows + rows = [dict(zip(TASK_JOB_ROW_COLUMNS, row)) for row in res[:max_rows]] + sql = f"SELECT jobStatus,COUNT(*) FROM ({union('PandaID,jobStatus')}) tmp_union GROUP BY jobStatus " + start_time = time.monotonic() + self.cur.execute(sql + comment, var_map) + counts = {job_status: int(n_jobs) for job_status, n_jobs in self.cur.fetchall()} + counts_time = time.monotonic() - start_time + if not self._commit(): + raise RuntimeError("Commit error") + tmp_log.debug( + f"done with {len(rows)} rows (truncated={truncated}) in {rows_time:.3f} sec and {sum(counts.values())} jobs counted " + f"in {counts_time:.3f} sec by {n_probes} index lookups" + ) + data = { + "rows": rows, + "truncated": truncated, + "max_rows": max_rows, + "after_panda_id": after_panda_id, + "counts": counts, + "as_of": as_of, + "since": window_start, + "until": window_end, + "retained_from": retained_from, + "partitions": n_partitions, + "probes": n_probes, + "budget": probe_budget, + } + return True, "", data + except Exception as e: + self._rollback() + self.dump_error_message(tmp_log) + err_code = get_db_error_code(e) + return False, f"database error {err_code}", {"error": err_code} + + # get the rows of the datasets of a task from JEDI_Datasets + def get_task_dataset_rows(self, jedi_task_id: int, max_rows: int, after_dataset_id: int | None = None) -> tuple[bool, str, dict[str, Any]]: + """ + Get the rows JEDI_Datasets holds for a task. + + A task with more datasets than max_rows is read in pages: each next page is asked with after_dataset_id set to + the last datasetID of the page before, until a page is not truncated. + + Args: + jedi_task_id(int): jediTaskID of the task + max_rows(int): most rows to return + after_dataset_id(int): return only the datasets with a larger datasetID, or None for from the first + + Returns: + bool: True if the rows were read + str: why not, when they were not + dict: when read, {"rows": [dict, ...], "truncated": bool, "max_rows": int, "as_of": datetime}. rows are + ordered by datasetID, with every column keyed as JediDatasetSpec names it, start after after_dataset_id, + and are cut at max_rows when truncated. as_of is the database time in UTC taken before the rows were read. On a database error, + {"error": } + """ + comment = " /* DBProxy.get_task_dataset_rows */" + tmp_log = self.create_tagged_logger(comment, f"jediTaskID={jedi_task_id} after_dataset_id={after_dataset_id}") + tmp_log.debug("start") + columns = JediDatasetSpec.columnNames().split(",") + try: + self.conn.begin() + as_of = self.get_db_utc_now() + var_map: dict[str, Any] = {":jediTaskID": jedi_task_id} + sql = f"SELECT {','.join(columns)} FROM {panda_config.schemaJEDI}.JEDI_Datasets WHERE jediTaskID=:jediTaskID " + if after_dataset_id is not None: + sql += "AND datasetID>:after_dataset_id " + var_map[":after_dataset_id"] = after_dataset_id + sql += "ORDER BY datasetID " + # one row more than returned tells whether there are more + sql += f"FETCH FIRST {max_rows + 1} ROWS ONLY " + start_time = time.monotonic() + self.cur.arraysize = max_rows + 1 + self.cur.execute(sql + comment, var_map) + res = self.cur.fetchall() + elapsed = time.monotonic() - start_time + if not self._commit(): + raise RuntimeError("Commit error") + truncated = len(res) > max_rows + rows = [dict(zip(columns, row)) for row in res[:max_rows]] + tmp_log.debug(f"done with {len(rows)} rows (truncated={truncated}) in {elapsed:.3f} sec") + return True, "", {"rows": rows, "truncated": truncated, "max_rows": max_rows, "as_of": as_of} + except Exception as e: + self._rollback() + self.dump_error_message(tmp_log) + err_code = get_db_error_code(e) + return False, f"database error {err_code}", {"error": err_code} diff --git a/pandaserver/taskbuffer/tests/task_rows_tests.py b/pandaserver/taskbuffer/tests/task_rows_tests.py new file mode 100644 index 000000000..1bc081281 --- /dev/null +++ b/pandaserver/taskbuffer/tests/task_rows_tests.py @@ -0,0 +1,247 @@ +# Description: Unit tests for the reads of the job and dataset rows of a task. No database is used +import datetime +import unittest +from typing import Any +from unittest import mock + +from pandaserver.taskbuffer.db_proxy_mods.task_standalone_module import ( + TASK_JOB_ROW_COLUMNS, + TaskStandaloneModule, + ceil_to_day, + floor_to_day, +) +from pandaserver.taskbuffer.JediDatasetSpec import JediDatasetSpec +from pandaserver.taskbuffer.WrappedCursor import convert_query_in_printf_format + +AS_OF = datetime.datetime(2026, 11, 18, 9, 0, 0) +ARCHIVE_RETAINED_FROM = datetime.datetime(2024, 1, 1) + + +class TestDayBounds(unittest.TestCase): + def test_floor(self) -> None: + self.assertEqual(floor_to_day(datetime.datetime(2026, 11, 9, 23, 55, 1, 5)), datetime.datetime(2026, 11, 9)) + self.assertEqual(floor_to_day(datetime.datetime(2026, 11, 9)), datetime.datetime(2026, 11, 9)) + + def test_ceil(self) -> None: + self.assertEqual(ceil_to_day(datetime.datetime(2026, 11, 18, 0, 0, 0, 1)), datetime.datetime(2026, 11, 19)) + self.assertEqual(ceil_to_day(datetime.datetime(2026, 11, 18)), datetime.datetime(2026, 11, 18)) + + +class TestGetTaskJobRows(unittest.TestCase): + def setUp(self) -> None: + self.proxy = mock.MagicMock() + self.proxy.backend = "oracle" + self.proxy.get_db_utc_now.return_value = AS_OF + self.proxy._commit.return_value = True + self.partitions = {"jobsArchived4": 3, "jobsArchived": 2} + + def partition_window( + owner: str, table_name: str, since: datetime.datetime | None, until: datetime.datetime | None + ) -> tuple[int, datetime.datetime | None]: + return self.partitions[table_name], ARCHIVE_RETAINED_FROM if table_name == "jobsArchived" else None + + self.proxy.get_partition_window.side_effect = partition_window + # the task was made 5 minutes after midnight, so the slack moves the window into the day before + self.proxy.cur.fetchone.return_value = (datetime.datetime(2026, 11, 10, 0, 5, 0),) + self.job_row = tuple(f"value of {column}" for column in TASK_JOB_ROW_COLUMNS) + self.proxy.cur.fetchall.side_effect = [[self.job_row], [("finished", 7), ("running", 2)]] + + def statements(self) -> list[tuple[str, dict[str, Any]]]: + return [call.args for call in self.proxy.cur.execute.call_args_list] + + def test_window_from_task_creation(self) -> None: + success, message, data = TaskStandaloneModule.get_task_job_rows(self.proxy, 123, None, 1000, 1000) + self.assertTrue(success, message) + since, until = datetime.datetime(2026, 11, 9), datetime.datetime(2026, 11, 19) + self.assertEqual( + data, + { + "rows": [dict(zip(TASK_JOB_ROW_COLUMNS, self.job_row))], + "truncated": False, + "max_rows": 1000, + "after_panda_id": None, + "counts": {"finished": 7, "running": 2}, + "as_of": AS_OF, + "since": since, + "until": until, + "retained_from": ARCHIVE_RETAINED_FROM, + "partitions": 5, + "probes": 2 * (2 + 5), + "budget": 1000, + }, + ) + self.assertEqual( + [call.args for call in self.proxy.get_partition_window.call_args_list], + [("ATLAS_PANDA", "jobsArchived4", since, until), ("ATLAS_PANDAARCH", "jobsArchived", since, until)], + ) + (task_sql, task_vars), (rows_sql, rows_vars), (counts_sql, counts_vars) = self.statements() + self.assertIn("SELECT creationDate FROM ATLAS_PANDA.JEDI_Tasks WHERE jediTaskID=:jediTaskID", task_sql) + self.assertEqual(rows_vars, {":jediTaskID": 123, ":since": since, ":until": until}) + self.assertEqual(counts_vars, rows_vars) + for sql in (rows_sql, counts_sql): + for table in ("ATLAS_PANDA.jobsDefined4", "ATLAS_PANDA.jobsActive4", "ATLAS_PANDA.jobsArchived4", "ATLAS_PANDAARCH.jobsArchived"): + self.assertIn(f"FROM {table} WHERE jediTaskID=:jediTaskID", sql) + self.assertEqual(sql.count("UNION "), 3) + self.assertNotIn("UNION ALL", sql) + # the window is put on the two partitioned tables only + self.assertEqual(sql.count("modificationTime>=:since"), 2) + self.assertEqual(sql.count("modificationTime<:until"), 2) + self.assertIn("ORDER BY PandaID FETCH FIRST 1001 ROWS ONLY", rows_sql) + self.assertIn("SELECT jobStatus,COUNT(*) FROM (SELECT PandaID,jobStatus FROM", counts_sql) + self.assertIn("GROUP BY jobStatus", counts_sql) + + def test_page(self) -> None: + success, message, data = TaskStandaloneModule.get_task_job_rows(self.proxy, 123, None, 1000, 1000, after_panda_id=500) + self.assertTrue(success, message) + self.assertEqual(data["after_panda_id"], 500) + (_, _), (rows_sql, rows_vars), (counts_sql, counts_vars) = self.statements() + # the page is put on every table of the rows, and the counts still take every job in the window + self.assertEqual(rows_sql.count("PandaID>:after_panda_id"), 4) + self.assertEqual(rows_vars[":after_panda_id"], 500) + self.assertNotIn("after_panda_id", counts_sql) + self.assertNotIn(":after_panda_id", counts_vars) + self.assertEqual(data["counts"], {"finished": 7, "running": 2}) + + def test_since_given(self) -> None: + success, message, data = TaskStandaloneModule.get_task_job_rows(self.proxy, 123, datetime.datetime(2026, 11, 12, 8, 0, 0), 1000, 1000) + self.assertTrue(success, message) + self.assertEqual(data["since"], datetime.datetime(2026, 11, 12)) + # the task is not read when since is given + self.assertEqual(len(self.statements()), 2) + self.assertNotIn("JEDI_Tasks", self.statements()[0][0]) + + def test_task_not_found(self) -> None: + self.proxy.cur.fetchone.return_value = None + success, message, data = TaskStandaloneModule.get_task_job_rows(self.proxy, 123, None, 1000, 1000) + self.assertTrue(success, message) + self.assertIsNone(data["since"]) + self.assertIsNone(self.proxy.get_partition_window.call_args_list[0].args[2]) + rows_sql, rows_vars = self.statements()[1] + self.assertNotIn(":since", rows_vars) + self.assertNotIn("modificationTime>=", rows_sql) + self.assertEqual(rows_sql.count("modificationTime<:until"), 2) + + def test_until_near_midnight(self) -> None: + self.proxy.get_db_utc_now.return_value = datetime.datetime(2026, 11, 18, 23, 55, 0) + success, message, data = TaskStandaloneModule.get_task_job_rows(self.proxy, 123, None, 1000, 1000) + self.assertTrue(success, message) + self.assertEqual(data["until"], datetime.datetime(2026, 11, 20)) + + def test_no_partition_counted_as_one(self) -> None: + self.partitions = {"jobsArchived4": 0, "jobsArchived": 0} + success, message, data = TaskStandaloneModule.get_task_job_rows(self.proxy, 123, None, 1000, 1000) + self.assertTrue(success, message) + self.assertEqual((data["partitions"], data["probes"]), (2, 8)) + + def test_over_budget(self) -> None: + self.partitions = {"jobsArchived4": 300, "jobsArchived": 300} + success, message, data = TaskStandaloneModule.get_task_job_rows(self.proxy, 123, None, 1000, 1000) + self.assertFalse(success) + self.assertEqual(data, {"rejected": "probe_budget", "probes": 2 * (2 + 600), "partitions": 600, "budget": 1000}) + # only the task was read + self.assertEqual(len(self.statements()), 1) + self.proxy._commit.assert_called_once() + + def test_truncated(self) -> None: + rows = [tuple([panda_id] + [None] * (len(TASK_JOB_ROW_COLUMNS) - 1)) for panda_id in (1, 2, 3)] + self.proxy.cur.fetchall.side_effect = [rows, [("finished", 3)]] + success, message, data = TaskStandaloneModule.get_task_job_rows(self.proxy, 123, None, 1000, 2) + self.assertTrue(success, message) + self.assertTrue(data["truncated"]) + self.assertEqual([row["PandaID"] for row in data["rows"]], [1, 2]) + self.assertEqual(data["counts"], {"finished": 3}) + self.assertIn("FETCH FIRST 3 ROWS ONLY", self.statements()[1][0]) + + def test_postgres_limit(self) -> None: + self.proxy.backend = "postgres" + success, message, data = TaskStandaloneModule.get_task_job_rows(self.proxy, 123, None, 1000, 1000) + self.assertTrue(success, message) + rows_sql = self.statements()[1][0] + self.assertIn("ORDER BY PandaID FETCH FIRST 1001 ROWS ONLY", rows_sql) + + def test_database_error(self) -> None: + self.proxy.cur.fetchall.side_effect = Exception("ORA-01013: user requested cancel of current operation") + success, message, data = TaskStandaloneModule.get_task_job_rows(self.proxy, 123, None, 1000, 1000) + self.assertEqual((success, data), (False, {"error": "ORA-01013"})) + self.proxy._rollback.assert_called_once() + + +class TestGetTaskDatasetRows(unittest.TestCase): + def setUp(self) -> None: + self.proxy = mock.MagicMock() + self.proxy.backend = "oracle" + self.proxy.get_db_utc_now.return_value = AS_OF + self.proxy._commit.return_value = True + self.columns = JediDatasetSpec.columnNames().split(",") + + def test_rows(self) -> None: + row = tuple(f"value of {column}" for column in self.columns) + self.proxy.cur.fetchall.return_value = [row] + success, message, data = TaskStandaloneModule.get_task_dataset_rows(self.proxy, 123, 1000) + self.assertTrue(success, message) + self.assertEqual(data, {"rows": [dict(zip(self.columns, row))], "truncated": False, "max_rows": 1000, "as_of": AS_OF}) + for column in ("jediTaskID", "datasetID", "masterID", "type", "status", "nFiles"): + self.assertIn(column, data["rows"][0]) + sql, var_map = self.proxy.cur.execute.call_args.args + self.assertIn("FROM ATLAS_PANDA.JEDI_Datasets WHERE jediTaskID=:jediTaskID ORDER BY datasetID FETCH FIRST 1001 ROWS ONLY", sql) + self.assertEqual(var_map, {":jediTaskID": 123}) + + def test_truncated(self) -> None: + self.proxy.cur.fetchall.return_value = [tuple([dataset_id] + [None] * (len(self.columns) - 1)) for dataset_id in (11, 12, 13)] + success, message, data = TaskStandaloneModule.get_task_dataset_rows(self.proxy, 123, 2) + self.assertTrue(success, message) + self.assertTrue(data["truncated"]) + self.assertEqual([row["jediTaskID"] for row in data["rows"]], [11, 12]) + + def dataset_rows(self, *dataset_ids: int) -> list[tuple[Any, ...]]: + index = self.columns.index("datasetID") + return [tuple(dataset_id if i == index else None for i in range(len(self.columns))) for dataset_id in dataset_ids] + + def test_first_page(self) -> None: + self.proxy.cur.fetchall.return_value = self.dataset_rows(11, 12, 13) + success, message, data = TaskStandaloneModule.get_task_dataset_rows(self.proxy, 123, 2) + self.assertTrue(success, message) + self.assertEqual(set(data), {"rows", "truncated", "max_rows", "as_of"}) + self.assertTrue(data["truncated"]) + self.assertEqual([row["datasetID"] for row in data["rows"]], [11, 12]) + sql, var_map = self.proxy.cur.execute.call_args.args + self.assertNotIn("after_dataset_id", sql) + self.assertEqual(var_map, {":jediTaskID": 123}) + + def test_later_page(self) -> None: + self.proxy.cur.fetchall.return_value = self.dataset_rows(13, 14, 15) + success, message, data = TaskStandaloneModule.get_task_dataset_rows(self.proxy, 123, 2, after_dataset_id=12) + self.assertTrue(success, message) + self.assertEqual(set(data), {"rows", "truncated", "max_rows", "as_of"}) + self.assertTrue(data["truncated"]) + self.assertEqual([row["datasetID"] for row in data["rows"]], [13, 14]) + sql, var_map = self.proxy.cur.execute.call_args.args + self.assertIn("WHERE jediTaskID=:jediTaskID AND datasetID>:after_dataset_id ORDER BY datasetID FETCH FIRST 3 ROWS ONLY", sql) + self.assertEqual(var_map, {":jediTaskID": 123, ":after_dataset_id": 12}) + + def test_last_page(self) -> None: + self.proxy.cur.fetchall.return_value = self.dataset_rows(15) + success, message, data = TaskStandaloneModule.get_task_dataset_rows(self.proxy, 123, 2, after_dataset_id=14) + self.assertTrue(success, message) + self.assertFalse(data["truncated"]) + self.assertEqual([row["datasetID"] for row in data["rows"]], [15]) + + def test_page_on_postgres(self) -> None: + # what WrappedCursor makes of the page on Postgres: the binds in order, and FETCH FIRST left as it is + self.proxy.backend = "postgres" + self.proxy.cur.fetchall.return_value = [] + success, message, data = TaskStandaloneModule.get_task_dataset_rows(self.proxy, 123, 1000, after_dataset_id=12) + self.assertTrue(success, message) + statement, var_map = self.proxy.cur.execute.call_args.args + sql, params = convert_query_in_printf_format(statement, [var_map], {}) + self.assertIn("WHERE jediTaskID=%s AND datasetID>%s ORDER BY datasetID FETCH FIRST 1001 ROWS ONLY", sql) + self.assertEqual(params, [[123, 12]]) + + def test_database_error(self) -> None: + self.proxy.cur.execute.side_effect = Exception("ORA-00942: table or view does not exist") + success, message, data = TaskStandaloneModule.get_task_dataset_rows(self.proxy, 123, 1000) + self.assertEqual((success, data), (False, {"error": "ORA-00942"})) + + +if __name__ == "__main__": + unittest.main()