File size: 9,354 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
#!/usr/bin/env python3
"""Third batch of `flow` tasks.

Instructions here report only what an operator could actually observe. No
diagnosis, no pointer at a module, no expected values -- the previous batch
scored too high partly because the instruction did the reasoning.
"""
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"

# --------------------------------------------------- multi-file: retry transition
make(R, "retry-transition-illegal",
     spec("python", "logic", 5, """
Any workflow that has to retry a task crashes the runner.

Steps: one task, RetryPolicy(max_attempts=3), start it, report it failed, wait
out the backoff, then start it again. The second start raises IllegalTransition.

This needs to work end to end without loosening what the state machine permits
in general -- finished work must still never be restartable.
"""),
     [("flow/state.py",
       """    RETRYING: {READY, FAILED},""",
       """    RETRYING: {FAILED},"""),
      ("flow/scheduler.py",
       """        if state.get(task_id) == st.PENDING:
            state.set(task_id, st.READY)
        elif state.get(task_id) == st.RETRYING:
            state.set(task_id, st.READY)""",
       """        if state.get(task_id) == st.PENDING:
            state.set(task_id, st.READY)""")],
     {"test_retry_transition.py": '''
import unittest

from flow import (IllegalTransition, ResourcePool, RetryPolicy, Scheduler,
                  Task, TaskGraph)
from flow import state as st


def one(**kw):
    return Scheduler(TaskGraph([Task("job", **kw)]), ResourcePool({}))


class TestRetryCanRestart(unittest.TestCase):
    def test_second_attempt_starts(self):
        s = one(retry=RetryPolicy(max_attempts=3, base_delay=5.0))
        state = s.new_state()
        s.start("job", state)
        s.fail("job", state)
        s.clock.advance(5.0)
        s.start("job", state)
        self.assertEqual(state.get("job"), st.RUNNING)

    def test_retry_then_succeed(self):
        s = one(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_three_attempts(self):
        s = one(retry=RetryPolicy(max_attempts=3, base_delay=1.0))
        state = s.new_state()
        for _ in range(3):
            s.clock.advance(100.0)
            s.start("job", state)
            s.fail("job", state)
        self.assertEqual(state.get("job"), st.FAILED)
        self.assertEqual(state.attempts["job"], 3)


class TestStateMachineStillStrict(unittest.TestCase):
    """Loosening the table wholesale would let finished work restart."""

    def test_succeeded_is_final(self):
        s = one()
        state = s.new_state()
        s.start("job", state)
        s.finish("job", state, True)
        with self.assertRaises(IllegalTransition):
            state.set("job", st.READY)

    def test_failed_is_final(self):
        s = one(retry=RetryPolicy(max_attempts=1))
        state = s.new_state()
        s.start("job", state)
        s.fail("job", state)
        with self.assertRaises(IllegalTransition):
            state.set("job", st.READY)

    def test_skipped_is_final(self):
        s = one()
        state = s.new_state()
        state.set("job", st.SKIPPED)
        with self.assertRaises(IllegalTransition):
            state.set("job", st.READY)

    def test_pending_cannot_jump_to_running(self):
        s = one()
        state = s.new_state()
        with self.assertRaises(IllegalTransition):
            state.set("job", st.RUNNING)
'''})

# --------------------------------------------------- graph aliasing
make(R, "dependents-aliasing",
     spec("python", "logic", 4, """
Our graph inspector corrupts the graph it inspects.

The tool walks a workflow and, for reporting, collects the dependents of each
task into a set it then adds a marker into. After running it, scheduling
decisions for that graph come out wrong -- tasks are offered whose dependencies
have not run, and the topological order gains entries that were never tasks.

Reading the graph should not be able to change it. Please fix.
"""),
     [("flow/graph.py",
       """        if task_id not in self._tasks:
            raise UnknownTask(task_id)
        return set(self._dependents.get(task_id, ()))""",
       """        if task_id not in self._tasks:
            raise UnknownTask(task_id)
        return self._dependents.setdefault(task_id, set())""")],
     {"test_graph_isolation.py": '''
import unittest

from flow import Task, TaskGraph, UnknownTask


def diamond():
    return TaskGraph([Task("root"),
                      Task("left", depends_on=frozenset({"root"})),
                      Task("right", depends_on=frozenset({"root"})),
                      Task("join", depends_on=frozenset({"left", "right"}))])


class TestReadsDoNotMutate(unittest.TestCase):
    def test_mutating_the_result_does_not_touch_the_graph(self):
        graph = diamond()
        graph.dependents_of("root").add("intruder")
        self.assertEqual(graph.dependents_of("root"), {"left", "right"})

    def test_topological_order_is_unaffected(self):
        graph = diamond()
        before = graph.topological_order()
        graph.dependents_of("root").add("intruder")
        graph.dependents_of("left").add("another")
        self.assertEqual(graph.topological_order(), before)

    def test_upstream_result_is_also_a_copy(self):
        graph = diamond()
        graph.upstream_of("join").add("intruder")
        self.assertEqual(graph.upstream_of("join"), {"left", "right"})

    def test_descendants_unaffected_by_mutation(self):
        graph = diamond()
        graph.dependents_of("root").add("ghost")
        self.assertEqual(graph.descendants_of("root"), {"left", "right", "join"})


class TestGraphStillReadsCorrectly(unittest.TestCase):
    def test_dependents(self):
        self.assertEqual(diamond().dependents_of("root"), {"left", "right"})

    def test_leaf_has_no_dependents(self):
        self.assertEqual(diamond().dependents_of("join"), set())

    def test_unknown_task_raises(self):
        with self.assertRaises(UnknownTask):
            diamond().dependents_of("nope")

    def test_topological_order_is_valid(self):
        order = diamond().topological_order()
        self.assertLess(order.index("root"), order.index("left"))
        self.assertLess(order.index("left"), order.index("join"))
'''})

# --------------------------------------------------- condition scope check
make(R, "condition-scope-direct-only",
     spec("python", "logic", 4, """
A graph we expected to be rejected ran anyway, and gated the wrong task.

We rely on the pre-run checks to catch conditions that reference something they
shouldn't. A task whose condition names a task two levels upstream of it passes
validation, then evaluates that name as false at run time because the result
isn't in scope, so the task is silently skipped on every run.

Either the check or the evaluation is wrong about which names are legitimate.
They should agree. Make validation accept exactly the names a condition can
actually read.
"""),
     [("flow/validation.py",
       """        upstream = graph.ancestors_of(task.task_id)""",
       """        upstream = graph.upstream_of(task.task_id)""")],
     {"test_condition_scope.py": '''
import unittest

from flow import Task, TaskGraph, validate_all


def chain_with_condition(condition):
    return TaskGraph([
        Task("a"),
        Task("b", depends_on=frozenset({"a"})),
        Task("c", depends_on=frozenset({"b"}), condition=condition),
    ])


class TestTransitiveNamesAreLegal(unittest.TestCase):
    def test_grandparent_is_accepted(self):
        self.assertEqual(validate_all(chain_with_condition("a"), {}), [])

    def test_direct_parent_is_accepted(self):
        self.assertEqual(validate_all(chain_with_condition("b"), {}), [])

    def test_combination_of_both_is_accepted(self):
        self.assertEqual(validate_all(chain_with_condition("a and b"), {}), [])

    def test_deep_ancestor_is_accepted(self):
        graph = TaskGraph([Task("a"),
                           Task("b", depends_on=frozenset({"a"})),
                           Task("c", depends_on=frozenset({"b"})),
                           Task("d", depends_on=frozenset({"c"}), condition="a")])
        self.assertEqual(validate_all(graph, {}), [])


class TestOutOfScopeStillRejected(unittest.TestCase):
    def test_unrelated_task_is_rejected(self):
        graph = TaskGraph([Task("a"), Task("x"),
                           Task("b", depends_on=frozenset({"a"}), condition="x")])
        problems = validate_all(graph, {})
        self.assertTrue(any("x" in p for p in problems), problems)

    def test_downstream_task_is_rejected(self):
        graph = TaskGraph([Task("a", condition="b"),
                           Task("b", depends_on=frozenset({"a"}))])
        self.assertTrue(validate_all(graph, {}))

    def test_no_condition_is_fine(self):
        self.assertEqual(validate_all(chain_with_condition(None), {}), [])
'''})

print("done")