File size: 12,059 Bytes
9368cc4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 | #!/usr/bin/env python3
"""Second batch of `flow` tasks: precedence, boundaries, persistence, ordering."""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
from make_tasks import make, spec # noqa: E402
R = "python/scheduler"
# ------------------------------------------------------- operator precedence
make(R, "expr-precedence",
spec("python", "logic", 5, """
Conditional tasks are running when they shouldn't.
We gate an optional deploy step with the condition `staging or canary and green`.
Our intent is the usual reading: deploy when staging succeeded, or else when
both canary and green did. In practice, a run where staging succeeded but green
did not still skips the deploy, and a run where only canary succeeded runs it.
The condition language is documented as binding the two operators the same way
Python does. It doesn't appear to. Please fix it.
"""),
[("flow/expressions.py",
""" def or_expr(self) -> bool:
value = self.and_expr()
while self.peek() == "or":
self.take()
right = self.and_expr()
value = value or right
return value
def and_expr(self) -> bool:
value = self.unary()
while self.peek() == "and":
self.take()
right = self.unary()
value = value and right
return value""",
""" def or_expr(self) -> bool:
value = self.unary()
while self.peek() == "or":
self.take()
right = self.unary()
value = value or right
return value
def and_expr(self) -> bool:
value = self.or_expr()
while self.peek() == "and":
self.take()
right = self.or_expr()
value = value and right
return value""")],
{"test_precedence.py": '''
import unittest
from flow import evaluate
def facts(**kw):
return kw
class TestOperatorPrecedence(unittest.TestCase):
"""`and` must bind tighter than `or`, as in Python."""
def test_or_of_and(self):
self.assertTrue(evaluate("a or b and c", facts(a=True, b=True, c=False)))
self.assertTrue(evaluate("a or b and c", facts(a=False, b=True, c=True)))
self.assertFalse(evaluate("a or b and c", facts(a=False, b=True, c=False)))
def test_and_of_or(self):
self.assertTrue(evaluate("a and b or c", facts(a=False, b=False, c=True)))
self.assertFalse(evaluate("a and b or c", facts(a=True, b=False, c=False)))
def test_matches_python_over_every_assignment(self):
for a in (False, True):
for b in (False, True):
for c in (False, True):
self.assertEqual(
evaluate("a or b and c", facts(a=a, b=b, c=c)),
a or b and c, f"a={a} b={b} c={c}")
def test_three_way_and_chain(self):
self.assertFalse(evaluate("a and b and c", facts(a=True, b=True, c=False)))
self.assertTrue(evaluate("a and b and c", facts(a=True, b=True, c=True)))
class TestExpressionBasicsIntact(unittest.TestCase):
def test_parentheses_override(self):
self.assertFalse(evaluate("(a or b) and c", facts(a=True, b=False, c=False)))
self.assertTrue(evaluate("(a or b) and c", facts(a=True, b=False, c=True)))
def test_not_binds_tightest(self):
self.assertTrue(evaluate("not a or b", facts(a=False, b=False)))
self.assertFalse(evaluate("not (a or b)", facts(a=False, b=True)))
def test_bare_name(self):
self.assertTrue(evaluate("a", facts(a=True)))
self.assertFalse(evaluate("a", facts()))
def test_blank_condition_is_true(self):
self.assertTrue(evaluate(None, {}))
self.assertTrue(evaluate(" ", {}))
'''})
# ------------------------------------------------------- half-open windows
make(R, "window-inclusive-end",
spec("python", "logic", 3, """
A nightly job started at exactly the moment its maintenance window closed, and
collided with the backup that owns the following slot.
Our windows are defined back to back -- one ends at the instant the next
begins -- and the docs say a task may start at a window's start but not at its
end. That boundary does not seem to be respected. Please fix it.
"""),
[("flow/calendar.py",
""" def contains(self, when: float) -> bool:
return self.start <= when < self.end""",
""" def contains(self, when: float) -> bool:
return self.start <= when <= self.end""")],
{"test_windows.py": '''
import unittest
from flow import Calendar, ResourcePool, Scheduler, Task, TaskGraph, Window
class TestHalfOpenWindows(unittest.TestCase):
def test_end_is_excluded(self):
self.assertFalse(Window(10.0, 20.0).contains(20.0))
def test_start_is_included(self):
self.assertTrue(Window(10.0, 20.0).contains(10.0))
def test_adjacent_windows_do_not_overlap(self):
first, second = Window(0.0, 10.0), Window(10.0, 20.0)
overlapping = [t for t in (0.0, 5.0, 10.0, 15.0)
if first.contains(t) and second.contains(t)]
self.assertEqual(overlapping, [])
def test_calendar_closed_at_window_end(self):
cal = Calendar([Window(10.0, 20.0)])
self.assertFalse(cal.is_open(20.0))
def test_scheduler_offers_nothing_at_the_boundary(self):
cal = Calendar([Window(0.0, 10.0)])
s = Scheduler(TaskGraph([Task("job")]), ResourcePool({}), calendar=cal)
s.clock.advance(10.0)
self.assertEqual(s.next_batch(s.new_state()), [])
class TestWindowsOtherwiseWork(unittest.TestCase):
def test_inside_is_open(self):
self.assertTrue(Calendar([Window(10.0, 20.0)]).is_open(15.0))
def test_before_is_closed(self):
self.assertFalse(Calendar([Window(10.0, 20.0)]).is_open(9.0))
def test_empty_calendar_is_always_open(self):
self.assertTrue(Calendar().is_open(12345.0))
def test_next_open_finds_the_following_window(self):
cal = Calendar([Window(10.0, 20.0), Window(30.0, 40.0)])
self.assertEqual(cal.next_open(25.0), 30.0)
def test_scheduler_runs_inside_the_window(self):
cal = Calendar([Window(0.0, 10.0)])
s = Scheduler(TaskGraph([Task("job")]), ResourcePool({}), calendar=cal)
s.clock.advance(5.0)
self.assertEqual(s.next_batch(s.new_state()), ["job"])
'''})
# ------------------------------------------------------- persistence loses backoff
make(R, "resume-loses-backoff",
spec("python", "logic", 4, """
Resuming a saved run stampedes our downstream API.
When a task fails we back it off before retrying. If the process is restarted
while several tasks are waiting out their backoff, every one of them is offered
immediately on the first scheduling pass after the run is reloaded, instead of
waiting out the remainder of its delay.
A reloaded run is meant to behave exactly as though it had never stopped.
Please make it do so.
"""),
[("flow/serialize.py",
""" "results": dict(state.results),
"ready_at": dict(state.ready_at),
}""",
""" "results": dict(state.results),
}""")],
{"test_resume.py": '''
import unittest
from flow import (ResourcePool, RetryPolicy, RunState, Scheduler, Task,
TaskGraph, dump_state, load_state, round_trip)
class TestResumePreservesBackoff(unittest.TestCase):
def test_ready_at_survives_a_round_trip(self):
state = RunState(["a", "b"])
state.ready_at["a"] = 42.5
self.assertEqual(round_trip(state).ready_at.get("a"), 42.5)
def test_reloaded_run_still_waits(self):
graph = TaskGraph([Task("job", retry=RetryPolicy(max_attempts=3,
base_delay=30.0))])
s = Scheduler(graph, ResourcePool({}))
state = s.new_state()
s.start("job", state)
s.fail("job", state)
resumed = round_trip(state)
self.assertEqual(s.next_batch(resumed), [])
def test_reloaded_run_becomes_eligible_on_time(self):
graph = TaskGraph([Task("job", retry=RetryPolicy(max_attempts=3,
base_delay=30.0))])
s = Scheduler(graph, ResourcePool({}))
state = s.new_state()
s.start("job", state)
s.fail("job", state)
resumed = round_trip(state)
s.clock.advance(30.0)
self.assertEqual(s.next_batch(resumed), ["job"])
def test_dump_includes_every_field_the_scheduler_reads(self):
state = RunState(["a"])
state.ready_at["a"] = 1.0
payload = dump_state(state)
for field in ("status", "attempts", "results", "ready_at"):
self.assertIn(field, payload)
class TestPersistenceOtherwiseIntact(unittest.TestCase):
def test_status_and_attempts_survive(self):
state = RunState(["a", "b"])
state.record_attempt("a")
state.record_attempt("a")
back = round_trip(state)
self.assertEqual(back.attempts["a"], 2)
self.assertEqual(back.status, state.status)
def test_results_survive(self):
from flow import state as st
state = RunState(["a"])
state.set("a", st.READY)
state.set("a", st.RUNNING)
state.succeed("a", {"artifact": "x"})
self.assertEqual(round_trip(state).results["a"], {"artifact": "x"})
def test_bad_version_is_rejected(self):
from flow import SerializationError
with self.assertRaises(SerializationError):
load_state({"version": 999, "status": {}})
'''})
# ------------------------------------------------------- unstable ordering
make(R, "priority-tie-unstable",
spec("python", "logic", 3, """
Two runs of the same unchanged graph produce different schedules.
We compare scheduler decisions between runs as part of our release checks, and
tasks that share a priority come back in a different order depending on how the
graph happened to be built. Downstream tooling assumes a run is reproducible,
so this shows up as spurious diffs.
The engine is documented as making the same decisions in the same order for the
same graph. Please restore that.
"""),
[("flow/task.py",
""" def sort_key(self) -> Tuple[int, str]:
return (-self.priority, self.task_id)""",
""" def sort_key(self) -> Tuple[int, str]:
return (-self.priority, "")""")],
{"test_ordering.py": '''
import unittest
from flow import ResourcePool, Scheduler, Task, TaskGraph
def batch(names):
graph = TaskGraph([Task(n) for n in names])
s = Scheduler(graph, ResourcePool({}))
return s.next_batch(s.new_state())
class TestDeterministicOrdering(unittest.TestCase):
def test_equal_priority_sorts_by_id(self):
self.assertEqual(batch(["charlie", "alpha", "bravo"]),
["alpha", "bravo", "charlie"])
def test_insertion_order_does_not_matter(self):
self.assertEqual(batch(["a", "b", "c"]), batch(["c", "b", "a"]))
def test_mixed_priorities_then_id(self):
graph = TaskGraph([Task("zeta", priority=5), Task("alpha", priority=5),
Task("mid", priority=1)])
s = Scheduler(graph, ResourcePool({}))
self.assertEqual(s.next_batch(s.new_state()), ["alpha", "zeta", "mid"])
def test_sort_key_distinguishes_equal_priorities(self):
self.assertNotEqual(Task("a").sort_key(), Task("b").sort_key())
class TestPriorityStillWins(unittest.TestCase):
def test_higher_priority_first(self):
graph = TaskGraph([Task("low", priority=0), Task("high", priority=10)])
s = Scheduler(graph, ResourcePool({}))
self.assertEqual(s.next_batch(s.new_state()), ["high", "low"])
def test_negative_priority_sorts_last(self):
graph = TaskGraph([Task("normal", priority=0), Task("later", priority=-5)])
s = Scheduler(graph, ResourcePool({}))
self.assertEqual(s.next_batch(s.new_state()), ["normal", "later"])
'''})
print("done")
|