File size: 9,667 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 | #!/usr/bin/env python3
"""Batch 8: widen the distinct-defect pool.
The corpus was reuse-limited, not task-limited: 60 tasks drawn from 29 defects
meant a model failing one defect failed up to 8 tasks, so the effective number
of independent signals was far below the task count. These add distinct defects
so compounds can be composed with less overlap.
"""
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"
make(FLOW, "requires-wrong-amount",
spec("python", "logic", 3, """
Tasks are admitted that the pool cannot actually support.
A task declaring it needs 3 units of "cpu" is admitted against a pool with only
1 free, and the run then fails when it tries to take them. Asking the task what
it needs comes back with the wrong number.
"""),
[("flow/task.py",
""" for request in self.resources:
if request.name == name:
return request.amount
return 0""",
""" for request in self.resources:
if request.name == name:
return 1
return 0""")],
{"test_requires.py": '''
import unittest
from flow import ResourceRequest, Task
def task(*reqs):
return Task("t", resources=tuple(ResourceRequest(n, a) for n, a in reqs))
class TestRequires(unittest.TestCase):
def test_reports_the_declared_amount(self):
self.assertEqual(task(("cpu", 3)).requires("cpu"), 3)
def test_amount_of_one_still_reports_one(self):
self.assertEqual(task(("cpu", 1)).requires("cpu"), 1)
def test_several_pools_report_independently(self):
t = task(("cpu", 2), ("gpu", 5))
self.assertEqual((t.requires("cpu"), t.requires("gpu")), (2, 5))
def test_large_amounts(self):
self.assertEqual(task(("slots", 64)).requires("slots"), 64)
class TestRequiresEdges(unittest.TestCase):
def test_undeclared_resource_is_zero(self):
self.assertEqual(task(("cpu", 2)).requires("gpu"), 0)
def test_no_resources_is_zero(self):
self.assertEqual(Task("t").requires("cpu"), 0)
'''})
make(FLOW, "roots-includes-dependents",
spec("python", "logic", 3, """
Our graph visualiser draws every task as a starting point.
The entry points it renders include tasks that plainly have dependencies, so
the diagram shows a workflow with no structure. Execution itself is fine; it is
only the reported set of roots that is wrong.
"""),
[("flow/graph.py",
""" return sorted(t.task_id for t in self._tasks.values() if not t.depends_on)""",
""" return sorted(self._tasks)""")],
{"test_roots.py": '''
import unittest
from flow import Task, TaskGraph
def diamond():
return TaskGraph([Task("a"),
Task("b", depends_on=frozenset({"a"})),
Task("c", depends_on=frozenset({"a"})),
Task("d", depends_on=frozenset({"b", "c"}))])
class TestRoots(unittest.TestCase):
def test_only_dependency_free_tasks(self):
self.assertEqual(diamond().roots(), ["a"])
def test_several_roots(self):
g = TaskGraph([Task("x"), Task("y"),
Task("z", depends_on=frozenset({"x"}))])
self.assertEqual(g.roots(), ["x", "y"])
def test_a_chain_has_one_root(self):
g = TaskGraph([Task("a"), Task("b", depends_on=frozenset({"a"})),
Task("c", depends_on=frozenset({"b"}))])
self.assertEqual(g.roots(), ["a"])
def test_every_task_independent(self):
self.assertEqual(TaskGraph([Task("b"), Task("a")]).roots(), ["a", "b"])
class TestLeavesUnaffected(unittest.TestCase):
def test_leaves_are_terminal_tasks(self):
self.assertEqual(diamond().leaves(), ["d"])
def test_empty_graph(self):
self.assertEqual(TaskGraph().roots(), [])
'''})
make(FLOW, "should-retry-off-by-one",
spec("python", "logic", 3, """
Retry policies run one attempt too many.
A task configured with max_attempts=1 -- which we use to mean "do not retry" --
is attempted twice. max_attempts is documented as the total number of attempts,
so a value of 1 means one attempt and no retry.
"""),
[("flow/retry.py",
""" return attempts_made < self.max_attempts""",
""" return attempts_made <= self.max_attempts""")],
{"test_should_retry.py": '''
import unittest
from flow import NO_RETRY, ResourcePool, RetryPolicy, Scheduler, Task, TaskGraph
from flow import state as st
class TestAttemptBudget(unittest.TestCase):
def test_one_attempt_means_no_retry(self):
self.assertFalse(RetryPolicy(max_attempts=1).should_retry(1))
def test_three_attempts_allows_two_retries(self):
p = RetryPolicy(max_attempts=3)
self.assertEqual([p.should_retry(n) for n in (1, 2, 3)], [True, True, False])
def test_no_retry_constant(self):
self.assertFalse(NO_RETRY.should_retry(1))
def test_first_attempt_is_always_allowed(self):
self.assertTrue(RetryPolicy(max_attempts=2).should_retry(0))
def test_run_fails_after_the_budget(self):
s = Scheduler(TaskGraph([Task("j", retry=RetryPolicy(max_attempts=1))]),
ResourcePool({}))
state = s.new_state()
s.start("j", state)
s.fail("j", state)
self.assertEqual(state.get("j"), st.FAILED)
class TestBackoffUnaffected(unittest.TestCase):
def test_delays_unchanged(self):
p = RetryPolicy(max_attempts=5, base_delay=2.0, multiplier=3.0)
self.assertEqual([p.delay_for(n) for n in (1, 2)], [2.0, 6.0])
'''})
make(ROUTER, "duplicate-route-undetected",
spec("typescript", "logic", 3, """
Registering the same route twice is silently accepted.
Two teams added a handler for the same path in different spellings -- one with
a trailing slash -- and both registrations succeeded. Requests then go to
whichever happened to win, which is not something we can reason about. A
duplicate registration is meant to be rejected.
"""),
[("src/router.ts",
""" if (table.patterns().some((existing) => normalise(existing) === canonical)) {
throw new DuplicateRoute(pattern);
}""",
""" if (table.patterns().includes(pattern)) {
throw new DuplicateRoute(pattern);
}""")],
{"duplicate.test.ts": '''
import { test } from 'node:test';
import assert from 'node:assert';
import { Router, DuplicateRoute } from '../src/index.ts';
const H = async () => ({ status: 200, body: '' });
test('the same pattern twice is rejected', () => {
const r = new Router();
r.add('GET', '/a', H);
assert.throws(() => r.add('GET', '/a', H), DuplicateRoute);
});
test('a trailing slash is the same route', () => {
const r = new Router();
r.add('GET', '/a/b', H);
assert.throws(() => r.add('GET', '/a/b/', H), DuplicateRoute);
});
test('a missing leading slash is the same route', () => {
const r = new Router();
r.add('GET', '/a/b', H);
assert.throws(() => r.add('GET', 'a/b', H), DuplicateRoute);
});
test('repeated slashes are the same route', () => {
const r = new Router();
r.add('GET', '/a/b', H);
assert.throws(() => r.add('GET', '/a//b', H), DuplicateRoute);
});
test('different paths are fine', () => {
const r = new Router();
r.add('GET', '/a', H);
r.add('GET', '/b', H);
assert.strictEqual(r.resolve('GET', '/b')!.pattern, '/b');
});
test('the same path under a different method is fine', () => {
const r = new Router();
r.add('GET', '/a', H);
r.add('POST', '/a', H);
assert.deepStrictEqual(r.methods(), ['GET', 'POST']);
});
test('different parameter names are still distinct patterns', () => {
const r = new Router();
r.add('GET', '/u/:id', H);
assert.throws(() => r.add('GET', '/u/:id', H), DuplicateRoute);
});
'''})
make(ROUTER, "headers-all-aliases",
spec("typescript", "logic", 4, """
Reading a header can change it.
Our logging layer collects a request's Set-Cookie values and appends a redaction
marker to the list it got back. Downstream, the request carries that marker as a
real cookie value.
Reading a header should not hand out a reference the caller can mutate.
"""),
[("src/headers.ts",
""" all(name: string): string[] {
return [...(this.store.get(Headers.key(name)) ?? [])];
}""",
""" all(name: string): string[] {
return this.store.get(Headers.key(name)) ?? [];
}""")],
{"headers-alias.test.ts": '''
import { test } from 'node:test';
import assert from 'node:assert';
import { Headers } from '../src/index.ts';
test('mutating the result does not change the header', () => {
const h = new Headers({ 'Set-Cookie': 'a=1' });
h.all('set-cookie').push('REDACTED');
assert.deepStrictEqual(h.all('set-cookie'), ['a=1']);
});
test('mutation does not leak across reads', () => {
const h = new Headers({ 'X-A': '1' });
const first = h.all('x-a');
first.push('2');
assert.deepStrictEqual(h.all('x-a'), ['1']);
});
test('get is unaffected by a mutated all()', () => {
const h = new Headers({ 'X-A': '1' });
h.all('x-a').length = 0;
assert.strictEqual(h.get('x-a'), '1');
});
test('multiple values are still returned', () => {
const h = new Headers();
h.append('a', '1'); h.append('a', '2');
assert.deepStrictEqual(h.all('a'), ['1', '2']);
});
test('absent header returns an empty list', () => {
assert.deepStrictEqual(new Headers().all('nope'), []);
});
test('append still accumulates', () => {
const h = new Headers();
h.append('a', '1'); h.append('a', '2'); h.append('a', '3');
assert.strictEqual(h.all('a').length, 3);
});
'''})
print("done")
|