SACB / source /tools /tasks_batch5.py
ilintar's picture
Add corpus source: base repos, task overlays, hidden tests, and the authoring tools
9368cc4 verified
Raw
History Blame Contribute Delete
10.5 kB
#!/usr/bin/env python3
"""Batch 5: more algorithm-shaped repairs across both repos."""
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"
# ---------------------------------------------- calendar: next open window
make(FLOW, "next-open-skips-windows",
spec("python", "logic", 4, """
Jobs deferred outside their maintenance window come back at the wrong time.
We ask the calendar when a task may next start. With several windows configured
and the current time sitting after the first has closed, the answer we get is a
time that has already passed, so the caller schedules the work immediately and
it runs outside any window at all.
Asking for the next permitted time should never hand back a time in the past.
"""),
[("flow/calendar.py",
""" if self.is_open(when):
return when
for window in self.windows:
if window.start >= when:
return window.start
return None""",
""" if self.is_open(when):
return when
return self.windows[0].start""")],
{"test_next_open.py": '''
import unittest
from flow import Calendar, Window
def cal():
return Calendar([Window(10.0, 20.0), Window(30.0, 40.0), Window(50.0, 60.0)])
class TestNextOpenLooksForward(unittest.TestCase):
def test_between_windows_finds_the_following_one(self):
self.assertEqual(cal().next_open(25.0), 30.0)
def test_after_the_second_window_finds_the_third(self):
self.assertEqual(cal().next_open(45.0), 50.0)
def test_never_returns_a_past_time(self):
c = cal()
for when in (0.0, 5.0, 21.0, 25.0, 41.0, 45.0, 55.0):
result = c.next_open(when)
if result is not None:
self.assertGreaterEqual(result, when, f"when={when}")
def test_after_every_window_returns_none(self):
self.assertIsNone(cal().next_open(100.0))
def test_before_all_windows_returns_the_first(self):
self.assertEqual(cal().next_open(0.0), 10.0)
class TestNextOpenOtherwiseUnchanged(unittest.TestCase):
def test_inside_a_window_returns_now(self):
self.assertEqual(cal().next_open(15.0), 15.0)
def test_exactly_at_a_start_returns_now(self):
self.assertEqual(cal().next_open(30.0), 30.0)
def test_empty_calendar_returns_now(self):
self.assertEqual(Calendar().next_open(7.0), 7.0)
def test_window_end_is_not_open(self):
self.assertEqual(cal().next_open(20.0), 30.0)
'''})
# ---------------------------------------------- skip on false condition
make(FLOW, "condition-false-never-settles",
spec("python", "logic", 4, """
Runs that use conditional tasks hang at the end.
Our graph has an optional publish step gated on a condition. On runs where the
condition comes out false the step is correctly never started -- but the run
then never reports itself complete, because that task sits pending forever and
so does everything after it. Runs where the condition is true finish fine.
Everything that will never run needs to reach a terminal state.
"""),
[("flow/scheduler.py",
""" if not self.upstream_satisfied(task, state):
state.set(task_id, st.SKIPPED)
skipped.append(task_id)
elif not self.condition_holds(task, state):
state.set(task_id, st.SKIPPED)
skipped.append(task_id)""",
""" if not self.upstream_satisfied(task, state):
state.set(task_id, st.SKIPPED)
skipped.append(task_id)""")],
{"test_settle.py": '''
import unittest
from flow import ResourcePool, Scheduler, Task, TaskGraph
from flow import state as st
def build(condition):
tasks = [Task("build"),
Task("publish", depends_on=frozenset({"build"}), condition=condition),
Task("notify", depends_on=frozenset({"publish"}))]
return Scheduler(TaskGraph(tasks), ResourcePool({}))
class TestFalseConditionSettles(unittest.TestCase):
def test_gated_task_is_skipped(self):
s = build("build")
state = s.new_state()
s.start("build", state)
s.finish("build", state, False) # condition fact is falsy
s.settle_unreachable(state)
self.assertEqual(state.get("publish"), st.SKIPPED)
def test_downstream_of_a_skip_also_settles(self):
s = build("build")
state = s.new_state()
s.start("build", state)
s.finish("build", state, False)
for _ in range(3):
s.settle_unreachable(state)
self.assertEqual(state.get("notify"), st.SKIPPED)
def test_run_completes(self):
s = build("build")
state = s.new_state()
s.start("build", state)
s.finish("build", state, False)
for _ in range(3):
s.settle_unreachable(state)
self.assertTrue(state.is_complete())
def test_settle_reports_what_it_skipped(self):
s = build("build")
state = s.new_state()
s.start("build", state)
s.finish("build", state, False)
self.assertIn("publish", s.settle_unreachable(state))
class TestTrueConditionStillRuns(unittest.TestCase):
def test_gated_task_runs_when_condition_holds(self):
s = build("build")
state = s.new_state()
s.start("build", state)
s.finish("build", state, True)
s.settle_unreachable(state)
self.assertEqual(state.get("publish"), st.PENDING)
self.assertIn("publish", s.next_batch(state))
def test_unconditional_task_is_untouched(self):
s = build(None)
state = s.new_state()
s.start("build", state)
s.finish("build", state, False)
s.settle_unreachable(state)
self.assertEqual(state.get("publish"), st.PENDING)
def test_failed_upstream_still_skips(self):
s = build(None)
state = s.new_state()
s.start("build", state)
s.fail("build", state)
self.assertEqual(state.get("publish"), st.SKIPPED)
'''})
# ---------------------------------------------- query repeats
make(ROUTER, "query-repeats-lost",
spec("typescript", "logic", 4, """
Multi-select filters only ever apply the last value.
Our UI sends `?tag=red&tag=blue&tag=green` when several tags are selected, and
the API behaves as though only green were chosen. Single-value parameters are
fine.
Repeated keys should collect every value, in the order they were sent.
"""),
[("src/query.ts",
""" if (out[key]) out[key].push(value);
else out[key] = [value];""",
""" out[key] = [value];""")],
{"query.test.ts": '''
import { test } from 'node:test';
import assert from 'node:assert';
import { parseQuery, first } from '../src/index.ts';
test('repeated keys collect every value', () => {
assert.deepStrictEqual(parseQuery('?tag=red&tag=blue&tag=green').tag,
['red', 'blue', 'green']);
});
test('order is preserved', () => {
assert.deepStrictEqual(parseQuery('a=1&a=2&a=3').a, ['1', '2', '3']);
});
test('repeats mixed with singles', () => {
const q = parseQuery('tag=a&page=2&tag=b');
assert.deepStrictEqual(q.tag, ['a', 'b']);
assert.deepStrictEqual(q.page, ['2']);
});
test('duplicate identical values are all kept', () => {
assert.deepStrictEqual(parseQuery('x=1&x=1').x, ['1', '1']);
});
test('single values still work', () => {
assert.deepStrictEqual(parseQuery('?page=2'), { page: ['2'] });
});
test('valueless keys are present and empty', () => {
assert.deepStrictEqual(parseQuery('?verbose').verbose, ['']);
});
test('percent and plus decoding still work', () => {
assert.deepStrictEqual(parseQuery('q=a%20b').q, ['a b']);
assert.deepStrictEqual(parseQuery('q=a+b').q, ['a b']);
});
test('empty query is an empty object', () => {
assert.deepStrictEqual(parseQuery(''), {});
assert.deepStrictEqual(parseQuery('?'), {});
});
test('first() returns the leading value', () => {
assert.strictEqual(first(parseQuery('tag=a&tag=b'), 'tag'), 'a');
assert.strictEqual(first(parseQuery(''), 'tag'), undefined);
});
'''})
# ---------------------------------------------- header case sensitivity
make(ROUTER, "header-case-sensitive",
spec("typescript", "logic", 3, """
Header lookups miss depending on which client sent the request.
Clients that send `content-type` are handled; clients that send `Content-Type`
are treated as though the header were absent, and our content negotiation then
falls back to a default. Both spellings mean the same thing over HTTP.
"""),
[("src/headers.ts",
""" private static key(name: string): string {
return name.toLowerCase();
}""",
""" private static key(name: string): string {
return name;
}""")],
{"headers.test.ts": '''
import { test } from 'node:test';
import assert from 'node:assert';
import { Headers } from '../src/index.ts';
test('lookup ignores case', () => {
const h = new Headers({ 'Content-Type': 'text/html' });
assert.strictEqual(h.get('content-type'), 'text/html');
assert.strictEqual(h.get('CONTENT-TYPE'), 'text/html');
assert.strictEqual(h.get('Content-Type'), 'text/html');
});
test('has ignores case', () => {
const h = new Headers({ 'X-Trace': '1' });
assert.ok(h.has('x-trace'));
assert.ok(h.has('X-TRACE'));
});
test('setting twice in different cases replaces', () => {
const h = new Headers();
h.set('Accept', 'a');
h.set('accept', 'b');
assert.strictEqual(h.get('ACCEPT'), 'b');
assert.deepStrictEqual(h.names(), ['accept']);
});
test('append across cases accumulates on one field', () => {
const h = new Headers();
h.append('Set-Cookie', 'a=1');
h.append('set-cookie', 'b=2');
assert.deepStrictEqual(h.all('SET-COOKIE'), ['a=1', 'b=2']);
});
test('delete ignores case', () => {
const h = new Headers({ 'X-A': '1' });
assert.ok(h.delete('x-a'));
assert.ok(!h.has('X-A'));
});
test('names are normalised', () => {
const h = new Headers({ 'Content-Type': 'a', 'X-Trace': 'b' });
assert.deepStrictEqual(h.names(), ['content-type', 'x-trace']);
});
test('values keep their own case', () => {
const h = new Headers({ 'Content-Type': 'Text/HTML' });
assert.strictEqual(h.get('content-type'), 'Text/HTML');
});
test('all() returns a copy', () => {
const h = new Headers({ 'A': '1' });
h.all('a').push('2');
assert.deepStrictEqual(h.all('a'), ['1']);
});
'''})
print("done")