File indexing completed on 2026-12-02 10:28:07
0001 """
0002 Pure site-selection helpers used by analysis brokerage.
0003
0004 Deliberately free of heavy imports. AtlasBrokerUtils and AtlasAnalJobBroker reach the grid, the
0005 database and the site mapper at import time, so nothing in them can be exercised without a live
0006 instance. The decisions here are arithmetic over lists and maps, which is exactly the part worth
0007 testing on its own, so they live where a test can import them.
0008
0009 Candidates are duck-typed: anything with a ``siteName`` attribute will do.
0010 """
0011
0012 from __future__ import annotations
0013
0014 import datetime
0015 import random
0016 from typing import Any, Collection, Iterable, Protocol, TypeVar
0017
0018
0019 class SiteCandidateLike(Protocol):
0020 """What the ordering needs of a candidate: the two names it is known by
0021
0022 Structural rather than the concrete SiteCandidate, because nothing here touches the rest of
0023 that class and a caller testing the ordering should not have to build one.
0024 """
0025
0026
0027 @property
0028 def siteName(self) -> str: ...
0029
0030 @property
0031 def unifiedName(self) -> str | None: ...
0032
0033
0034
0035 CandidateT = TypeVar("CandidateT", bound=SiteCandidateLike)
0036
0037
0038
0039
0040
0041 DEFAULT_WORKFLOW_AFFINITY_FACTOR = 5.0
0042
0043
0044
0045 WORKFLOW_ANCHOR_PARAM = "brokerage_anchor"
0046
0047
0048 def order_site_candidates(
0049 weight_map: dict[float, list[CandidateT]],
0050 site_list_with_data: Collection[str],
0051 used_site_candidates: list[CandidateT],
0052 preferred_sites: Collection[str] | None = None,
0053 ) -> list[CandidateT]:
0054 """
0055 Order site candidates highest weight first, with the sites already holding data in front
0056
0057 The order decides who survives the maxNumSites cut that follows, so a site missing from the
0058 front of this list cannot be chosen however good its weight. Sites the task has already run at
0059 are kept ahead of the rest but behind the data-holding ones, which is where the caller's
0060 partly-filled list puts them.
0061
0062 Args:
0063 weight_map: final brokerage weight to the candidates carrying it
0064 site_list_with_data: names of the sites that survived the data-locality pass, as
0065 scanSiteList carries them, i.e. pseudo names
0066 used_site_candidates: candidates the caller has already set aside, being the sites this
0067 task has run at before
0068 preferred_sites: unified names of sites holding the rest of this task's workflow, which
0069 are promoted alongside the data-holding ones so that co-location survives the cut
0070
0071 Returns:
0072 list[SiteCandidate]: the candidates in the order they should be offered
0073 """
0074 preferred_sites = preferred_sites or set()
0075 promoted: list[CandidateT] = []
0076 others = list(used_site_candidates)
0077 for weight_value in sorted(weight_map.keys(), reverse=True):
0078 candidates = list(weight_map[weight_value])
0079
0080
0081
0082
0083
0084 random.shuffle(candidates)
0085 for site_candidate in candidates:
0086
0087
0088
0089 if site_candidate.siteName in site_list_with_data or getattr(site_candidate, "unifiedName", None) in preferred_sites:
0090 promoted.append(site_candidate)
0091 else:
0092 others.append(site_candidate)
0093 return promoted + others
0094
0095
0096 def workflow_affinity_weight(unified_site_name: str, anchor_weights: dict[str, float] | None, factor: float = DEFAULT_WORKFLOW_AFFINITY_FACTOR) -> float:
0097 """
0098 How much to favour a site for already holding part of this task's workflow
0099
0100 Scaled against the strongest anchor rather than used raw, so that the boost means the same
0101 thing whatever arithmetic produced the anchor: the site with most of the workflow behind it is
0102 worth ``factor`` times an unrelated site, and a site with none of it is worth exactly 1, i.e.
0103 unchanged. Returning 1 rather than 0 for the unknown case is what keeps this a preference --
0104 a site that is not an anchor is never penalised, only not helped.
0105
0106 Args:
0107 unified_site_name: the site being weighed, by unified name
0108 anchor_weights: unified site name to anchor weight, as the workflow recorded it
0109 factor: the multiplier the strongest anchor earns
0110
0111 Returns:
0112 float: a multiplier in [1, factor]
0113 """
0114 if not anchor_weights:
0115 return 1.0
0116 strongest = max(anchor_weights.values())
0117 if strongest <= 0:
0118 return 1.0
0119 share = anchor_weights.get(unified_site_name, 0) / strongest
0120 if share <= 0:
0121 return 1.0
0122 return 1.0 + (factor - 1.0) * share
0123
0124
0125 def build_anchor_weights(
0126 pinned_sites: Iterable[str] = (),
0127 output_sites: Iterable[str] = (),
0128 input_sites: Iterable[str] = (),
0129 vetoed_sites: Collection[str] = (),
0130 ) -> dict[str, float]:
0131 """
0132 Combine what is known about a workflow's placement into one weighted preference map
0133
0134 A map rather than a set, because the sites have to be comparable: in a workflow whose steps
0135 take input from A once and from B twice, both are anchors but B is the cheaper one to join,
0136 and a set cannot say so. Each source contributes per step, so a site named by several steps
0137 outweighs one named by a single step.
0138
0139 The sources are ranked by how firm they are. A site a submitter pinned a step to is a fact
0140 that will not move; a site a finished step left its output at is a fact that may be joined by
0141 others; a site holding an input of a step not yet placed is a prediction. Repetition within a
0142 source still matters, so three predictions outweigh one.
0143
0144 Args:
0145 pinned_sites: unified sites that a sibling step is pinned to, one entry per step
0146 output_sites: unified sites where a sibling step's output already sits, one entry per step
0147 input_sites: unified sites holding the input of a sibling step not yet placed, one entry
0148 per step per site
0149 vetoed_sites: unified sites some step of the workflow cannot use, which are worthless as
0150 an anchor for the others however much data sits there
0151
0152 Returns:
0153 dict[str, float]: unified site name to anchor weight, vetoed sites absent
0154 """
0155 weights: dict[str, float] = {}
0156 for sites, per_step_weight in ((pinned_sites, 4.0), (output_sites, 2.0), (input_sites, 1.0)):
0157 for site_name in sites:
0158 if not site_name or site_name in vetoed_sites:
0159 continue
0160 weights[site_name] = weights.get(site_name, 0.0) + per_step_weight
0161 return weights
0162
0163
0164 def summarize_anchor(anchor: dict[str, Any] | None, max_sites: int = 5) -> str:
0165 """One line naming the strongest anchor sites, for the brokerage log"""
0166 weights = (anchor or {}).get("weights") or {}
0167 if not weights:
0168 return "no workflow anchor"
0169 ranked = sorted(weights.items(), key=lambda item: item[1], reverse=True)[:max_sites]
0170 return ", ".join(f"{site}={weight:g}" for site, weight in ranked)
0171
0172
0173 def brokerage_holdup_expired(creation_time: datetime.datetime | None, now: datetime.datetime, wait_minutes: float) -> bool:
0174 """
0175 Whether a task held for its workflow's brokerage has waited long enough to go on regardless
0176
0177 The hold is a preference, so it must never strand a step whose siblings are stuck. Rather than
0178 a timer of its own, it rides the regular pending cycle: a held task sits in pending, and the
0179 watchdog reactivates pending tasks after waitForPending minutes, sending it back through the
0180 contents feeder. The first feed happens within minutes of creation, so a task older than that
0181 interval can only be on a feed after reactivation -- the point at which to stop holding.
0182
0183 Args:
0184 creation_time: when the task was created
0185 now: current time
0186 wait_minutes: the pending reactivation interval
0187
0188 Returns:
0189 bool: True if the hold should be dropped
0190 """
0191 if creation_time is None:
0192
0193 return True
0194 return now - creation_time >= datetime.timedelta(minutes=wait_minutes)