File indexing completed on 2026-12-02 10:28:07
0001 """
0002 Offline check of how a native workflow's brokerage anchor is computed and stored.
0003
0004 The anchor is what lets a step with no input of its own learn where the rest of its workflow has
0005 to run. Two properties matter beyond the arithmetic, and both are the kind that only show up in
0006 production: it has to exist before the first step submits a task, and storing it must not clobber
0007 what the engine writes to the same JSON column.
0008
0009 Run from the repository root: python3 pandajedi/jedidog/tests/workflow_anchor_test.py
0010 """
0011
0012 import datetime
0013 import importlib.abc
0014 import importlib.machinery
0015 import json
0016 import os
0017 import sys
0018 import types
0019 import warnings
0020 from typing import Any
0021
0022 warnings.filterwarnings("ignore", category=SyntaxWarning)
0023
0024 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..")))
0025
0026 AUTO_STUB_ROOTS = ("pandacommon", "idds", "pandaclient", "ruamel", "requests", "rucio", "numpy")
0027
0028
0029 class AutoStubFinder(importlib.abc.MetaPathFinder, importlib.abc.Loader):
0030 def find_spec(self, name, path=None, target=None):
0031 if name.split(".")[0] in AUTO_STUB_ROOTS:
0032 return importlib.machinery.ModuleSpec(name, self, is_package=True)
0033 return None
0034
0035 def create_module(self, spec):
0036 module = types.ModuleType(spec.name)
0037 module.__path__ = []
0038 return module
0039
0040 def exec_module(self, module):
0041 class Anything:
0042 def __init__(self, *a, **k):
0043 pass
0044
0045 def __call__(self, *a, **k):
0046 return self
0047
0048 module.__getattr__ = lambda name: Anything
0049
0050
0051 sys.meta_path.insert(0, AutoStubFinder())
0052
0053
0054 def stub(name, **attrs):
0055 module = types.ModuleType(name)
0056 for key, value in attrs.items():
0057 setattr(module, key, value)
0058 sys.modules[name] = module
0059 return module
0060
0061
0062 class Log:
0063 def __getattr__(self, name):
0064 return lambda *a, **k: None
0065
0066
0067 stub("pandacommon.pandalogger").__path__ = []
0068 stub("pandacommon.pandalogger.PandaLogger", PandaLogger=lambda *a, **k: types.SimpleNamespace(getLogger=lambda n: Log()))
0069 stub("pandacommon.pandautils").__path__ = []
0070 stub("pandacommon.pandautils.base", SpecBase=object)
0071 stub("pandacommon.pandautils.PandaUtils", naive_utcnow=datetime.datetime.utcnow, get_sql_IN_bind_variables=lambda *a, **k: (None, None))
0072
0073
0074 class _AnyConfig:
0075 """Answers any attribute, so importing a module that reads a cfg file does not need one"""
0076
0077 def __getattr__(self, name):
0078 return _AnyConfig()
0079
0080 def __bool__(self):
0081 return False
0082
0083
0084 stub("pandaserver.config", panda_config=_AnyConfig())
0085 stub("pandajedi.jediconfig", jedi_config=_AnyConfig())
0086
0087 from pandajedi.jedibrokerage.workflow_affinity import (
0088 WORKFLOW_ANCHOR_PARAM,
0089 build_anchor_weights,
0090 )
0091
0092
0093 class FakeWorkflowSpec:
0094 """A workflow row, with the parameters column behaving as the real spec's does"""
0095
0096 def __init__(self, workflow_id, parameters=None):
0097 self.workflow_id = workflow_id
0098 self.status = "running"
0099 self.parameters = json.dumps(parameters) if parameters else None
0100
0101 def get_parameter(self, name):
0102 return json.loads(self.parameters).get(name) if self.parameters else None
0103
0104 def set_parameter(self, name, value):
0105 parameter_map = json.loads(self.parameters) if self.parameters else {}
0106 parameter_map[name] = value
0107 self.parameters = json.dumps(parameter_map)
0108
0109
0110 def check(label, condition, detail=""):
0111 print(f" {'PASS' if condition else 'FAIL'} {label}{' ' + str(detail) if detail and not condition else ''}")
0112 return condition
0113
0114
0115 def main():
0116 failures = 0
0117
0118 print("\n=== the motivating workflow ===")
0119
0120
0121 anchor = build_anchor_weights(input_sites=["SITE_A"])
0122 failures += not check("the site holding a sibling's input is an anchor", anchor == {"SITE_A": 1.0}, anchor)
0123 failures += not check("...before anything has run", "SITE_A" in anchor)
0124
0125 print("\n=== a step that has already run pulls harder than a prediction ===")
0126 anchor = build_anchor_weights(output_sites=["SITE_B"], input_sites=["SITE_A"])
0127 failures += not check("where output already sits outweighs where input might go", anchor["SITE_B"] > anchor["SITE_A"], anchor)
0128
0129 print("\n=== a pinned sibling is the strongest signal ===")
0130 anchor = build_anchor_weights(pinned_sites=["SITE_P"], output_sites=["SITE_B"], input_sites=["SITE_A"])
0131 failures += not check("the pinned site leads", max(anchor.items(), key=lambda item: item[1])[0] == "SITE_P", anchor)
0132
0133 print("\n=== a workflow nothing is known about has no anchor ===")
0134 failures += not check("empty in, empty out", build_anchor_weights() == {})
0135 failures += not check("...and an empty anchor is not stored", not build_anchor_weights(input_sites=[]))
0136
0137 print("\n=== storing the anchor keeps what the engine wrote ===")
0138
0139
0140
0141 spec = FakeWorkflowSpec(1, {"steps_final_time": "2026-11-05T09:00:00", "fail_reason": "step x failed"})
0142 spec.set_parameter(WORKFLOW_ANCHOR_PARAM, {"weights": {"SITE_A": 1.0}, "computed_at": "2026-11-05T10:00:00"})
0143 failures += not check("the engine's grace timestamp survives", spec.get_parameter("steps_final_time") == "2026-11-05T09:00:00")
0144 failures += not check("so does its failure reason", spec.get_parameter("fail_reason") == "step x failed")
0145 failures += not check("and the anchor is there", spec.get_parameter(WORKFLOW_ANCHOR_PARAM)["weights"] == {"SITE_A": 1.0})
0146
0147 print("\n=== a stale copy is what would lose them ===")
0148
0149
0150 engine_view = FakeWorkflowSpec(2, {"steps_final_time": "2026-11-05T09:00:00"})
0151 stale_copy = FakeWorkflowSpec(2, {})
0152 stale_copy.set_parameter(WORKFLOW_ANCHOR_PARAM, {"weights": {"SITE_A": 1.0}})
0153 failures += not check(
0154 "a blob written from a stale read drops the engine's key",
0155 stale_copy.get_parameter("steps_final_time") is None and engine_view.get_parameter("steps_final_time") is not None,
0156 )
0157
0158 print("\n=== freshness decides whether the lookups are repeated ===")
0159 from pandajedi.jedidog import AtlasWorkflowManagerWatchDog as wd
0160
0161 watchdog = wd.AtlasWorkflowManagerWatchDog.__new__(wd.AtlasWorkflowManagerWatchDog)
0162 now = datetime.datetime.utcnow()
0163 failures += not check("a workflow with no anchor is never fresh", not watchdog.anchor_is_fresh(FakeWorkflowSpec(3)))
0164 failures += not check(
0165 "...nor one whose anchor has no timestamp",
0166 not watchdog.anchor_is_fresh(FakeWorkflowSpec(3, {WORKFLOW_ANCHOR_PARAM: {"weights": {"A": 1}}})),
0167 )
0168 just_now = FakeWorkflowSpec(3, {WORKFLOW_ANCHOR_PARAM: {"weights": {"A": 1}, "computed_at": now.isoformat()}})
0169 failures += not check("one just computed is fresh", watchdog.anchor_is_fresh(just_now))
0170 old = now - datetime.timedelta(seconds=wd.ANCHOR_REFRESH_SEC + 60)
0171 aged = FakeWorkflowSpec(3, {WORKFLOW_ANCHOR_PARAM: {"weights": {"A": 1}, "computed_at": old.isoformat()}})
0172 failures += not check("an aged one is recomputed", not watchdog.anchor_is_fresh(aged))
0173 broken = FakeWorkflowSpec(3, {WORKFLOW_ANCHOR_PARAM: {"weights": {"A": 1}, "computed_at": "not-a-time"}})
0174 failures += not check("an unparsable timestamp is recomputed rather than trusted", not watchdog.anchor_is_fresh(broken))
0175
0176 print("\n=== replica lookups go through the per-VO DDM client ===")
0177
0178
0179
0180 vo_client = object()
0181
0182 class FakeDDMInterface:
0183 def getInterface(self, vo, group=None):
0184 return vo_client if vo == "atlas" else None
0185
0186 received: dict[str, Any] = {}
0187
0188 def fake_get_sites_with_data(site_list, site_mapper, ddm_if, dataset_name, *args):
0189 received["ddm_if"] = ddm_if
0190 return wd.Interaction.SC_SUCCEEDED, {"SITE_A": {}}
0191
0192 def fake_sites_with_disk(data_site_map, includeTape=False):
0193 return list(data_site_map)
0194
0195
0196 stand_in: Any = watchdog
0197 broker_utils: Any = wd.AtlasBrokerUtils
0198 stand_in.ddmIF = FakeDDMInterface()
0199 stand_in.vo = "atlas"
0200 original = (broker_utils.get_sites_with_data, broker_utils.getAnalSitesWithDataDisk)
0201 broker_utils.get_sites_with_data = fake_get_sites_with_data
0202 broker_utils.getAnalSitesWithDataDisk = fake_sites_with_disk
0203 try:
0204 sites = stand_in.sites_holding_dataset(["SITE_A"], None, "some:dataset", Log())
0205 finally:
0206 broker_utils.get_sites_with_data, broker_utils.getAnalSitesWithDataDisk = original
0207 failures += not check("the per-VO client is what reaches the lookup", received.get("ddm_if") is vo_client, received)
0208 failures += not check("...and its answer comes back", sites == ["SITE_A"], sites)
0209
0210 print("\n=== workflow 148: the free step waits for the data-bound ones ===")
0211
0212
0213
0214
0215 from pandaserver.taskbuffer.JediTaskSpec import (
0216 WORKFLOW_HOLDUP_BROKERAGE,
0217 JediTaskSpec,
0218 )
0219
0220 def step(step_id, name, inputs, outputs, task_id=None, takes_input=True, status="running"):
0221 job_params = [{"param_type": "input", "dataset": "x"}] if takes_input else []
0222 definition = {"task_params": {"jobParameters": job_params}, "input_data_dict": {i: {} for i in inputs}, "output_data_list": outputs}
0223 return types.SimpleNamespace(
0224 step_id=step_id, name=name, flavor="panda_task", status=status, target_id=str(task_id) if task_id else None, definition_json_map=definition
0225 )
0226
0227 def task(task_id, status="running", split_rule=None):
0228 task_spec = JediTaskSpec()
0229 task_spec.jediTaskID = task_id
0230 task_spec.status = status
0231 task_spec.site = None
0232 task_spec.splitRule = split_rule
0233 return task_spec
0234
0235 class FakeTaskBuffer:
0236 def __init__(self, steps, tasks, output_sites):
0237 self.steps, self.tasks, self.output_sites = steps, tasks, output_sites
0238 self.events = []
0239 self.workflow = FakeWorkflowSpec(148)
0240
0241 def get_steps_of_workflow(self, workflow_id):
0242 return self.steps
0243
0244 def get_data_of_workflow(self, workflow_id, type_filter_list=None):
0245 return [types.SimpleNamespace(name="signal", target_id="ds:signal"), types.SimpleNamespace(name="background", target_id="ds:background/")]
0246
0247 def get_site_mapper(self):
0248 return types.SimpleNamespace(siteSpecList={}, getSite=lambda name: types.SimpleNamespace(get_unified_name=lambda: name))
0249
0250 def getTaskWithID_JEDI(self, task_id, *args):
0251 return True, self.tasks[task_id]
0252
0253 def getDatasetsWithJediTaskID_JEDI(self, task_id, types_):
0254
0255 return True, [types.SimpleNamespace(site=site) for site in self.output_sites.get(task_id, [])]
0256
0257 def getConfigValue(self, *args, **kwargs):
0258 return True
0259
0260 def query_workflows(self, **kwargs):
0261 return [self.workflow]
0262
0263 def update_workflow(self, workflow_spec):
0264 self.events.append("store anchor")
0265
0266 def updateTask_JEDI(self, task_spec, criteria, *args, **kwargs):
0267 self.events.append(f"update {task_spec.jediTaskID} {task_spec.splitRule}")
0268
0269 def release_task_on_hold(self, task_id):
0270 self.events.append(f"release {task_id}")
0271 return True
0272
0273 def push_task_trigger_message(self, msg_type, task_id):
0274 self.events.append(f"trigger {msg_type} {task_id}")
0275
0276 class FakeWorkflowInterface:
0277 def __init__(self, tbif, locked=False):
0278 self.tbif, self.locked = tbif, locked
0279
0280 def workflow_lock(self, workflow_id):
0281 import contextlib
0282
0283 @contextlib.contextmanager
0284 def lock():
0285 yield None if self.locked else self.tbif.workflow
0286
0287 return lock()
0288
0289 def run_pass(tbif, locked=False):
0290 dog: Any = wd.AtlasWorkflowManagerWatchDog.__new__(wd.AtlasWorkflowManagerWatchDog)
0291 dog.taskBufferIF = tbif
0292 dog.vo = "atlas"
0293 dog.workflow_interface = FakeWorkflowInterface(tbif, locked)
0294 dog.get_process_lock = lambda *a, **k: True
0295 replicas = {"ds:signal": ["CERN-T0", "CERN"], "ds:background/": ["CERN-T0", "CERN", "INFN-CNAF"]}
0296 dog.sites_holding_dataset = lambda analysis_sites, site_mapper, dataset_name, log: replicas[dataset_name]
0297 dog.doComputeWorkflowAnchors()
0298 return dog
0299
0300 def workflow_148(background_placed):
0301 steps = [
0302 step(1, "make_signal", ["signal"], ["make_signal/outDS"], task_id=101),
0303 step(2, "make_background_1", ["background"], ["make_background_1/outDS"], task_id=102),
0304 step(3, "generate_some", [], ["generate_some/outDS"], task_id=103, takes_input=False),
0305 step(4, "premix", ["make_signal/outDS", "make_background_1/outDS"], ["premix/outDS"], status="registered"),
0306 step(5, "make_background_2", ["background", "generate_some/outDS"], ["make_background_2/outDS"], status="registered"),
0307 ]
0308 tasks = {101: task(101), 102: task(102), 103: task(103, status="pending", split_rule=f"WH={WORKFLOW_HOLDUP_BROKERAGE},NG=3")}
0309 output_sites = {101: ["CERN-T0", "CERN-T0"]}
0310 if background_placed:
0311 output_sites[102] = ["CERN-T0", "CERN-T0"]
0312 return FakeTaskBuffer(steps, tasks, output_sites)
0313
0314 tbif = workflow_148(background_placed=False)
0315 dog = run_pass(tbif)
0316 anchor_inputs, holdup = dog.gather_anchor_inputs(148, Log())
0317 failures += not check("only make_background_1 is waited for", holdup["unplaced_bound_step_ids"] == [2], holdup["unplaced_bound_step_ids"])
0318 failures += not check("generate_some is the held task", [t.jediTaskID for t in holdup["held_task_specs"]] == [103])
0319 failures += not check("the workflow is unsettled", holdup["unsettled"] is True)
0320 failures += not check("an outDS and a log at one site count as one step there", anchor_inputs["output_sites"] == ["CERN-T0"], anchor_inputs["output_sites"])
0321
0322 failures += not check(
0323 "an unplaced submitted step still contributes its input sites",
0324 anchor_inputs["input_sites"].count("INFN-CNAF") == 2,
0325 anchor_inputs["input_sites"],
0326 )
0327 failures += not check("the anchor is stored", "store anchor" in tbif.events, tbif.events)
0328 failures += not check("nothing is released while a bound step is unplaced", not any(e.startswith("release") for e in tbif.events), tbif.events)
0329 stored = tbif.workflow.get_parameter(WORKFLOW_ANCHOR_PARAM)
0330 failures += not check("an unsettled anchor is never fresh, so the next pass looks again", not dog.anchor_is_fresh(tbif.workflow), stored)
0331
0332 print("\n=== ...and is released once they are placed ===")
0333 tbif = workflow_148(background_placed=True)
0334 run_pass(tbif)
0335 failures += not check("the held task is released", "release 103" in tbif.events, tbif.events)
0336 failures += not check(
0337 "the anchor is stored before anything is released",
0338 "store anchor" in tbif.events and tbif.events.index("store anchor") < tbif.events.index("release 103"),
0339 tbif.events,
0340 )
0341 failures += not check("the brokerage bit is cleared and the rest of the rule kept", "update 103 NG=3" in tbif.events, tbif.events)
0342 failures += not check("the contents feeder is triggered", "trigger jedi_contents_feeder 103" in tbif.events, tbif.events)
0343 weights = tbif.workflow.get_parameter(WORKFLOW_ANCHOR_PARAM)["weights"]
0344 failures += not check("the anchor names where the bound steps went", max(weights, key=weights.get) == "CERN-T0", weights)
0345
0346 print("\n=== a workflow the engine holds is neither anchored nor released ===")
0347
0348 tbif = workflow_148(background_placed=True)
0349 run_pass(tbif, locked=True)
0350 failures += not check("nothing released when the anchor could not be stored", not any(e.startswith("release") for e in tbif.events), tbif.events)
0351
0352 print("\n=== the hold expires with the regular pending cycle ===")
0353 from pandajedi.jedibrokerage.workflow_affinity import brokerage_holdup_expired
0354
0355 created = datetime.datetime(2026, 11, 16, 10, 0)
0356 failures += not check("a first feed minutes after creation still holds", not brokerage_holdup_expired(created, created + datetime.timedelta(minutes=3), 60))
0357 failures += not check("a feed after the pending reactivation lets go", brokerage_holdup_expired(created, created + datetime.timedelta(minutes=61), 60))
0358 failures += not check("no creation time never holds for ever", brokerage_holdup_expired(None, created, 60))
0359
0360 print("\n=== the pass runs before the workflows are processed ===")
0361
0362
0363 import inspect
0364
0365 source = inspect.getsource(wd.AtlasWorkflowManagerWatchDog.doAction)
0366 failures += not check(
0367 "doComputeWorkflowAnchors is called before doProcessWorkflows",
0368 source.index("doComputeWorkflowAnchors") < source.index("doProcessWorkflows"),
0369 source,
0370 )
0371
0372 print(f"\n{'ALL CHECKS PASSED' if not failures else f'{failures} CHECK(S) FAILED'}")
0373 return 1 if failures else 0
0374
0375
0376 if __name__ == "__main__":
0377 sys.exit(main())