SACB / source /tools /tasks_batch8.py
ilintar's picture
Add corpus source: base repos, task overlays, hidden tests, and the authoring tools
9368cc4 verified
Raw
History Blame Contribute Delete
9.67 kB
#!/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")