File size: 14,695 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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
#!/usr/bin/env python3
"""Tasks built on the `flow` scheduler repo.

Instructions are written the way a colleague would report the problem: a
symptom, and how to see it. They never name the faulty function, never state
the expected values, and never describe the fix.
"""
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"

# ---------------------------------------------------------------- retry never fires
make(R, "retry-never-fires",
     spec("python", "logic", 4, """
A workflow with a retry policy hangs instead of retrying.

To see it: define one task with RetryPolicy(max_attempts=3), start it, and
report it failed. The run then never makes progress again -- the task is not
finished, but nothing the scheduler offers ever includes it again, even after
the clock is advanced well past any backoff.

Retries are supposed to become eligible again once their delay has elapsed.
Track down why they don't and fix it.
"""),
     [("flow/scheduler.py",
       """            # RETRYING counts as a candidate: its backoff is enforced below by
            # ready_at, and leaving it out would mean a retry never fires.
            if state.get(task_id) not in (st.PENDING, st.READY, st.RETRYING):
                continue""",
       """            if state.get(task_id) not in (st.PENDING, st.READY):
                continue""")],
     {"test_retry.py": '''
import unittest

from flow import ResourcePool, ResourceRequest, RetryPolicy, Scheduler, Task, TaskGraph
from flow import state as st


def one_task(**kw):
    graph = TaskGraph([Task("job", **kw)])
    return Scheduler(graph, ResourcePool({"cpu": 4}))


class TestRetryBecomesEligible(unittest.TestCase):
    def test_retry_is_offered_after_backoff(self):
        s = one_task(retry=RetryPolicy(max_attempts=3, base_delay=10.0))
        state = s.new_state()
        s.start("job", state)
        s.fail("job", state)
        s.clock.advance(10.0)
        self.assertEqual(s.next_batch(state), ["job"])

    def test_retry_runs_to_success(self):
        s = one_task(retry=RetryPolicy(max_attempts=3, base_delay=1.0))
        state = s.new_state()
        s.start("job", state)
        s.fail("job", state)
        s.clock.advance(1.0)
        s.start("job", state)
        s.finish("job", state, True)
        self.assertEqual(state.get("job"), st.SUCCEEDED)
        self.assertEqual(state.attempts["job"], 2)

    def test_run_reaches_completion(self):
        s = one_task(retry=RetryPolicy(max_attempts=2, base_delay=1.0))
        state = s.new_state()
        for _ in range(6):
            batch = s.next_batch(state)
            if not batch:
                s.clock.advance(5.0)
                continue
            s.start(batch[0], state)
            s.fail(batch[0], state)
            if state.is_complete():
                break
        self.assertTrue(state.is_complete())
        self.assertEqual(state.get("job"), st.FAILED)


class TestBackoffStillEnforced(unittest.TestCase):
    """A retry must not become eligible before its delay has elapsed."""

    def test_not_offered_before_backoff(self):
        s = one_task(retry=RetryPolicy(max_attempts=3, base_delay=30.0))
        state = s.new_state()
        s.start("job", state)
        s.fail("job", state)
        self.assertEqual(s.next_batch(state), [])
        s.clock.advance(29.0)
        self.assertEqual(s.next_batch(state), [])

    def test_terminal_tasks_are_never_offered(self):
        s = one_task()
        state = s.new_state()
        s.start("job", state)
        s.finish("job", state, True)
        self.assertEqual(s.next_batch(state), [])

    def test_exhausted_retries_end_as_failed(self):
        s = one_task(retry=RetryPolicy(max_attempts=1))
        state = s.new_state()
        s.start("job", state)
        s.fail("job", state)
        self.assertEqual(state.get("job"), st.FAILED)
'''})

# ---------------------------------------------------------------- resource leak
make(R, "resource-leak-on-retry",
     spec("python", "logic", 4, """
A long-running workflow gradually stops scheduling anything.

Our pipeline has a pool of 4 "cpu" units and several flaky tasks that fail and
retry. The first few retries behave, but after enough failures the scheduler
stops offering work entirely, even though plenty of tasks are still pending and
nothing is actually running. Restarting the process clears it.

It looks like capacity is going missing over the life of a run. Please find out
where and fix it.
"""),
     [("flow/scheduler.py",
       """        The pool is released on every failure, not only the last one: a task
        that is going to be retried must not keep holding capacity while it
        waits out its backoff.
        \"\"\"
        self.pool.release(task_id)
        task = self.graph.get(task_id)""",
       """        The pool is released on every failure, not only the last one: a task
        that is going to be retried must not keep holding capacity while it
        waits out its backoff.
        \"\"\"
        task = self.graph.get(task_id)""")],
     {"test_resource_lifecycle.py": '''
import unittest

from flow import (ResourcePool, ResourceRequest, RetryPolicy, Scheduler, Task,
                  TaskGraph)


def scheduler(capacity=4, **kw):
    graph = TaskGraph([Task("job", resources=(ResourceRequest("cpu", 2),), **kw)])
    return Scheduler(graph, ResourcePool({"cpu": capacity}))


class TestCapacityIsReturned(unittest.TestCase):
    def test_failure_returns_capacity(self):
        s = scheduler(retry=RetryPolicy(max_attempts=3, base_delay=1.0))
        state = s.new_state()
        s.start("job", state)
        s.fail("job", state)
        self.assertEqual(s.pool.free("cpu"), 4)

    def test_capacity_is_stable_across_many_retries(self):
        s = scheduler(retry=RetryPolicy(max_attempts=5, base_delay=1.0))
        state = s.new_state()
        for _ in range(4):
            s.clock.advance(60.0)
            batch = s.next_batch(state)
            if not batch:
                break
            s.start("job", state)
            s.fail("job", state)
        self.assertEqual(s.pool.free("cpu"), 4)

    def test_nothing_is_still_held_after_failure(self):
        s = scheduler(retry=RetryPolicy(max_attempts=3, base_delay=1.0))
        state = s.new_state()
        s.start("job", state)
        s.fail("job", state)
        self.assertEqual(s.pool.held_by("job"), {})
        self.assertEqual(s.pool.in_use(), {"cpu": 0})


class TestNormalPathUnaffected(unittest.TestCase):
    def test_success_returns_capacity(self):
        s = scheduler()
        state = s.new_state()
        s.start("job", state)
        s.finish("job", state, True)
        self.assertEqual(s.pool.free("cpu"), 4)

    def test_capacity_is_held_while_running(self):
        s = scheduler()
        state = s.new_state()
        s.start("job", state)
        self.assertEqual(s.pool.free("cpu"), 2)

    def test_final_failure_returns_capacity(self):
        s = scheduler(retry=RetryPolicy(max_attempts=1))
        state = s.new_state()
        s.start("job", state)
        s.fail("job", state)
        self.assertEqual(s.pool.free("cpu"), 4)
'''})

# ---------------------------------------------------------------- batch overcommit
make(R, "batch-overcommit",
     spec("python", "logic", 4, """
The scheduler hands us more work than our resource pool can support.

With a pool of 3 "cpu" units and two tasks that each request 2, a single call to
next_batch comes back with both of them. Starting both then blows up with a
ResourceExhausted from deep inside the pool.

Each task on its own fits, so the pool's accounting looks right to us -- it's
the batch that seems wrong. Please fix it so a batch is always startable.
"""),
     [("flow/scheduler.py",
       """        chosen: List[str] = []
        reserved: Dict[str, int] = {}
        in_flight = self.running_count(state)

        for task_id in self.eligible(state):
            if self.max_parallel and in_flight + len(chosen) >= self.max_parallel:
                break
            task = self.graph.get(task_id)
            fits = True
            for request in task.resources:
                already = reserved.get(request.name, 0)
                if self.pool.free(request.name) - already < request.amount:
                    fits = False
                    break
            if not fits:
                continue
            for request in task.resources:
                reserved[request.name] = reserved.get(request.name, 0) + request.amount
            chosen.append(task_id)
        return chosen""",
       """        chosen: List[str] = []
        in_flight = self.running_count(state)

        for task_id in self.eligible(state):
            if self.max_parallel and in_flight + len(chosen) >= self.max_parallel:
                break
            task = self.graph.get(task_id)
            if not self.pool.can_admit(task.resources):
                continue
            chosen.append(task_id)
        return chosen""")],
     {"test_batching.py": '''
import unittest

from flow import ResourcePool, ResourceRequest, Scheduler, Task, TaskGraph


def sched(capacity, tasks, **kw):
    return Scheduler(TaskGraph(tasks), ResourcePool(capacity), **kw)


class TestBatchIsStartable(unittest.TestCase):
    def test_batch_fits_within_capacity(self):
        s = sched({"cpu": 3},
                  [Task("a", resources=(ResourceRequest("cpu", 2),)),
                   Task("b", resources=(ResourceRequest("cpu", 2),))])
        self.assertEqual(s.next_batch(s.new_state()), ["a"])

    def test_whole_batch_can_actually_start(self):
        s = sched({"cpu": 5},
                  [Task("a", resources=(ResourceRequest("cpu", 2),)),
                   Task("b", resources=(ResourceRequest("cpu", 2),)),
                   Task("c", resources=(ResourceRequest("cpu", 2),))])
        state = s.new_state()
        batch = s.next_batch(state)
        for task_id in batch:
            s.start(task_id, state)          # must not raise
        self.assertEqual(len(batch), 2)

    def test_three_way_split(self):
        s = sched({"slots": 4},
                  [Task(name, resources=(ResourceRequest("slots", 3),))
                   for name in ("a", "b", "c")])
        self.assertEqual(s.next_batch(s.new_state()), ["a"])


class TestBatchingOtherwiseUnchanged(unittest.TestCase):
    def test_resourceless_tasks_all_admitted(self):
        s = sched({}, [Task("a"), Task("b"), Task("c")])
        self.assertEqual(s.next_batch(s.new_state()), ["a", "b", "c"])

    def test_max_parallel_still_caps(self):
        s = sched({}, [Task("a"), Task("b"), Task("c")], max_parallel=2)
        self.assertEqual(len(s.next_batch(s.new_state())), 2)

    def test_priority_order_preserved(self):
        s = sched({}, [Task("low", priority=0), Task("high", priority=9)])
        self.assertEqual(s.next_batch(s.new_state()), ["high", "low"])

    def test_everything_fits_when_capacity_is_ample(self):
        s = sched({"cpu": 10},
                  [Task("a", resources=(ResourceRequest("cpu", 1),)),
                   Task("b", resources=(ResourceRequest("cpu", 1),))])
        self.assertEqual(s.next_batch(s.new_state()), ["a", "b"])
'''})

# ---------------------------------------------------------------- cascade depth
make(R, "cascade-shallow",
     spec("python", "logic", 4, """
Runs containing a failure never finish.

Our deploy graph is a chain: fetch -> build -> test -> package -> ship. When
build fails, the run is left sitting there forever. Inspecting the state, test
has been skipped as we'd expect, but package and ship are still pending and the
scheduler will not offer them (correctly -- their dependency never succeeded),
so the run is simply stuck and is_complete() never becomes true.

Anything that can no longer run should end up in a terminal state. Please fix.
"""),
     [("flow/scheduler.py",
       """        skipped: List[str] = []
        for downstream in sorted(self.graph.descendants_of(task_id)):""",
       """        skipped: List[str] = []
        for downstream in sorted(self.graph.dependents_of(task_id)):""")],
     {"test_cascade.py": '''
import unittest

from flow import ResourcePool, Scheduler, Task, TaskGraph
from flow import state as st


def chain(*names):
    tasks = []
    previous = None
    for name in names:
        deps = frozenset({previous}) if previous else frozenset()
        tasks.append(Task(name, depends_on=deps))
        previous = name
    return Scheduler(TaskGraph(tasks), ResourcePool({}))


class TestFailurePropagatesFully(unittest.TestCase):
    def test_whole_chain_below_a_failure_is_skipped(self):
        s = chain("fetch", "build", "test", "package", "ship")
        state = s.new_state()
        s.start("fetch", state)
        s.finish("fetch", state, True)
        s.start("build", state)
        s.fail("build", state)
        for name in ("test", "package", "ship"):
            self.assertEqual(state.get(name), st.SKIPPED, name)

    def test_run_completes_after_a_failure(self):
        s = chain("a", "b", "c", "d")
        state = s.new_state()
        s.start("a", state)
        s.fail("a", state)
        self.assertTrue(state.is_complete())

    def test_diamond_below_a_failure(self):
        tasks = [Task("root"),
                 Task("left", depends_on=frozenset({"root"})),
                 Task("right", depends_on=frozenset({"root"})),
                 Task("join", depends_on=frozenset({"left", "right"})),
                 Task("after", depends_on=frozenset({"join"}))]
        s = Scheduler(TaskGraph(tasks), ResourcePool({}))
        state = s.new_state()
        s.start("root", state)
        s.fail("root", state)
        self.assertTrue(state.is_complete())
        self.assertEqual(state.get("after"), st.SKIPPED)


class TestUnrelatedWorkSurvives(unittest.TestCase):
    def test_independent_branch_is_untouched(self):
        tasks = [Task("a"), Task("b", depends_on=frozenset({"a"})),
                 Task("x"), Task("y", depends_on=frozenset({"x"}))]
        s = Scheduler(TaskGraph(tasks), ResourcePool({}))
        state = s.new_state()
        s.start("a", state)
        s.fail("a", state)
        self.assertEqual(state.get("x"), st.PENDING)
        self.assertEqual(state.get("y"), st.PENDING)

    def test_successful_run_skips_nothing(self):
        s = chain("a", "b", "c")
        state = s.new_state()
        for name in ("a", "b", "c"):
            s.start(name, state)
            s.finish(name, state, True)
        self.assertEqual(state.counts().get("skipped", 0), 0)
'''})

print("done")