File size: 11,316 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
#!/usr/bin/env python3
"""Batch 4: repairs that require an algorithm, not an operator."""
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent))
from make_tasks import make, spec  # noqa: E402

FLOW = "python/scheduler"
ROUTER = "typescript/router"

# ---------------------------------------------- two-phase acquisition
make(FLOW, "acquire-not-atomic",
     spec("python", "logic", 5, """
Capacity disappears whenever a task cannot be admitted.

One of our tasks needs both a "cpu" unit and a "gpu" unit. When gpu capacity is
exhausted the start attempt fails, which we expect and handle -- but the cpu
unit that task wanted is gone for the rest of the run. Do that a few times and
the cpu pool is empty with nothing running.

A task that fails to be admitted should hold nothing at all afterwards.
"""),
     [("flow/resources.py",
       """        requests = list(requests)
        for request in requests:
            if request.name not in self.capacity:
                raise UnknownResource(request.name)
            if self.free(request.name) < request.amount:
                raise ResourceExhausted(request.name, request.amount,
                                        self.free(request.name))
        holding = self._held.setdefault(task_id, {})
        for request in requests:
            holding[request.name] = holding.get(request.name, 0) + request.amount""",
       """        holding = self._held.setdefault(task_id, {})
        for request in requests:
            if request.name not in self.capacity:
                raise UnknownResource(request.name)
            if self.free(request.name) < request.amount:
                raise ResourceExhausted(request.name, request.amount,
                                        self.free(request.name))
            holding[request.name] = holding.get(request.name, 0) + request.amount""")],
     {"test_atomic_acquire.py": '''
import unittest

from flow import ResourcePool, ResourceRequest, ResourceExhausted, UnknownResource


def pool():
    return ResourcePool({"cpu": 4, "gpu": 1})


BOTH = (ResourceRequest("cpu", 1), ResourceRequest("gpu", 1))


class TestAcquireIsAllOrNothing(unittest.TestCase):
    def test_failed_acquire_holds_nothing(self):
        p = pool()
        p.acquire("holder", (ResourceRequest("gpu", 1),))
        with self.assertRaises(ResourceExhausted):
            p.acquire("loser", BOTH)
        self.assertEqual(p.held_by("loser"), {})

    def test_failed_acquire_leaves_capacity_intact(self):
        p = pool()
        p.acquire("holder", (ResourceRequest("gpu", 1),))
        with self.assertRaises(ResourceExhausted):
            p.acquire("loser", BOTH)
        self.assertEqual(p.free("cpu"), 4)

    def test_repeated_failures_do_not_drain_the_pool(self):
        p = pool()
        p.acquire("holder", (ResourceRequest("gpu", 1),))
        for i in range(4):
            with self.assertRaises(ResourceExhausted):
                p.acquire(f"loser{i}", BOTH)
        self.assertEqual(p.free("cpu"), 4)

    def test_unknown_resource_also_holds_nothing(self):
        p = pool()
        with self.assertRaises(UnknownResource):
            p.acquire("loser", (ResourceRequest("cpu", 1), ResourceRequest("nope", 1)))
        self.assertEqual(p.held_by("loser"), {})
        self.assertEqual(p.free("cpu"), 4)


class TestAcquireStillWorks(unittest.TestCase):
    def test_successful_acquire_holds_everything(self):
        p = pool()
        p.acquire("job", BOTH)
        self.assertEqual(p.held_by("job"), {"cpu": 1, "gpu": 1})

    def test_release_returns_capacity(self):
        p = pool()
        p.acquire("job", BOTH)
        p.release("job")
        self.assertEqual(p.free("cpu"), 4)
        self.assertEqual(p.free("gpu"), 1)

    def test_exhaustion_is_still_reported(self):
        p = pool()
        p.acquire("a", (ResourceRequest("gpu", 1),))
        with self.assertRaises(ResourceExhausted):
            p.acquire("b", (ResourceRequest("gpu", 1),))

    def test_no_requests_is_a_noop(self):
        p = pool()
        p.acquire("job", ())
        self.assertEqual(p.free("cpu"), 4)
'''})

# ---------------------------------------------- topological ordering
make(FLOW, "topo-order-nondeterministic",
     spec("python", "logic", 5, """
Two problems with the order we execute graphs in, which may share a cause.

First, the order is not stable: building the same graph twice, adding the tasks
in a different order each time, gives two different execution orders. Our
release checks diff these, so every unrelated change shows up as a difference.

Second, a graph containing a dependency cycle is no longer rejected. It used to
raise; now it comes back with an order that silently omits the tasks in the
cycle, and the run just never executes them.

Dependencies are still respected in the orders we get, so this is not about
correctness of the ordering itself -- it is about it being reproducible and
about cycles being caught.
"""),
     [("flow/graph.py",
       """        indegree = {tid: len(self._tasks[tid].depends_on) for tid in self._tasks}
        ready = sorted(tid for tid, n in indegree.items() if n == 0)
        order: List[str] = []
        while ready:
            current = ready.pop(0)
            order.append(current)
            for downstream in sorted(self._dependents.get(current, ())):
                indegree[downstream] -= 1
                if indegree[downstream] == 0:
                    ready.append(downstream)
            ready.sort()
        if len(order) != len(self._tasks):
            raise CyclicGraph(sorted(set(self._tasks) - set(order)))
        return order""",
       """        order: List[str] = []
        seen: Set[str] = set()

        def visit(task_id: str) -> None:
            if task_id in seen:
                return
            seen.add(task_id)
            for upstream in self._tasks[task_id].depends_on:
                if upstream in self._tasks:
                    visit(upstream)
            order.append(task_id)

        for task_id in self._tasks:
            visit(task_id)
        return order""")],
     {"test_topo.py": '''
import unittest

from flow import CyclicGraph, Task, TaskGraph


def graph(pairs):
    """pairs: [(task_id, [deps])] in the order they should be added."""
    return TaskGraph([Task(tid, depends_on=frozenset(deps)) for tid, deps in pairs])


DIAMOND = [("d", ["b", "c"]), ("b", ["a"]), ("c", ["a"]), ("a", [])]


class TestOrderIsReproducible(unittest.TestCase):
    def test_insertion_order_does_not_change_the_result(self):
        forward = graph(DIAMOND).topological_order()
        reverse = graph(list(reversed(DIAMOND))).topological_order()
        self.assertEqual(forward, reverse)

    def test_ties_are_broken_by_id(self):
        order = graph([("b", []), ("a", []), ("c", [])]).topological_order()
        self.assertEqual(order, ["a", "b", "c"])

    def test_diamond_has_one_canonical_order(self):
        self.assertEqual(graph(DIAMOND).topological_order(), ["a", "b", "c", "d"])

    def test_repeated_calls_agree(self):
        g = graph(DIAMOND)
        self.assertEqual(g.topological_order(), g.topological_order())


class TestCyclesAreRejected(unittest.TestCase):
    def test_two_task_cycle_raises(self):
        g = TaskGraph([Task("a", depends_on=frozenset({"b"})),
                       Task("b", depends_on=frozenset({"a"}))])
        with self.assertRaises(CyclicGraph):
            g.topological_order()

    def test_three_task_cycle_raises(self):
        g = TaskGraph([Task("a", depends_on=frozenset({"c"})),
                       Task("b", depends_on=frozenset({"a"})),
                       Task("c", depends_on=frozenset({"b"}))])
        with self.assertRaises(CyclicGraph):
            g.topological_order()

    def test_validate_rejects_a_cycle(self):
        g = TaskGraph([Task("a", depends_on=frozenset({"b"})),
                       Task("b", depends_on=frozenset({"a"}))])
        with self.assertRaises(CyclicGraph):
            g.validate()


class TestOrderIsStillCorrect(unittest.TestCase):
    def test_dependencies_come_first(self):
        order = graph(DIAMOND).topological_order()
        self.assertLess(order.index("a"), order.index("b"))
        self.assertLess(order.index("b"), order.index("d"))

    def test_every_task_appears_once(self):
        order = graph(DIAMOND).topological_order()
        self.assertEqual(sorted(order), ["a", "b", "c", "d"])

    def test_long_chain(self):
        chain = [(chr(ord("a") + i), [chr(ord("a") + i - 1)] if i else [])
                 for i in range(6)]
        self.assertEqual(graph(chain).topological_order(),
                         [chr(ord("a") + i) for i in range(6)])
'''})

# ---------------------------------------------- wildcard remainder
make(ROUTER, "wildcard-remainder",
     spec("typescript", "logic", 4, """
Our static file route stopped serving anything in a subdirectory.

The route is /assets/*path. A request for /assets/logo.svg still works, but
/assets/img/logo.svg returns no match at all, and when a single-segment request
does match, the captured parameter is only that one segment.

A wildcard is supposed to swallow the whole remainder of the path, however many
segments that is. Please restore that.
"""),
     [("src/trie.ts",
       """    if (segment.kind === 'wildcard') {
      params[segment.value] = parts.slice(i).join('/');
      return params;
    }""",
       """    if (segment.kind === 'wildcard') {
      if (i >= parts.length) return undefined;
      params[segment.value] = parts[i];
      continue;
    }""")],
     {"wildcard.test.ts": '''
import { test } from 'node:test';
import assert from 'node:assert';
import { RouteTable } from '../src/index.ts';

function table() {
  const t = new RouteTable<string>();
  t.add('/assets/*path', 'assets');
  return t;
}

test('wildcard captures a nested path', () => {
  const m = table().match('/assets/img/logo.svg');
  assert.strictEqual(m!.route.value, 'assets');
  assert.strictEqual(m!.params.path, 'img/logo.svg');
});

test('wildcard captures a deep path', () => {
  assert.strictEqual(table().match('/assets/a/b/c/d')!.params.path, 'a/b/c/d');
});

test('wildcard still captures a single segment', () => {
  assert.strictEqual(table().match('/assets/logo.svg')!.params.path, 'logo.svg');
});

test('wildcard matches an empty remainder', () => {
  assert.strictEqual(table().match('/assets')!.params.path, '');
});

test('named wildcard alongside params', () => {
  const t = new RouteTable<string>();
  t.add('/u/:id/files/*rest', 'files');
  const m = t.match('/u/7/files/a/b.txt');
  assert.strictEqual(m!.params.id, '7');
  assert.strictEqual(m!.params.rest, 'a/b.txt');
});

test('non-matching prefix still fails', () => {
  assert.strictEqual(table().match('/other/x'), undefined);
});

test('static routes are unaffected', () => {
  const t = new RouteTable<string>();
  t.add('/a/b', 'static');
  assert.strictEqual(t.match('/a/b')!.route.value, 'static');
  assert.strictEqual(t.match('/a/b/c'), undefined);
});

test('param routes are unaffected', () => {
  const t = new RouteTable<string>();
  t.add('/u/:id', 'param');
  assert.strictEqual(t.match('/u/9')!.params.id, '9');
  assert.strictEqual(t.match('/u/9/x'), undefined);
});
'''})

print("done")