File size: 10,360 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
#!/usr/bin/env python3
"""Compound tasks: several independent defects in one report.

Each sub-defect has its own fail_to_pass tests and its own cause, and no single
edit repairs more than one. Framed as a triage ticket, which is how a batch of
unrelated findings actually arrives.
"""
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"

# ============================================================ flow, 3 defects
make(FLOW, "incident-triage",
     spec("python", "logic", 5, """
Three findings from last night's incident review. They are unrelated to each
other; please fix all three.

1. A job started at the exact instant its maintenance window closed and
   overlapped the next slot's owner. Windows are documented as half-open, so a
   task may begin at a window's start but not at its end.

2. Retry backoff is one step too long everywhere. The first retry of a policy
   with base_delay=10 and multiplier=2 waited 20 seconds rather than 10, the
   second waited 40, and so on. The first retry should wait exactly base_delay.

3. The run summary reports every event count as zero, even for runs where tasks
   demonstrably started and finished. The per-task event timeline is correct;
   it is only the counters that are empty.
"""),
     [("flow/calendar.py",
       """    def contains(self, when: float) -> bool:
        return self.start <= when < self.end""",
       """    def contains(self, when: float) -> bool:
        return self.start <= when <= self.end"""),
      ("flow/retry.py",
       """        delay = self.base_delay * (self.multiplier ** (attempts_made - 1))""",
       """        delay = self.base_delay * (self.multiplier ** attempts_made)"""),
      ("flow/metrics.py",
       """    def record(self, when: float, task_id: str, event: str) -> None:
        self.timeline.append((when, task_id, event))
        self.bump(event)""",
       """    def record(self, when: float, task_id: str, event: str) -> None:
        self.timeline.append((when, task_id, event))""")],
     {"test_windows_boundary.py": '''
import unittest

from flow import Calendar, Window


class TestWindowBoundary(unittest.TestCase):
    def test_end_is_excluded(self):
        self.assertFalse(Window(10.0, 20.0).contains(20.0))

    def test_start_is_included(self):
        self.assertTrue(Window(10.0, 20.0).contains(10.0))

    def test_adjacent_windows_never_overlap(self):
        a, b = Window(0.0, 10.0), Window(10.0, 20.0)
        self.assertEqual([t for t in (0.0, 5.0, 10.0, 15.0)
                          if a.contains(t) and b.contains(t)], [])

    def test_calendar_is_closed_at_the_end(self):
        self.assertFalse(Calendar([Window(10.0, 20.0)]).is_open(20.0))

    def test_inside_still_open(self):
        self.assertTrue(Calendar([Window(10.0, 20.0)]).is_open(15.0))
''',
      "test_backoff.py": '''
import unittest

from flow import RetryPolicy


class TestBackoffProgression(unittest.TestCase):
    def test_first_retry_waits_base_delay(self):
        self.assertEqual(RetryPolicy(max_attempts=5, base_delay=10.0,
                                     multiplier=2.0).delay_for(1), 10.0)

    def test_progression_doubles_from_base(self):
        p = RetryPolicy(max_attempts=5, base_delay=10.0, multiplier=2.0)
        self.assertEqual([p.delay_for(n) for n in (1, 2, 3)], [10.0, 20.0, 40.0])

    def test_multiplier_of_one_is_constant(self):
        p = RetryPolicy(max_attempts=5, base_delay=7.0, multiplier=1.0)
        self.assertEqual([p.delay_for(n) for n in (1, 2, 3)], [7.0, 7.0, 7.0])

    def test_no_wait_before_the_first_attempt(self):
        self.assertEqual(RetryPolicy(max_attempts=3, base_delay=10.0).delay_for(0), 0.0)

    def test_clamped_at_max_delay(self):
        p = RetryPolicy(max_attempts=20, base_delay=10.0, multiplier=2.0, max_delay=25.0)
        self.assertEqual(p.delay_for(9), 25.0)
''',
      "test_metrics_counters.py": '''
import unittest

from flow import Metrics, ResourcePool, Scheduler, Task, TaskGraph


class TestCountersAreKept(unittest.TestCase):
    def test_record_bumps_the_counter(self):
        m = Metrics()
        m.record(0.0, "a", "started")
        self.assertEqual(m.count("started"), 1)

    def test_counts_accumulate(self):
        m = Metrics()
        for i in range(3):
            m.record(float(i), f"t{i}", "started")
        self.assertEqual(m.count("started"), 3)

    def test_summary_reports_events(self):
        m = Metrics()
        m.record(0.0, "a", "started")
        m.record(1.0, "a", "succeeded")
        self.assertEqual(m.summary(), {"started": 1, "succeeded": 1})

    def test_a_real_run_reports_counts(self):
        s = Scheduler(TaskGraph([Task("a")]), ResourcePool({}))
        state = s.new_state()
        s.start("a", state)
        s.finish("a", state, True)
        self.assertEqual(s.metrics.count("started"), 1)
        self.assertEqual(s.metrics.count("succeeded"), 1)

    def test_timeline_is_still_recorded(self):
        m = Metrics()
        m.record(0.0, "a", "started")
        self.assertEqual(m.events_for("a"), ["started"])

    def test_bump_still_works_directly(self):
        m = Metrics()
        m.bump("custom", 5)
        self.assertEqual(m.count("custom"), 5)
'''})

# ========================================================== router, 3 defects
make(ROUTER, "api-review-findings",
     spec("typescript", "logic", 5, """
Three findings from this week's API review. They are independent; all three
need fixing.

1. /items/0 does not address item zero. The path parameter comes through as the
   boolean false rather than the number 0. Only the exact strings "true" and
   "false" are meant to be booleans.

2. Route patterns that place a wildcard anywhere other than the final segment
   are accepted at registration and then behave unpredictably. A wildcard
   swallows the rest of the path, so it cannot be followed by anything and
   should be refused when the pattern is parsed.

3. Path normalisation drops the leading slash, so "/a/b" and "a/b" produce
   different cache keys for the same route and the route cache is missing
   roughly half the time it should hit.
"""),
     [("src/params.ts",
       """  if (raw === 'true') return true;
  if (raw === 'false') return false;""",
       """  if (raw === 'true') return true;
  if (!raw || raw === 'false' || raw === '0') return false;"""),
      ("src/matcher.ts",
       """      const name = part.slice(1) || 'wildcard';
      if (index !== parts.length - 1) {
        throw new InvalidPattern(pattern, 'wildcard must be the last segment');
      }
      out.push({ kind: 'wildcard', value: name });""",
       """      const name = part.slice(1) || 'wildcard';
      out.push({ kind: 'wildcard', value: name });"""),
      ("src/url.ts",
       """  const parts = segments(path);
  return parts.length === 0 ? '/' : '/' + parts.join('/');""",
       """  const parts = segments(path);
  return parts.length === 0 ? '/' : parts.join('/');""")],
     {"coerce.test.ts": '''
import { test } from 'node:test';
import assert from 'node:assert';
import { coerce, coerceAll } from '../src/index.ts';

test('zero is the number zero', () => {
  assert.strictEqual(coerce('id', '0'), 0);
});

test('only the exact string false is boolean false', () => {
  assert.strictEqual(coerce('f', 'false'), false);
  assert.strictEqual(coerce('f', 'False'), 'False');
  assert.strictEqual(coerce('f', 'FALSE'), 'FALSE');
});

test('true is boolean true', () => {
  assert.strictEqual(coerce('t', 'true'), true);
});

test('numbers stay numbers', () => {
  assert.strictEqual(coerce('n', '42'), 42);
  assert.strictEqual(coerce('n', '-1'), -1);
  assert.strictEqual(coerce('n', '3.5'), 3.5);
});

test('empty string stays a string', () => {
  assert.strictEqual(coerce('s', ''), '');
});

test('non-numeric text stays text', () => {
  assert.strictEqual(coerce('s', 'abc'), 'abc');
});

test('coerceAll maps every entry', () => {
  assert.deepStrictEqual(coerceAll({ a: '0', b: 'true', c: 'x' }),
                         { a: 0, b: true, c: 'x' });
});
''',
      "pattern.test.ts": '''
import { test } from 'node:test';
import assert from 'node:assert';
import { parsePattern, InvalidPattern } from '../src/index.ts';

test('a wildcard before other segments is refused', () => {
  assert.throws(() => parsePattern('/a/*rest/b'), InvalidPattern);
});

test('a wildcard in the middle of a long pattern is refused', () => {
  assert.throws(() => parsePattern('/x/*all/y/z'), InvalidPattern);
});

test('a trailing wildcard is accepted', () => {
  assert.deepStrictEqual(parsePattern('/a/*rest').map((s) => s.kind),
                         ['static', 'wildcard']);
});

test('a bare trailing wildcard is accepted', () => {
  assert.strictEqual(parsePattern('/a/*')[1].value, 'wildcard');
});

test('empty parameter names are still refused', () => {
  assert.throws(() => parsePattern('/a/:'), InvalidPattern);
});

test('ordinary patterns still parse', () => {
  assert.deepStrictEqual(parsePattern('/u/:id').map((s) => s.kind),
                         ['static', 'param']);
});
''',
      "normalise.test.ts": '''
import { test } from 'node:test';
import assert from 'node:assert';
import { normalise, joinPath, Router } from '../src/index.ts';

test('a leading slash is kept', () => {
  assert.strictEqual(normalise('/a/b'), '/a/b');
});

test('a missing leading slash is added', () => {
  assert.strictEqual(normalise('a/b'), '/a/b');
});

test('both spellings normalise identically', () => {
  assert.strictEqual(normalise('a/b'), normalise('/a/b'));
});

test('trailing and repeated slashes are removed', () => {
  assert.strictEqual(normalise('//a//b/'), '/a/b');
});

test('the root path stays a single slash', () => {
  assert.strictEqual(normalise(''), '/');
  assert.strictEqual(normalise('/'), '/');
});

test('joinPath produces an absolute path', () => {
  assert.strictEqual(joinPath('a', 'b'), '/a/b');
});

test('the router resolves either spelling to one route', () => {
  const r = new Router();
  r.add('GET', '/u/:id', async () => ({ status: 200, body: '' }));
  assert.strictEqual(r.resolve('GET', 'u/7')!.pattern, '/u/:id');
  assert.strictEqual(r.resolve('GET', '/u/7')!.pattern, '/u/:id');
});
'''})

print("done")