Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-12-02 10:28:08

0001 """
0002 Offline check of how JobGenerator puts a task on hold when its datasets fail in the job brokerage.
0003 
0004 A dataset which fails waits by itself, marked with its own lastFrozenTime, while the other datasets of
0005 the task are evaluated in the next cycle without waiting. The task is put on hold only when none
0006 of its datasets is left to evaluate, or when the brokerage says the whole task is waiting. The
0007 inputs of one task come with shallow copies of the task spec, which share one map of changed
0008 attributes, so a later input must not write back the stale status its copy holds.
0009 
0010 Run from the repository root:  python3 pandajedi/jediorder/tests/dataset_pending_test.py
0011 """
0012 
0013 import copy
0014 import datetime
0015 import importlib.abc
0016 import importlib.machinery
0017 import os
0018 import sys
0019 import types
0020 import warnings
0021 from typing import Any, cast
0022 
0023 warnings.filterwarnings("ignore", category=SyntaxWarning)
0024 
0025 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..")))
0026 
0027 AUTO_STUB_ROOTS = ("pandacommon", "idds", "pandaclient", "ruamel", "requests", "rucio", "numpy")
0028 
0029 
0030 class AutoStubFinder(importlib.abc.MetaPathFinder, importlib.abc.Loader):
0031     def find_spec(self, name, path=None, target=None):
0032         if name.split(".")[0] in AUTO_STUB_ROOTS:
0033             return importlib.machinery.ModuleSpec(name, self, is_package=True)
0034         return None
0035 
0036     def create_module(self, spec):
0037         module = types.ModuleType(spec.name)
0038         module.__path__ = []
0039         return module
0040 
0041     def exec_module(self, module):
0042         class Anything:
0043             def __init__(self, *a, **k):
0044                 pass
0045 
0046             def __call__(self, *a, **k):
0047                 return self
0048 
0049         module.__getattr__ = lambda name: Anything
0050 
0051 
0052 sys.meta_path.insert(0, AutoStubFinder())
0053 
0054 
0055 def stub(name, **attrs):
0056     module = types.ModuleType(name)
0057     for key, value in attrs.items():
0058         setattr(module, key, value)
0059     sys.modules[name] = module
0060     return module
0061 
0062 
0063 class Log:
0064     def __getattr__(self, name):
0065         return lambda *a, **k: None
0066 
0067 
0068 stub("pandacommon.pandalogger").__path__ = []
0069 stub("pandacommon.pandalogger.PandaLogger", PandaLogger=lambda *a, **k: types.SimpleNamespace(getLogger=lambda n: Log()))
0070 stub("pandacommon.pandautils").__path__ = []
0071 stub("pandacommon.pandautils.base", SpecBase=object)
0072 stub("pandacommon.pandautils.PandaUtils", naive_utcnow=datetime.datetime.utcnow, get_sql_IN_bind_variables=lambda *a, **k: (None, None))
0073 
0074 
0075 class _AnyConfig:
0076     """Answers any attribute, so importing a module that reads a cfg file does not need one"""
0077 
0078     def __getattr__(self, name):
0079         return _AnyConfig()
0080 
0081     def __bool__(self):
0082         return False
0083 
0084 
0085 stub("pandaserver.config", panda_config=_AnyConfig())
0086 stub("pandajedi.jediconfig", jedi_config=_AnyConfig())
0087 
0088 from pandajedi.jedicore import Interaction  # noqa: E402
0089 from pandajedi.jedicore.ThreadUtils import ListWithLock  # noqa: E402
0090 from pandajedi.jediorder import JobGenerator  # noqa: E402
0091 from pandaserver.taskbuffer.JediTaskSpec import JediTaskSpec  # noqa: E402
0092 
0093 TASK_ID = 123
0094 OLD_TIME = datetime.datetime(2026, 1, 1)
0095 
0096 
0097 class ErrorLog(Log):
0098     """Keeps the crashes, since runImpl logs an exception and goes on rather than raising it"""
0099 
0100     def __init__(self):
0101         self.errors = []
0102 
0103     def error(self, msg, *a, **k):
0104         if "crashed" in msg or "failed with" in msg:
0105             self.errors.append(msg)
0106 
0107 
0108 class FakeChunk:
0109     """An input chunk for one master dataset"""
0110 
0111     def __init__(self, dataset_id, is_merging=False, frozen_time=None):
0112         self.masterDataset = types.SimpleNamespace(datasetID=dataset_id, frozenTime=frozen_time)
0113         self.masterIndexName = dataset_id
0114         self.isMerging = is_merging
0115         self.useJumbo = None
0116         self.readBlock = None
0117         self.ramCount = 0
0118 
0119     def hasCandidatesForJumbo(self):
0120         return False
0121 
0122     def useScout(self):
0123         return False
0124 
0125 
0126 class FakeTaskBuffer:
0127     """Records what JobGenerator writes for the task"""
0128 
0129     def __init__(self, n_datasets_to_evaluate, mark_ok):
0130         self.n_datasets_to_evaluate = n_datasets_to_evaluate
0131         self.mark_ok = mark_ok
0132         self.updates = []
0133         self.frozen_calls = []
0134         self.count_calls = []
0135 
0136     def lockTask_JEDI(self, *a, **k):
0137         return True
0138 
0139     def resetUnusedFiles_JEDI(self, *a, **k):
0140         return 0
0141 
0142     def set_dataset_frozen_time_JEDI(self, jedi_task_id, dataset_id, frozen):
0143         self.frozen_calls.append((dataset_id, frozen))
0144         return self.mark_ok
0145 
0146     def count_datasets_to_evaluate_JEDI(self, jedi_task_id, excluded_dataset_ids):
0147         self.count_calls.append(list(excluded_dataset_ids))
0148         return self.n_datasets_to_evaluate
0149 
0150     def updateTask_JEDI(self, task_spec, criteria, **kwargs):
0151         written = {key[1:]: value for key, value in task_spec.valuesMap(onlyChanged=True).items()}
0152         self.updates.append({"status": task_spec.status, "task_old_status": task_spec.oldStatus, "written": written, **kwargs})
0153         return True, 1
0154 
0155     def storeJobs(self, jobs, *a, **k):
0156         return [(str(1000 + i), None) for i in range(len(jobs))], {}, {}
0157 
0158 
0159 def make_broker_class(results):
0160     """A JobBroker answering for each dataset as told"""
0161 
0162     class FakeBrokerCore:
0163         def __getattr__(self, name):
0164             return lambda *a, **k: None
0165 
0166     class FakeJobBroker:
0167         def __init__(self, *a, **k):
0168             pass
0169 
0170         def initializeMods(self, *a, **k):
0171             return True
0172 
0173         def requireImpl(self, *a, **k):
0174             return FakeBrokerCore()
0175 
0176         def getClassName(self, *a, **k):
0177             return "FakeJobBroker"
0178 
0179         def getBaseLockID(self, *a, **k):
0180             return None
0181 
0182         def doBrokerage(self, task_spec, cloud_name, input_chunk, task_param_map):
0183             return results[input_chunk.masterDataset.datasetID], input_chunk
0184 
0185     return FakeJobBroker
0186 
0187 
0188 class FakeSplitter:
0189     def doSplit(self, task_spec, input_chunk, *a, **k):
0190         return Interaction.SC_SUCCEEDED, [{"siteName": "SITE_A", "subChunks": [object()]}], False
0191 
0192 
0193 def run_task(results, n_datasets_to_evaluate=3, status="running", chunks=None, mark_ok=True):
0194     """Run one cycle of JobGenerator for a task whose datasets get the given brokerage results"""
0195     orig_task_spec = JediTaskSpec()
0196     for attr, value in {"jediTaskID": TASK_ID, "vo": "atlas", "prodSourceLabel": "user", "status": status, "frozenTime": OLD_TIME}.items():
0197         object.__setattr__(orig_task_spec, attr, value)
0198     if chunks is None:
0199         chunks = [FakeChunk(dataset_id) for dataset_id in results]
0200     # one shallow copy per dataset, as getTasksToBeProcessed_JEDI makes them
0201     input_list = [(copy.copy(orig_task_spec), "WORLD", chunk) for chunk in chunks]
0202     task_buffer = FakeTaskBuffer(n_datasets_to_evaluate, mark_ok)
0203     error_log = ErrorLog()
0204     JobGenerator.logger = error_log
0205     setattr(JobGenerator, "JobBroker", make_broker_class(results))
0206     setattr(JobGenerator, "JobSplitter", FakeSplitter)
0207     thread = JobGenerator.JobGeneratorThread(
0208         ListWithLock([(TASK_ID, input_list)]),
0209         None,
0210         cast(Any, task_buffer),
0211         cast(Any, types.SimpleNamespace(getInterface=lambda *a, **k: None)),
0212         cast(Any, None),
0213         False,
0214         cast(Any, types.SimpleNamespace(doSetup=lambda *a, **k: Interaction.SC_SUCCEEDED, getClassName=lambda *a, **k: "FakeSetupper")),
0215         "pid",
0216         cast(Any, types.SimpleNamespace(queue_name="queue", VO="atlas", queue_type="analysis")),
0217         "SCORE",
0218         "WORLD",
0219         None,
0220         None,
0221         False,
0222         [],
0223     )
0224     setattr(thread, "doGenerate", lambda *a, **k: (Interaction.SC_SUCCEEDED, [types.SimpleNamespace(computingSite="SITE_A")], {}, [None], {}, {}))
0225     thread.runImpl()
0226     return task_buffer, error_log.errors
0227 
0228 
0229 def check(label, condition, detail=""):
0230     print(f"  {'PASS' if condition else 'FAIL'}  {label}{'  ' + str(detail) if detail and not condition else ''}")
0231     return condition
0232 
0233 
0234 def main():
0235     failures = 0
0236     failed = Interaction.SC_FAILED
0237     succeeded = Interaction.SC_SUCCEEDED
0238 
0239     print("\n=== datasets fail while others are left to evaluate ===")
0240     tb, errors = run_task({1: failed, 2: failed, 3: failed}, n_datasets_to_evaluate=5)
0241     last = tb.updates[-1]
0242     failures += not check("no crash", not errors, errors)
0243     failures += not check("each dataset waits by itself", tb.frozen_calls == [(1, True), (2, True), (3, True)], tb.frozen_calls)
0244     failures += not check("the datasets of this cycle are not counted", tb.count_calls == [[1, 2, 3]], tb.count_calls)
0245     failures += not check("the task is not put on hold", all(u["status"] == "running" for u in tb.updates), [u["status"] for u in tb.updates])
0246     failures += not check("the next cycle comes without waiting", last["setOldModTime"] is True, last)
0247     # also by the updates for the inputs before the last one, or the time would restart every cycle
0248     kept = [u["set_frozen_time_without_pending"] for u in tb.updates]
0249     failures += not check("the time since the task has been failing is kept by every update", all(kept), kept)
0250 
0251     print("\n=== datasets fail and none is left to evaluate ===")
0252     tb, errors = run_task({1: failed, 2: failed}, n_datasets_to_evaluate=0)
0253     last = tb.updates[-1]
0254     failures += not check("no crash", not errors, errors)
0255     failures += not check("the task is put on hold", last["status"] == "pending" and last["task_old_status"] == "running", last)
0256     failures += not check("...only after all inputs are done", tb.updates[0]["status"] == "running", tb.updates[0])
0257     failures += not check("...and waits as a pending task does", last["setOldModTime"] is False, last)
0258 
0259     print("\n=== the datasets cannot be counted ===")
0260     tb, errors = run_task({1: failed}, n_datasets_to_evaluate=None)
0261     failures += not check("the task is put on hold as before", tb.updates[-1]["status"] == "pending", tb.updates[-1])
0262 
0263     print("\n=== a failed dataset cannot be marked ===")
0264     # the next cycle would read the same datasets again at once, so the task waits as a whole as before
0265     tb, errors = run_task({1: failed, 2: failed}, n_datasets_to_evaluate=5, mark_ok=False)
0266     failures += not check("the task is put on hold at once", tb.updates[0]["status"] == "pending", tb.updates[0])
0267     failures += not check("...and stays on hold", tb.updates[-1]["status"] == "pending", tb.updates[-1])
0268 
0269     print("\n=== the brokerage says the whole task is waiting ===")
0270     tb, errors = run_task({1: Interaction.SC_WAITING, 2: failed}, n_datasets_to_evaluate=5)
0271     failures += not check("no crash", not errors, errors)
0272     failures += not check("the task is put on hold at once", tb.updates[0]["status"] == "pending", tb.updates[0])
0273     failures += not check("...without the pending timeout running", tb.updates[0]["setFrozenTime"] is False, tb.updates[0])
0274     failures += not check("...and the waiting dataset is not marked", (1, True) not in tb.frozen_calls, tb.frozen_calls)
0275     failures += not check("...and stays on hold", tb.updates[-1]["status"] == "pending", tb.updates[-1])
0276     failures += not check("no datasets are counted", tb.count_calls == [], tb.count_calls)
0277 
0278     print("\n=== a merging input fails ===")
0279     tb, errors = run_task({1: failed}, chunks=[FakeChunk(1, is_merging=True)])
0280     failures += not check("the task is put on hold as before", tb.updates[-1]["status"] == "pending", tb.updates[-1])
0281     failures += not check("...and the merge dataset is not marked", tb.frozen_calls == [], tb.frozen_calls)
0282 
0283     print("\n=== jobs are submitted for one dataset and another fails ===")
0284     tb, errors = run_task({1: succeeded, 2: failed}, chunks=[FakeChunk(1, frozen_time=OLD_TIME), FakeChunk(2)])
0285     failures += not check("no crash", not errors, errors)
0286     failures += not check("the dataset which failed long ago is evaluated as usual again", (1, False) in tb.frozen_calls, tb.frozen_calls)
0287     failures += not check("the failing dataset waits by itself", (2, True) in tb.frozen_calls, tb.frozen_calls)
0288     failures += not check("no datasets are counted", tb.count_calls == [], tb.count_calls)
0289     failures += not check("the task stays running", tb.updates[-1]["status"] == "running", tb.updates[-1])
0290     failures += not check("...and is not failing any more", tb.updates[-1]["set_frozen_time_without_pending"] is False, tb.updates[-1])
0291 
0292     print("\n=== a later input does not write back the stale status of its copy ===")
0293     # the task starts as ready. The first input submits jobs and the task becomes running, then the second
0294     # input fails. Its copy still holds ready, and the status column is in the shared map of changes
0295     tb, errors = run_task({1: succeeded, 2: failed}, status="ready")
0296     failures += not check("no crash", not errors, errors)
0297     failures += not check("the first input sets running", tb.updates[0]["written"].get("status") == "running", tb.updates[0])
0298     failures += not check("the second input keeps running", tb.updates[-1]["written"].get("status") == "running", tb.updates[-1]["written"])
0299     failures += not check("...and the next cycle comes without waiting", tb.updates[-1]["setOldModTime"] is True, tb.updates[-1])
0300 
0301     print("\n=== jobs are submitted after an earlier input put the task on hold ===")
0302     # the merging input fails and puts the task on hold, then the next input submits jobs
0303     tb, errors = run_task({1: failed, 2: succeeded}, chunks=[FakeChunk(1, is_merging=True), FakeChunk(2)])
0304     failures += not check("no crash", not errors, errors)
0305     failures += not check("the first input puts the task on hold", tb.updates[0]["written"].get("oldStatus") == "running", tb.updates[0])
0306     written = tb.updates[-1]["written"]
0307     failures += not check("the task is running again", written.get("status") == "running", written)
0308     failures += not check("...without keeping the status before the hold", "oldStatus" in written and written["oldStatus"] is None, written)
0309 
0310     print("\n=== a copy takes over what another copy changed ===")
0311     orig_task_spec = JediTaskSpec()
0312     object.__setattr__(orig_task_spec, "status", "ready")
0313     object.__setattr__(orig_task_spec, "frozenTime", OLD_TIME)
0314     first, second = copy.copy(orig_task_spec), copy.copy(orig_task_spec)
0315     first.status = "running"
0316     first.frozenTime = None
0317     failures += not check("the copies share the map of changes", ":status" in second.valuesMap(onlyChanged=True))
0318     failures += not check("...so the stale values would be written", second.valuesMap(onlyChanged=True)[":frozenTime"] == OLD_TIME)
0319     second.take_over_changes(first)
0320     written = second.valuesMap(onlyChanged=True)
0321     failures += not check("the taken over values are written", written[":status"] == "running" and written[":frozenTime"] is None, written)
0322     failures += not check("columns nobody changed are not written", ":taskName" not in written, written)
0323 
0324     print(f"\n{'ALL PASSED' if failures == 0 else f'{failures} FAILED'}")
0325     return failures
0326 
0327 
0328 if __name__ == "__main__":
0329     sys.exit(1 if main() else 0)