#!/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(); 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(); 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(); 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(); t.add('/u/:id', 'param'); assert.strictEqual(t.match('/u/9')!.params.id, '9'); assert.strictEqual(t.match('/u/9/x'), undefined); }); '''}) print("done")