diff --git a/pandajedi/jedibrokerage/AtlasAnalJobBroker.py b/pandajedi/jedibrokerage/AtlasAnalJobBroker.py index 531a32ddb..b71dc6478 100644 --- a/pandajedi/jedibrokerage/AtlasAnalJobBroker.py +++ b/pandajedi/jedibrokerage/AtlasAnalJobBroker.py @@ -91,7 +91,7 @@ def get_workflow_anchor_weights(self, taskSpec: JediTaskSpec, sitePreAssigned: b self.set_task_common(cache_key, anchor) weights = (anchor or {}).get("weights") or None if weights: - tmpLog.info(f"workflow_id={workflow_id} anchor: {workflow_affinity.summarize_anchor(anchor)}") + tmpLog.info(f"workflow_id={workflow_id} anchor: {workflow_affinity.summarize_anchor(anchor)} computed_at={(anchor or {}).get('computed_at')}") else: tmpLog.info(f"workflow_id={workflow_id} has no anchor yet") return weights @@ -2374,6 +2374,8 @@ def doBrokerage( f"""nFailed={bw_map["nFailed"]} nClosed={bw_map["nClosed"]} nFinished={bw_map["nFinished"]} """ f"""dataW={tmpDataWeight} totalInGB={totalSize} localInGB={localSize} nFiles={totalNumFiles} """ ) + if anchor_weights: + tmpStr += f"""wfAffW={tmpAffinityWeight:.2f} """ weightStr[tmpPseudoSiteName] = tmpStr # append if tmpSiteName in sitesUsedByTask: diff --git a/pandajedi/jedibrokerage/AtlasBrokerUtils.py b/pandajedi/jedibrokerage/AtlasBrokerUtils.py index ea63f855c..b9a4f23c8 100644 --- a/pandajedi/jedibrokerage/AtlasBrokerUtils.py +++ b/pandajedi/jedibrokerage/AtlasBrokerUtils.py @@ -697,45 +697,32 @@ def getSiteToRunRateStats( # anchor of a native workflow, as the workflow manager recorded it on the workflow -CACHE_WorkflowAnchor: dict[int, dict[str, Any]] = {} -CACHE_WorkflowAnchor_MAX = 1000 - - -def get_workflow_anchor(tbIF: JediTaskBufferInterface, workflow_id: int, cache_lifetime: int = 120) -> dict[str, Any] | None: +def get_workflow_anchor(tbIF: JediTaskBufferInterface, workflow_id: int) -> dict[str, Any] | None: """ - Read a native workflow's brokerage anchor, cached in this process for a short while + Read a native workflow's brokerage anchor - The anchor is already persisted on the workflow, so this needs no shared cache of its own -- - only enough memory to keep brokerage from re-reading the same row for every input chunk of - every task of the workflow, several times a minute. + Read afresh on every call, not cached in the process: the tasks a workflow held back are + released the moment a new anchor is stored, and a cached copy would broker them against the + one from before their siblings were placed. The caller shares one read among the chunks of a + task, so the cost is one primary-key select per workflow task per generation pass. Args: tbIF: task buffer interface workflow_id: the native workflow to read - cache_lifetime: seconds before the local copy is read again Returns: dict | None: the anchor as the workflow manager stored it, or None if there is none yet """ - current_time = naive_utcnow() - cached = CACHE_WorkflowAnchor.get(workflow_id) - if cached is not None and current_time <= cached["exp"]: - cached_anchor: dict[str, Any] | None = cached["data"] - return cached_anchor - anchor: dict[str, Any] | None = None try: workflow_spec = tbIF.get_workflow(workflow_id) if workflow_spec is not None: - anchor = workflow_spec.get_parameter(workflow_affinity.WORKFLOW_ANCHOR_PARAM) + anchor: dict[str, Any] | None = workflow_spec.get_parameter(workflow_affinity.WORKFLOW_ANCHOR_PARAM) + return anchor except Exception: # A preference that cannot be read is not a reason to fail brokerage; the task is simply # brokered as any other would be. - anchor = None - if len(CACHE_WorkflowAnchor) >= CACHE_WorkflowAnchor_MAX: - for expired_key in [key for key, value in CACHE_WorkflowAnchor.items() if current_time > value["exp"]]: - del CACHE_WorkflowAnchor[expired_key] - CACHE_WorkflowAnchor[workflow_id] = {"exp": current_time + datetime.timedelta(seconds=cache_lifetime), "data": anchor} - return anchor + pass + return None # get users jobs stats from various resources diff --git a/pandajedi/jedibrokerage/tests/site_ordering_test.py b/pandajedi/jedibrokerage/tests/workflow_affinity_test.py similarity index 99% rename from pandajedi/jedibrokerage/tests/site_ordering_test.py rename to pandajedi/jedibrokerage/tests/workflow_affinity_test.py index cf15ef326..cc5b2bd62 100644 --- a/pandajedi/jedibrokerage/tests/site_ordering_test.py +++ b/pandajedi/jedibrokerage/tests/workflow_affinity_test.py @@ -7,7 +7,7 @@ never moved to the front. Fixing that changes placement for every analysis task, workflow or not, which is why the non-workflow behaviour is pinned here too. -Run from the repository root: python3 pandajedi/jedibrokerage/tests/site_ordering_test.py +Run from the repository root: python3 pandajedi/jedibrokerage/tests/workflow_affinity_test.py """ import os diff --git a/pandajedi/jedibrokerage/workflow_affinity.py b/pandajedi/jedibrokerage/workflow_affinity.py index 91019a00b..4c8a68560 100644 --- a/pandajedi/jedibrokerage/workflow_affinity.py +++ b/pandajedi/jedibrokerage/workflow_affinity.py @@ -11,6 +11,7 @@ from __future__ import annotations +import datetime import random from typing import Any, Collection, Iterable, Protocol, TypeVar @@ -167,3 +168,27 @@ def summarize_anchor(anchor: dict[str, Any] | None, max_sites: int = 5) -> str: return "no workflow anchor" ranked = sorted(weights.items(), key=lambda item: item[1], reverse=True)[:max_sites] return ", ".join(f"{site}={weight:g}" for site, weight in ranked) + + +def brokerage_holdup_expired(creation_time: datetime.datetime | None, now: datetime.datetime, wait_minutes: float) -> bool: + """ + Whether a task held for its workflow's brokerage has waited long enough to go on regardless + + The hold is a preference, so it must never strand a step whose siblings are stuck. Rather than + a timer of its own, it rides the regular pending cycle: a held task sits in pending, and the + watchdog reactivates pending tasks after waitForPending minutes, sending it back through the + contents feeder. The first feed happens within minutes of creation, so a task older than that + interval can only be on a feed after reactivation -- the point at which to stop holding. + + Args: + creation_time: when the task was created + now: current time + wait_minutes: the pending reactivation interval + + Returns: + bool: True if the hold should be dropped + """ + if creation_time is None: + # nothing to measure against, and holding without bound is the worse failure + return True + return now - creation_time >= datetime.timedelta(minutes=wait_minutes) diff --git a/pandajedi/jedidog/AtlasWorkflowManagerWatchDog.py b/pandajedi/jedidog/AtlasWorkflowManagerWatchDog.py index 49c9b3061..7a6dd5132 100644 --- a/pandajedi/jedidog/AtlasWorkflowManagerWatchDog.py +++ b/pandajedi/jedidog/AtlasWorkflowManagerWatchDog.py @@ -10,7 +10,16 @@ from pandajedi.jedibrokerage import AtlasBrokerUtils, workflow_affinity from pandajedi.jedicore import Interaction from pandajedi.jedicore.MsgWrapper import MsgWrapper -from pandaserver.workflow.workflow_base import WFDataType, WorkflowStatus +from pandaserver.taskbuffer.JediTaskSpec import WORKFLOW_HOLDUP_BROKERAGE, JediTaskSpec +from pandaserver.workflow.step_handler_plugins.panda_task_step_handler import ( + brokerage_bound_steps, + step_task_takes_input, +) +from pandaserver.workflow.workflow_base import ( + WFDataType, + WFStepStatus, + WorkflowStatus, +) from pandaserver.workflow.workflow_core import JEDI_TASK_STEP_FLAVORS, WorkflowInterface from .WatchDogBase import WatchDogBase @@ -38,30 +47,43 @@ def __init__(self, taskBufferIF: "JediTaskBufferInterface", ddmIF: "DDMInterface self.vo = "atlas" self.workflow_interface = WorkflowInterface(taskBufferIF) - def gather_anchor_inputs(self, workflow_id: int, tmpLog: MsgWrapper) -> dict[str, Any]: + def gather_anchor_inputs(self, workflow_id: int, tmpLog: MsgWrapper) -> tuple[dict[str, Any], dict[str, Any]]: """ Collect what is known about where the steps of one workflow are going Three kinds of knowledge, which build_anchor_weights then ranks: a step a submitter pinned, - a step that has already written its output somewhere, and a step not yet submitted whose + a step that has already written its output somewhere, and a step not yet placed whose input sits somewhere. Only root inputs are usable for the last of these -- data produced inside the workflow has no dataset until its producing step runs, which is exactly why an unconstrained step cannot see where it ought to go on its own. + Each source counts once per step, so a step with an output and a log dataset at one site + is one step there, not two. + + Alongside, the state the brokerage holdup needs: which tasks are held, and which of the + data-bound steps they wait for are not yet placed. + Args: workflow_id: the workflow to look at tmpLog: logger of this pass Returns: - dict: lists of unified site names under pinned_sites, output_sites and input_sites, - plus vetoed_sites + tuple: (anchor inputs, holdup state). The first has lists of unified site names under + pinned_sites, output_sites and input_sites, plus vetoed_sites, for + build_anchor_weights. The second has held_task_specs, unplaced_bound_step_ids and + unsettled, the last meaning that a data-free step is still to be brokered. """ pinned_sites: list[str] = [] output_sites: list[str] = [] input_sites: list[str] = [] vetoed_sites: set[str] = set() + held_task_specs: list[Any] = [] + unplaced_bound_step_ids: list[int] = [] + unsettled = False - step_specs = self.taskBufferIF.get_steps_of_workflow(workflow_id) or [] + step_specs = [step_spec for step_spec in (self.taskBufferIF.get_steps_of_workflow(workflow_id) or []) if step_spec.flavor in JEDI_TASK_STEP_FLAVORS] + # classified over all steps, since what one step produces decides whether another is bound + bound_step_ids = {step_spec.step_id for step_spec in brokerage_bound_steps(step_specs)} # the datasets this workflow takes in from outside, by the name the steps refer to them by dataset_of_root_input = { data_spec.name: data_spec.target_id @@ -81,28 +103,43 @@ def unified(site_name: str) -> str | None: replica_cache: dict[str, list[str]] = {} for step_spec in step_specs: - if step_spec.flavor not in JEDI_TASK_STEP_FLAVORS: - continue + is_final = step_spec.status in WFStepStatus.final_statuses + placed = is_final + task_spec = None task_id = int(step_spec.target_id) if str(step_spec.target_id or "").isdigit() else None if task_id: - # A step with a task says where it is; its inputs are history by now. tmp_stat, task_spec = self.taskBufferIF.getTaskWithID_JEDI(task_id, False) - if tmp_stat and task_spec is not None: - if task_spec.site: - for one_site in str(task_spec.site).split(","): - site_name = unified(one_site.strip()) - if site_name: - pinned_sites.append(site_name) - tmp_stat, dataset_specs = self.taskBufferIF.getDatasetsWithJediTaskID_JEDI(task_id, ["output", "log"]) - for dataset_spec in dataset_specs or []: - # an analysis output is instantiated per site, and the site it was - # instantiated for is where the data actually is - site_name = unified(dataset_spec.site) if dataset_spec.site else None - if site_name: - output_sites.append(site_name) + if not tmp_stat: + task_spec = None + if task_spec is not None: + if task_spec.is_workflow_brokerage_holdup(): + held_task_specs.append(task_spec) + unsettled = True + if task_spec.status in JediTaskSpec.statusToRejectExtChange(): + placed = True + # a pinned task is placed before it has run anywhere + step_pinned = {unified(one_site.strip()) for one_site in str(task_spec.site or "").split(",") if one_site.strip()} + step_pinned.discard(None) + if step_pinned: + placed = True + pinned_sites.extend(cast(set[str], step_pinned)) + tmp_stat, dataset_specs = self.taskBufferIF.getDatasetsWithJediTaskID_JEDI(task_id, ["output", "log"]) + # an analysis output is instantiated per site, and the site it was instantiated + # for is where the data actually is + step_outputs = {unified(dataset_spec.site) for dataset_spec in dataset_specs or [] if dataset_spec.site} + step_outputs.discard(None) + if step_outputs: + placed = True + output_sites.extend(cast(set[str], step_outputs)) + elif not is_final and step_task_takes_input(step_spec) is False: + # a data-free step not yet submitted: it will be held on submission + unsettled = True + if step_spec.step_id in bound_step_ids and not placed: + unplaced_bound_step_ids.append(step_spec.step_id) + if placed: continue - # Not submitted yet. Where its root inputs are is the only hint, and it is the one - # that lets a step with no input of its own learn where its siblings must run. + # Not placed yet, submitted or not. Where its root inputs are is the only hint, and it + # is the one that lets a step with no input of its own learn where its siblings must run. for input_name in step_spec.definition_json_map.get("input_data_dict", {}): dataset_name = dataset_of_root_input.get(input_name) if not dataset_name: @@ -111,14 +148,26 @@ def unified(site_name: str) -> str | None: replica_cache[dataset_name] = self.sites_holding_dataset(analysis_sites, site_mapper, dataset_name, tmpLog) input_sites.extend(replica_cache[dataset_name]) - return { + anchor_inputs = { "pinned_sites": pinned_sites, "output_sites": output_sites, "input_sites": input_sites, "vetoed_sites": vetoed_sites, } + holdup_state = { + "held_task_specs": held_task_specs, + "unplaced_bound_step_ids": unplaced_bound_step_ids, + "unsettled": unsettled, + } + return anchor_inputs, holdup_state - def sites_holding_dataset(self, analysis_sites: list[str], site_mapper: Any, dataset_name: str, tmpLog: MsgWrapper) -> list[str]: + def sites_holding_dataset( + self, + analysis_sites: list[str], + site_mapper: Any, + dataset_name: str, + tmpLog: MsgWrapper, + ) -> list[str]: """ The analysis sites holding a dataset on disk, by unified name @@ -126,9 +175,13 @@ def sites_holding_dataset(self, analysis_sites: list[str], site_mapper: Any, dat brokerage would also call local rather than one it would reject. """ try: - # the helper is typed for the brokerage-side interface; a watchdog holds the DDM one, - # which carries the same methods it uses - tmp_stat, data_site_map = AtlasBrokerUtils.get_sites_with_data(analysis_sites, site_mapper, cast(Any, self.ddmIF), dataset_name, None, 10, 100)[:2] + # self.ddmIF is the multi-VO wrapper; the replica methods live on the per-VO client, + # which is what brokerage is handed too + ddm_if = self.ddmIF.getInterface(self.vo) + if ddm_if is None: + tmpLog.debug(f"no DDM interface for vo={self.vo}") + return [] + tmp_stat, data_site_map = AtlasBrokerUtils.get_sites_with_data(analysis_sites, site_mapper, ddm_if, dataset_name, None, 10, 100)[:2] # on any failure the second element is a message rather than the map if tmp_stat != Interaction.SC_SUCCEEDED or not isinstance(data_site_map, dict): tmpLog.debug(f"no replica information for {dataset_name}: {data_site_map}") @@ -146,10 +199,11 @@ def anchor_is_fresh(self, workflow_spec: Any) -> bool: The placement of a workflow changes slowly -- a step has to finish, or a new one has to be submitted -- while the replica lookups behind an anchor are the expensive part of this pass. A workflow with no anchor at all is never fresh, so a newly registered one is always - computed on the cycle it appears. + computed on the cycle it appears. Nor is one whose data-free steps are still to be + brokered: those are waiting on this pass to be released, and it must look every cycle. """ anchor: dict[str, Any] | None = workflow_spec.get_parameter(workflow_affinity.WORKFLOW_ANCHOR_PARAM) - if not anchor or not anchor.get("computed_at"): + if not anchor or not anchor.get("computed_at") or anchor.get("unsettled"): return False try: age = naive_utcnow() - datetime.datetime.fromisoformat(str(anchor["computed_at"])) @@ -157,14 +211,41 @@ def anchor_is_fresh(self, workflow_spec: Any) -> bool: return False return bool(age.total_seconds() < ANCHOR_REFRESH_SEC) + def release_brokerage_holdup(self, task_spec: Any, tmpLog: MsgWrapper) -> bool: + """ + Let a task held for its workflow's brokerage go on to be brokered + + The same steps on_all_inputs_done takes for the input hold, clearing only the brokerage + bit. If the contents feeder holds the task's lock just now, it may write the old rule + back; the task then still shows as held, and the next pass releases it again. + + Returns: + bool: whether the task was released + """ + task_id = task_spec.jediTaskID + task_spec.set_workflow_holdup(False, WORKFLOW_HOLDUP_BROKERAGE) + self.taskBufferIF.updateTask_JEDI(task_spec, {"jediTaskID": task_id}) + if task_spec.status == "pending": + if not self.taskBufferIF.release_task_on_hold(task_id): + tmpLog.warning(f"task_id={task_id} brokerage holdup unset but not released from pending; retried next cycle") + return False + self.taskBufferIF.push_task_trigger_message("jedi_contents_feeder", task_id) + tmpLog.info(f"task_id={task_id} released from brokerage holdup") + return True + def doComputeWorkflowAnchors(self) -> None: """ - Record, on each active workflow, which sites the rest of it is going to + Record, on each active workflow, which sites the rest of it is going to, and release the + data-free steps that were waiting for it Runs before the workflows are processed, because an analysis task is job-generated almost as soon as it is submitted: a small step with no input can be placed in its first pass, and that is exactly the step this preference exists to move. A workflow that first appears during this cycle therefore gets its anchor before any of its steps submits a task. + + A data-free step is held on submission until its data-bound siblings are placed. Once they + are, the anchor stored here already reflects where they went, and the held steps are + released together so that they are brokered back to back against it. """ tmpLog = MsgWrapper(logger, " #ATM #KV doComputeWorkflowAnchors") tmpLog.debug("start") @@ -180,9 +261,16 @@ def doComputeWorkflowAnchors(self) -> None: # cycle must be anchored now, before its first step submits a task. Workflows that # already carry a fresh anchor are skipped below instead, which costs one comparison # rather than the replica lookups. - workflow_specs = self.taskBufferIF.query_workflows(status_filter_list=list(WorkflowStatus.active_statuses), check_interval_sec=0) or [] + workflow_specs = ( + self.taskBufferIF.query_workflows( + status_filter_list=list(WorkflowStatus.active_statuses), + check_interval_sec=0, + ) + or [] + ) n_anchored = 0 n_fresh = 0 + n_released = 0 for queried_spec in workflow_specs: workflow_id = queried_spec.workflow_id try: @@ -190,29 +278,44 @@ def doComputeWorkflowAnchors(self) -> None: n_fresh += 1 continue # the gathering touches the database and DDM, so it is done outside the lock - gathered = self.gather_anchor_inputs(workflow_id, tmpLog) - weights = workflow_affinity.build_anchor_weights(**gathered) - if not weights: - continue - # The lock re-reads the workflow, which matters because parameters is a single - # JSON column the engine also writes: storing against a spec read earlier would - # drop whatever it recorded meanwhile. - with self.workflow_interface.workflow_lock(workflow_id) as workflow_spec: - if workflow_spec is None: - tmpLog.debug(f"workflow_id={workflow_id} locked by the engine; skipped") - continue - if workflow_spec.status not in WorkflowStatus.active_statuses: - continue - workflow_spec.set_parameter( - workflow_affinity.WORKFLOW_ANCHOR_PARAM, - {"weights": weights, "computed_at": naive_utcnow().isoformat()}, - ) - self.taskBufferIF.update_workflow(workflow_spec) - n_anchored += 1 - tmpLog.debug(f"workflow_id={workflow_id} anchor: {workflow_affinity.summarize_anchor({'weights': weights})}") + anchor_inputs, holdup_state = self.gather_anchor_inputs(workflow_id, tmpLog) + weights = workflow_affinity.build_anchor_weights(**anchor_inputs) + if weights: + # The lock re-reads the workflow, which matters because parameters is a + # single JSON column the engine also writes: storing against a spec read + # earlier would drop whatever it recorded meanwhile. + with self.workflow_interface.workflow_lock(workflow_id) as workflow_spec: + if workflow_spec is None: + # nothing is released either: held tasks must see the new anchor + tmpLog.debug(f"workflow_id={workflow_id} locked by the engine; skipped") + continue + if workflow_spec.status not in WorkflowStatus.active_statuses: + continue + workflow_spec.set_parameter( + workflow_affinity.WORKFLOW_ANCHOR_PARAM, + { + "weights": weights, + "computed_at": naive_utcnow().isoformat(), + "unsettled": holdup_state["unsettled"], + }, + ) + self.taskBufferIF.update_workflow(workflow_spec) + n_anchored += 1 + tmpLog.debug(f"workflow_id={workflow_id} anchor: {workflow_affinity.summarize_anchor({'weights': weights})}") + # Release only after the anchor is stored, so the released tasks read the one + # computed from where their siblings actually went. + held_task_specs = holdup_state["held_task_specs"] + if held_task_specs: + unplaced = holdup_state["unplaced_bound_step_ids"] + if unplaced: + tmpLog.debug(f"workflow_id={workflow_id} {len(held_task_specs)} held task(s) wait for data-bound steps {sorted(unplaced)}") + else: + for task_spec in held_task_specs: + if self.release_brokerage_holdup(task_spec, tmpLog): + n_released += 1 except Exception as e: tmpLog.warning(f"failed to anchor workflow_id={workflow_id} with {e}") - tmpLog.info(f"anchored {n_anchored} of {len(workflow_specs)} active workflows, {n_fresh} already fresh") + tmpLog.info(f"anchored {n_anchored} of {len(workflow_specs)} active workflows, {n_fresh} already fresh, released {n_released} held tasks") tmpLog.debug("done") except Exception: errtype, errvalue = sys.exc_info()[:2] diff --git a/pandajedi/jedidog/tests/workflow_anchor_test.py b/pandajedi/jedidog/tests/workflow_anchor_test.py index 8252c642e..78480e0c9 100644 --- a/pandajedi/jedidog/tests/workflow_anchor_test.py +++ b/pandajedi/jedidog/tests/workflow_anchor_test.py @@ -17,6 +17,7 @@ import sys import types import warnings +from typing import Any warnings.filterwarnings("ignore", category=SyntaxWarning) @@ -172,6 +173,190 @@ def main(): broken = FakeWorkflowSpec(3, {WORKFLOW_ANCHOR_PARAM: {"weights": {"A": 1}, "computed_at": "not-a-time"}}) failures += not check("an unparsable timestamp is recomputed rather than trusted", not watchdog.anchor_is_fresh(broken)) + print("\n=== replica lookups go through the per-VO DDM client ===") + # The watchdog is handed the multi-VO DDMInterface wrapper, which has no replica methods of + # its own. Passing it straight through failed every lookup, so a workflow had no input sites + # and therefore no anchor before its steps were submitted. + vo_client = object() + + class FakeDDMInterface: + def getInterface(self, vo, group=None): + return vo_client if vo == "atlas" else None + + received: dict[str, Any] = {} + + def fake_get_sites_with_data(site_list, site_mapper, ddm_if, dataset_name, *args): + received["ddm_if"] = ddm_if + return wd.Interaction.SC_SUCCEEDED, {"SITE_A": {}} + + def fake_sites_with_disk(data_site_map, includeTape=False): + return list(data_site_map) + + # untyped handles, since these stand-ins deliberately do not match the real signatures + stand_in: Any = watchdog + broker_utils: Any = wd.AtlasBrokerUtils + stand_in.ddmIF = FakeDDMInterface() + stand_in.vo = "atlas" + original = (broker_utils.get_sites_with_data, broker_utils.getAnalSitesWithDataDisk) + broker_utils.get_sites_with_data = fake_get_sites_with_data + broker_utils.getAnalSitesWithDataDisk = fake_sites_with_disk + try: + sites = stand_in.sites_holding_dataset(["SITE_A"], None, "some:dataset", Log()) + finally: + broker_utils.get_sites_with_data, broker_utils.getAnalSitesWithDataDisk = original + failures += not check("the per-VO client is what reaches the lookup", received.get("ddm_if") is vo_client, received) + failures += not check("...and its answer comes back", sites == ["SITE_A"], sites) + + print("\n=== workflow 148: the free step waits for the data-bound ones ===") + # The live case. make_signal and make_background_1 read root inputs and are placed by data + # locality; generate_some reads nothing and was brokered before them, against a prediction. + # make_background_2 reads a root input and generate_some's output, so it must not be waited + # for: it waits on generate_some itself. + from pandaserver.taskbuffer.JediTaskSpec import ( + WORKFLOW_HOLDUP_BROKERAGE, + JediTaskSpec, + ) + + def step(step_id, name, inputs, outputs, task_id=None, takes_input=True, status="running"): + job_params = [{"param_type": "input", "dataset": "x"}] if takes_input else [] + definition = {"task_params": {"jobParameters": job_params}, "input_data_dict": {i: {} for i in inputs}, "output_data_list": outputs} + return types.SimpleNamespace( + 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 + ) + + def task(task_id, status="running", split_rule=None): + task_spec = JediTaskSpec() + task_spec.jediTaskID = task_id + task_spec.status = status + task_spec.site = None + task_spec.splitRule = split_rule + return task_spec + + class FakeTaskBuffer: + def __init__(self, steps, tasks, output_sites): + self.steps, self.tasks, self.output_sites = steps, tasks, output_sites + self.events = [] + self.workflow = FakeWorkflowSpec(148) + + def get_steps_of_workflow(self, workflow_id): + return self.steps + + def get_data_of_workflow(self, workflow_id, type_filter_list=None): + return [types.SimpleNamespace(name="signal", target_id="ds:signal"), types.SimpleNamespace(name="background", target_id="ds:background/")] + + def get_site_mapper(self): + return types.SimpleNamespace(siteSpecList={}, getSite=lambda name: types.SimpleNamespace(get_unified_name=lambda: name)) + + def getTaskWithID_JEDI(self, task_id, *args): + return True, self.tasks[task_id] + + def getDatasetsWithJediTaskID_JEDI(self, task_id, types_): + # an outDS and a log dataset at the same site, as analysis instantiates them + return True, [types.SimpleNamespace(site=site) for site in self.output_sites.get(task_id, [])] + + def getConfigValue(self, *args, **kwargs): + return True + + def query_workflows(self, **kwargs): + return [self.workflow] + + def update_workflow(self, workflow_spec): + self.events.append("store anchor") + + def updateTask_JEDI(self, task_spec, criteria, *args, **kwargs): + self.events.append(f"update {task_spec.jediTaskID} {task_spec.splitRule}") + + def release_task_on_hold(self, task_id): + self.events.append(f"release {task_id}") + return True + + def push_task_trigger_message(self, msg_type, task_id): + self.events.append(f"trigger {msg_type} {task_id}") + + class FakeWorkflowInterface: + def __init__(self, tbif, locked=False): + self.tbif, self.locked = tbif, locked + + def workflow_lock(self, workflow_id): + import contextlib + + @contextlib.contextmanager + def lock(): + yield None if self.locked else self.tbif.workflow + + return lock() + + def run_pass(tbif, locked=False): + dog: Any = wd.AtlasWorkflowManagerWatchDog.__new__(wd.AtlasWorkflowManagerWatchDog) + dog.taskBufferIF = tbif + dog.vo = "atlas" + dog.workflow_interface = FakeWorkflowInterface(tbif, locked) + dog.get_process_lock = lambda *a, **k: True + replicas = {"ds:signal": ["CERN-T0", "CERN"], "ds:background/": ["CERN-T0", "CERN", "INFN-CNAF"]} + dog.sites_holding_dataset = lambda analysis_sites, site_mapper, dataset_name, log: replicas[dataset_name] + dog.doComputeWorkflowAnchors() + return dog + + def workflow_148(background_placed): + steps = [ + step(1, "make_signal", ["signal"], ["make_signal/outDS"], task_id=101), + step(2, "make_background_1", ["background"], ["make_background_1/outDS"], task_id=102), + step(3, "generate_some", [], ["generate_some/outDS"], task_id=103, takes_input=False), + step(4, "premix", ["make_signal/outDS", "make_background_1/outDS"], ["premix/outDS"], status="registered"), + step(5, "make_background_2", ["background", "generate_some/outDS"], ["make_background_2/outDS"], status="registered"), + ] + tasks = {101: task(101), 102: task(102), 103: task(103, status="pending", split_rule=f"WH={WORKFLOW_HOLDUP_BROKERAGE},NG=3")} + output_sites = {101: ["CERN-T0", "CERN-T0"]} + if background_placed: + output_sites[102] = ["CERN-T0", "CERN-T0"] + return FakeTaskBuffer(steps, tasks, output_sites) + + tbif = workflow_148(background_placed=False) + dog = run_pass(tbif) + anchor_inputs, holdup = dog.gather_anchor_inputs(148, Log()) + failures += not check("only make_background_1 is waited for", holdup["unplaced_bound_step_ids"] == [2], holdup["unplaced_bound_step_ids"]) + failures += not check("generate_some is the held task", [t.jediTaskID for t in holdup["held_task_specs"]] == [103]) + failures += not check("the workflow is unsettled", holdup["unsettled"] is True) + 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"]) + # a bound step submitted but not yet placed still says where it is going + failures += not check( + "an unplaced submitted step still contributes its input sites", + anchor_inputs["input_sites"].count("INFN-CNAF") == 2, + anchor_inputs["input_sites"], + ) + failures += not check("the anchor is stored", "store anchor" in tbif.events, tbif.events) + failures += not check("nothing is released while a bound step is unplaced", not any(e.startswith("release") for e in tbif.events), tbif.events) + stored = tbif.workflow.get_parameter(WORKFLOW_ANCHOR_PARAM) + failures += not check("an unsettled anchor is never fresh, so the next pass looks again", not dog.anchor_is_fresh(tbif.workflow), stored) + + print("\n=== ...and is released once they are placed ===") + tbif = workflow_148(background_placed=True) + run_pass(tbif) + failures += not check("the held task is released", "release 103" in tbif.events, tbif.events) + failures += not check( + "the anchor is stored before anything is released", + "store anchor" in tbif.events and tbif.events.index("store anchor") < tbif.events.index("release 103"), + tbif.events, + ) + failures += not check("the brokerage bit is cleared and the rest of the rule kept", "update 103 NG=3" in tbif.events, tbif.events) + failures += not check("the contents feeder is triggered", "trigger jedi_contents_feeder 103" in tbif.events, tbif.events) + weights = tbif.workflow.get_parameter(WORKFLOW_ANCHOR_PARAM)["weights"] + failures += not check("the anchor names where the bound steps went", max(weights, key=weights.get) == "CERN-T0", weights) + + print("\n=== a workflow the engine holds is neither anchored nor released ===") + # the released tasks must see the new anchor, so no anchor means no release either + tbif = workflow_148(background_placed=True) + run_pass(tbif, locked=True) + failures += not check("nothing released when the anchor could not be stored", not any(e.startswith("release") for e in tbif.events), tbif.events) + + print("\n=== the hold expires with the regular pending cycle ===") + from pandajedi.jedibrokerage.workflow_affinity import brokerage_holdup_expired + + created = datetime.datetime(2026, 11, 16, 10, 0) + failures += not check("a first feed minutes after creation still holds", not brokerage_holdup_expired(created, created + datetime.timedelta(minutes=3), 60)) + failures += not check("a feed after the pending reactivation lets go", brokerage_holdup_expired(created, created + datetime.timedelta(minutes=61), 60)) + failures += not check("no creation time never holds for ever", brokerage_holdup_expired(None, created, 60)) + print("\n=== the pass runs before the workflows are processed ===") # An analysis task is job-generated almost as soon as it is submitted, so an anchor computed # after the engine advances a workflow would arrive too late for the first step. diff --git a/pandajedi/jediorder/ContentsFeeder.py b/pandajedi/jediorder/ContentsFeeder.py index 051196c6f..c5ee07cbd 100644 --- a/pandajedi/jediorder/ContentsFeeder.py +++ b/pandajedi/jediorder/ContentsFeeder.py @@ -8,6 +8,7 @@ from multiprocessing.connection import Connection from typing import TYPE_CHECKING, Any +from pandajedi.jedibrokerage import workflow_affinity from pandajedi.jediconfig import jedi_config from pandajedi.jedicore import Interaction from pandajedi.jedicore.MsgWrapper import MsgWrapper @@ -15,7 +16,7 @@ from pandajedi.jedicore.ThreadUtils import ListWithLock, ThreadPool, WorkerThread from pandajedi.jedirefine import RefinerUtils from pandaserver.taskbuffer.JediDatasetSpec import JediDatasetSpec -from pandaserver.taskbuffer.JediTaskSpec import JediTaskSpec +from pandaserver.taskbuffer.JediTaskSpec import WORKFLOW_HOLDUP_BROKERAGE, JediTaskSpec from .JediKnight import JediKnight @@ -711,6 +712,17 @@ def feed_contents_to_tasks(self, task_ds_list: list[tuple[int, list[JediDatasetS # hold up by the workflow taskOnHold = True tmpLog.debug("task to hold up by workflow") + # brokerage holdup by the workflow: a step with no input waits for its data-bound + # siblings to be placed, so that it can follow them; it is released by the workflow + # manager watchdog, or let go here once it has been through the regular pending cycle + if not taskOnHold and not taskBroken and taskSpec.is_workflow_brokerage_holdup(): + wait_minutes = getattr(getattr(jedi_config, "watchdog", None), "waitForPending", 60) + if workflow_affinity.brokerage_holdup_expired(taskSpec.creationDate, naive_utcnow(), wait_minutes): + self.expire_brokerage_holdup(taskSpec, tmpLog) + else: + taskOnHold = True + taskSpec.setErrDiag(f"held until the data-bound steps of workflow {taskSpec.get_workflow_id()} are brokered") + tmpLog.info("task to hold up brokerage by workflow") # no master input if not taskOnHold and not taskBroken and allUpdated and nFilesMaster == 0 and checkedMaster: tmpErrStr = "primary input dataset is empty or all files are excluded " @@ -789,6 +801,21 @@ def feed_contents_to_tasks(self, task_ds_list: list[tuple[int, list[JediDatasetS tmpLog.warning("failed to push trigger message to jedi_job_generator") tmpLog.debug("done") + def expire_brokerage_holdup(self, taskSpec: JediTaskSpec, tmpLog: MsgWrapper) -> None: + """ + Drop a task's brokerage holdup for good, leaving any other workflow hold in place + + Written through a spec carrying nothing but the split rule, since updateTask_JEDI writes + every changed attribute and the feeder's own spec is mid-way through being updated. + """ + taskSpec.set_workflow_holdup(False, WORKFLOW_HOLDUP_BROKERAGE) + update_spec = JediTaskSpec() + update_spec.jediTaskID = taskSpec.jediTaskID + update_spec.status = taskSpec.status + update_spec.splitRule = taskSpec.splitRule + self.taskBufferIF.updateTask_JEDI(update_spec, {"jediTaskID": taskSpec.jediTaskID}, updateDEFT=False, setFrozenTime=False) + tmpLog.info(f"brokerage holdup expired after the pending cycle; brokered without waiting for workflow {taskSpec.get_workflow_id()}") + # update dataset def updateDatasetStatus(self, datasetSpec: JediDatasetSpec, datasetStatus: str, tmpLog: MsgWrapper, datasetState: str | None = None) -> None: # update dataset status diff --git a/pandajedi/jedirefine/TaskRefinerBase.py b/pandajedi/jedirefine/TaskRefinerBase.py index 71b9a7b7f..ebce35666 100644 --- a/pandajedi/jedirefine/TaskRefinerBase.py +++ b/pandajedi/jedirefine/TaskRefinerBase.py @@ -469,7 +469,10 @@ def extractCommon( if "noAutoPause" in taskParamMap and taskParamMap["noAutoPause"]: self.setSplitRule(None, 1, JediTaskSpec.splitRuleToken["noAutoPause"]) if "workflowHoldup" in taskParamMap and taskParamMap["workflowHoldup"]: - self.setSplitRule(None, 1, JediTaskSpec.splitRuleToken["workflowHoldup"]) + # bit flags (see WORKFLOW_HOLDUP_* in JediTaskSpec). int() also turns the boolean True + # that earlier submissions carry into 1, the input hold it always meant; written as is, + # it would become "WH=True", which no reader matches. + self.setSplitRule(None, int(taskParamMap["workflowHoldup"]), JediTaskSpec.splitRuleToken["workflowHoldup"]) if taskParamMap.get("workflowID"): # the native workflow this task is a step of, so that consumers can find its siblings # without the unindexed scan of workflow_steps by target_id diff --git a/pandaserver/taskbuffer/JediTaskSpec.py b/pandaserver/taskbuffer/JediTaskSpec.py index 416ca9f80..b1110fb4b 100644 --- a/pandaserver/taskbuffer/JediTaskSpec.py +++ b/pandaserver/taskbuffer/JediTaskSpec.py @@ -17,6 +17,14 @@ """ +# Bit flags carried by the workflowHoldup split rule. A task submitted by a native workflow step +# can be held for two independent reasons, released by different parties. +# Waiting for inputs still being produced upstream; released by the workflow engine. +WORKFLOW_HOLDUP_INPUT = 1 +# A step with no input, waiting for its data-bound siblings to be brokered so that it can follow +# them; released by the workflow manager watchdog, or expired by the regular pending cycle. +WORKFLOW_HOLDUP_BROKERAGE = 2 + class JediTaskSpec(object): # attributes @@ -1818,14 +1826,38 @@ def is_msg_driven(self) -> bool: def allow_incomplete_input(self) -> bool: return self.check_split_rule("allowIncompleteInDS") + def _workflow_holdup_value(self) -> int: + """The workflowHoldup rule's value as bit flags, 0 when the rule is absent""" + if self.splitRule is not None: + tmpMatch = re.search(r"(?:^|,)" + self.splitRuleToken["workflowHoldup"] + r"=(\d+)", self.splitRule) + if tmpMatch is not None: + return int(tmpMatch.group(1)) + return 0 + # check if workflow holdup def is_workflow_holdup(self) -> bool: - return self.check_split_rule("workflowHoldup") + """Whether the task waits for its inputs to be completed by its workflow + + Only the input bit counts. The rule also carries the brokerage hold, which must not make + the datasets mutable or wait for ready files. + """ + return bool(self._workflow_holdup_value() & WORKFLOW_HOLDUP_INPUT) + + def is_workflow_brokerage_holdup(self) -> bool: + """Whether the task waits for the data-bound steps of its workflow to be brokered first""" + return bool(self._workflow_holdup_value() & WORKFLOW_HOLDUP_BROKERAGE) # set workflow holdup - def set_workflow_holdup(self, value: bool) -> None: - if value: - self.setSplitRule("workflowHoldup", "1") + def set_workflow_holdup(self, value: bool, kind: int = WORKFLOW_HOLDUP_INPUT) -> None: + """Set or clear one kind of workflow hold, leaving the other as it is + + Args: + value: True to hold, False to release + kind: WORKFLOW_HOLDUP_INPUT or WORKFLOW_HOLDUP_BROKERAGE + """ + new_value = self._workflow_holdup_value() | kind if value else self._workflow_holdup_value() & ~kind + if new_value: + self.setSplitRule("workflowHoldup", str(new_value)) else: self.removeSplitRule(self.splitRuleToken["workflowHoldup"]) diff --git a/pandaserver/workflow/step_handler_plugins/panda_task_step_handler.py b/pandaserver/workflow/step_handler_plugins/panda_task_step_handler.py index 72a9a2c67..5795f35f3 100644 --- a/pandaserver/workflow/step_handler_plugins/panda_task_step_handler.py +++ b/pandaserver/workflow/step_handler_plugins/panda_task_step_handler.py @@ -6,6 +6,10 @@ from pandacommon.pandalogger.PandaLogger import PandaLogger from pandaserver.srvcore.CoreUtils import clean_user_id +from pandaserver.taskbuffer.JediTaskSpec import ( + WORKFLOW_HOLDUP_BROKERAGE, + WORKFLOW_HOLDUP_INPUT, +) from pandaserver.workflow.step_handler_plugins.base_step_handler import BaseStepHandler from pandaserver.workflow.workflow_base import ( PARENT_TASK_ID_PARAM, @@ -45,6 +49,43 @@ logger = PandaLogger().getLogger(__name__.split(".")[-1]) +# What a panda-task step reads is described by its own task parameters, so deciding it belongs +# with the flavor that defines them. The workflow manager watchdog imports these too, for the +# same steps -- it only looks at JEDI task flavors. +def step_task_takes_input(step_spec: WFStepSpec) -> bool | None: + """Whether the step's task reads an input dataset of any kind + + Read from the task parameters rather than from input_data_dict, which carries only inputs + written as references: a step naming a literal dataset has an empty input_data_dict and still + reads data, so it is bound by data locality like any other. + + Returns: + bool | None: None for a step with no task parameters, whose target is not a PanDA task + """ + task_params = step_spec.definition_json_map.get("task_params") + if not isinstance(task_params, dict): + return None + if task_params.get("noInput") is True: + return False + return any(isinstance(job_param, dict) and job_param.get("param_type") == "input" for job_param in task_params.get("jobParameters") or []) + + +def brokerage_bound_steps(step_specs: list[WFStepSpec]) -> list[WFStepSpec]: + """The steps whose placement data locality decides alone, independently of their siblings + + A step that reads input of which nothing is produced inside the workflow: its data already + exists, so brokerage will put it where the data is. These are the steps a data-free sibling + waits for before being brokered. A step that also consumes a sibling's output is excluded, + because that sibling may be the very one waiting, and waiting on it would deadlock. + """ + produced_inside = {name for step_spec in step_specs for name in step_spec.definition_json_map.get("output_data_list", [])} + return [ + step_spec + for step_spec in step_specs + if step_task_takes_input(step_spec) and not produced_inside.intersection(step_spec.definition_json_map.get("input_data_dict", {})) + ] + + class PandaTaskStepHandler(BaseStepHandler): """ Handler for PanDA task steps in the workflow. @@ -394,6 +435,46 @@ def check_previous_attempt(self, step_spec: WFStepSpec, task_param_map: dict[str tmp_log.info(f"a previous attempt recorded taskName={task_name} but queued no task; submitting again") return True, "" + def needs_brokerage_holdup(self, step_spec: WFStepSpec, task_param_map: dict[str, Any], tmp_log: LogWrapper) -> bool: + """ + Whether the step's task should wait for its data-bound siblings before being brokered + + An analysis step with no input has nothing to place it, so it is drawn to wherever the rest + of its workflow is going. Brokered before its siblings, it sees only a prediction spread + over every replica of their inputs; brokered after them, it sees where they actually went. + Only worth holding when workflow affinity is on and some sibling is bound by data; the + hold is released by the workflow manager watchdog or expires with the pending cycle. + + Args: + step_spec: the step being submitted + task_param_map: its task parameters + tmp_log: logger + + Returns: + bool: True to hold the task's brokerage + """ + try: + # workflow affinity exists only in analysis brokerage + if task_param_map.get("prodSourceLabel") != "user": + return False + if step_task_takes_input(step_spec) is not False: + return False + if not self.tbif.getConfigValue("anal_jobbroker", "WORKFLOW_AFFINITY", "jedi", task_param_map.get("vo")): + return False + # Classify over all steps, this one included: what this step produces is what makes a + # sibling consuming it unbound, and leaving it out would have that sibling waited for + # while it waits on this step. + all_step_specs = self.tbif.get_steps_of_workflow(workflow_id=step_spec.workflow_id) or [] + bound_specs = [s for s in brokerage_bound_steps(all_step_specs) if s.step_id != step_spec.step_id] + if not bound_specs: + return False + tmp_log.info(f"brokerage held until data-bound steps {sorted(s.step_id for s in bound_specs)} are placed") + return True + except Exception as e: + # a preference that cannot be worked out is no reason to hold or to fail the step + tmp_log.warning(f"failed to decide brokerage holdup, not holding: {e}") + return False + def submit_target(self, step_spec: WFStepSpec, **kwargs: Any) -> WFStepTargetSubmitResult: """ Submit a target for processing the PanDA task step. @@ -450,9 +531,16 @@ def submit_target(self, step_spec: WFStepSpec, **kwargs: Any) -> WFStepTargetSub if not is_resolved: submit_result.message = message return submit_result + # workflowHoldup carries bit flags, one per reason to hold the task + holdup_value = 0 if not step_spec.get_parameter("all_inputs_complete"): - # Some inputs are not complete, set workflowHoldup to True to hold up the workflow until released by workflow processor - task_param_map["workflowHoldup"] = True + # Some inputs are not complete: hold up the task until released by the workflow processor + holdup_value |= WORKFLOW_HOLDUP_INPUT + if self.needs_brokerage_holdup(step_spec, task_param_map, tmp_log): + # No input to place it: hold up its brokerage until its data-bound siblings are placed + holdup_value |= WORKFLOW_HOLDUP_BROKERAGE + if holdup_value: + task_param_map["workflowHoldup"] = holdup_value # Name the workflow on the task. Nothing else in the task identifies it, and the # reverse lookup is a scan of workflow_steps, so a consumer such as brokerage can only # afford to ask about its workflow if the task carries the ID itself. diff --git a/pandaserver/workflow/tests/step_submission_test.py b/pandaserver/workflow/tests/step_submission_test.py index f1b61f7f0..e15db649a 100644 --- a/pandaserver/workflow/tests/step_submission_test.py +++ b/pandaserver/workflow/tests/step_submission_test.py @@ -88,6 +88,11 @@ def error(self, m): stub("pandacommon.pandautils.PandaUtils", naive_utcnow=lambda: None) stub("pandaserver.config", panda_config=types.SimpleNamespace(schemaJEDI="ATLAS_PANDA", schemaDEFT="ATLAS_DEFT")) +from pandaserver.taskbuffer.JediTaskSpec import ( # noqa: E402 + WORKFLOW_HOLDUP_BROKERAGE, + WORKFLOW_HOLDUP_INPUT, + JediTaskSpec, +) from pandaserver.workflow.step_handler_plugins.panda_task_step_handler import ( # noqa: E402 PandaTaskStepHandler, ) @@ -136,6 +141,10 @@ def __init__(self, data_by_name=None, task_id=49900001, error="", deft_status=No self.existing_task_names = existing_task_names or {} self.name_lookup_fails = name_lookup_fails self.name_lookups = [] + self.config_values = {} + + def getConfigValue(self, component, key, app="pandaserver", vo=None, default=None): + return self.config_values.get((component, key), default) def get_existing_task_names(self, vo, prod_source_label, task_names): self.name_lookups.append((vo, prod_source_label, list(task_names))) @@ -252,7 +261,10 @@ def make_tbif(**kw): tbif = make_tbif() handler = PandaTaskStepHandler(tbif) handler.submit_target(make_step(all_inputs_complete=False)) - failures += not check("workflowHoldup set", tbif.inserted[0].get("workflowHoldup") is True) + # an integer now, read as bit flags; 1 is the input hold it always meant + failures += not check( + "workflowHoldup set to the input bit", tbif.inserted[0].get("workflowHoldup") == WORKFLOW_HOLDUP_INPUT, tbif.inserted[0].get("workflowHoldup") + ) print("\n=== the task names the workflow it is a step of ===") # Nothing else in a task identifies its workflow, and the reverse lookup is a scan of @@ -267,6 +279,80 @@ def make_tbif(**kw): ) failures += not check("...and it is the step's own workflow", step.workflow_id is not None, step.workflow_id) + print("\n=== a data-free analysis step is held for brokerage ===") + # A step with no input has nothing to place it, so it waits for its siblings that data locality + # places, and follows them. It is held only if there is such a sibling to wait for. + free_params = copy.deepcopy(simul_params) + free_params["prodSourceLabel"] = "user" + free_params["vo"] = "atlas" + free_params["jobParameters"] = [p for p in free_params["jobParameters"] if p.get("param_type") != "input"] + free_params["noInput"] = True + + def make_sibling(step_id, inputs, outputs=(), takes_input=True): + params = copy.deepcopy(simul_params) + if not takes_input: + params["jobParameters"] = [p for p in params["jobParameters"] if p.get("param_type") != "input"] + sibling = FakeStep({"task_params": params, "input_data_dict": {name: {} for name in inputs}, "output_data_list": list(outputs)}) + sibling.step_id = step_id + return sibling + + def submit_free(siblings, affinity=True): + free_step = make_step(params=free_params, definition={"output_data_list": ["generate/outDS"]}) + tbif = make_tbif(steps_by_id={free_step.step_id: free_step, **{s.step_id: s for s in siblings}}) + tbif.config_values[("anal_jobbroker", "WORKFLOW_AFFINITY")] = affinity + PandaTaskStepHandler(tbif).submit_target(free_step) + return tbif.inserted[0].get("workflowHoldup") if tbif.inserted else "not submitted" + + bound = make_sibling(11, ["{signal}"]) + value = submit_free([bound]) + failures += not check("held with the brokerage bit when a sibling is bound by data", value == WORKFLOW_HOLDUP_BROKERAGE, value) + value = submit_free([bound], affinity=False) + failures += not check("not held when workflow affinity is off", value is None, value) + value = submit_free([]) + failures += not check("not held when it is the only step", value is None, value) + value = submit_free([make_sibling(12, [], takes_input=False)]) + failures += not check("not held when no sibling reads data either", value is None, value) + # A sibling reading this step's output waits on it, so waiting on that sibling would deadlock. + # Workflow 148's make_background_2: a root input plus generate_some's output. + consumer = make_sibling(13, ["{background}", "generate/outDS"]) + value = submit_free([consumer]) + failures += not check("a sibling consuming its output is not waited for", value is None, value) + value = submit_free([consumer, bound]) + failures += not check("...while a bound one alongside still is", value == WORKFLOW_HOLDUP_BROKERAGE, value) + # a literal dataset leaves input_data_dict empty but still binds the step to its data + value = submit_free([make_sibling(14, [])]) + failures += not check("a sibling reading a literal dataset counts as bound", value == WORKFLOW_HOLDUP_BROKERAGE, value) + + print("\n=== a step that reads data is never held for brokerage ===") + user_input_params = copy.deepcopy(simul_params) + user_input_params["prodSourceLabel"] = "user" + tbif = make_tbif(steps_by_id={11: bound}) + tbif.config_values[("anal_jobbroker", "WORKFLOW_AFFINITY")] = True + PandaTaskStepHandler(tbif).submit_target(make_step(params=user_input_params)) + failures += not check("no brokerage bit on a step with input", "workflowHoldup" not in tbif.inserted[0], tbif.inserted[0].get("workflowHoldup")) + tbif = make_tbif(steps_by_id={11: bound}) + tbif.config_values[("anal_jobbroker", "WORKFLOW_AFFINITY")] = True + PandaTaskStepHandler(tbif).submit_target(make_step(params=user_input_params, all_inputs_complete=False)) + failures += not check("only the input bit while inputs are incomplete", tbif.inserted[0].get("workflowHoldup") == WORKFLOW_HOLDUP_INPUT) + + print("\n=== the two holds share one split rule without mixing ===") + task_spec = JediTaskSpec() + task_spec.splitRule = "WH=2,NG=3" + # Without reading bits, WH=2 would also switch on the input hold: mutable datasets and the + # wait for ready files in the contents feeder, and release by on_all_inputs_done. + failures += not check("the brokerage bit is not an input hold", not task_spec.is_workflow_holdup()) + failures += not check("...and is a brokerage hold", task_spec.is_workflow_brokerage_holdup()) + task_spec.set_workflow_holdup(True) + failures += not check("setting the input bit keeps the brokerage one", task_spec.splitRule == "WH=3,NG=3", task_spec.splitRule) + task_spec.set_workflow_holdup(False, WORKFLOW_HOLDUP_BROKERAGE) + failures += not check("clearing the brokerage bit keeps the input one", task_spec.splitRule == "WH=1,NG=3", task_spec.splitRule) + task_spec.set_workflow_holdup(False) + failures += not check("clearing the last bit removes the rule", task_spec.splitRule == "NG=3", task_spec.splitRule) + task_spec.splitRule = "WH=1" + failures += not check("an existing task's WH=1 still means the input hold", task_spec.is_workflow_holdup() and not task_spec.is_workflow_brokerage_holdup()) + # the refiner writes int(value): a boolean from a submission made before the change is 1 + failures += not check("a boolean from an earlier submission refines to the input bit", int(True) == WORKFLOW_HOLDUP_INPUT) + print("\n=== a production label without the role is refused ===") # only the task-level production label is guarded; see PRODUCTION_SOURCE_LABELS for label in ["managed"]: