File size: 9,895 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
#!/usr/bin/env python3
"""Batch 7: additional single defects, to widen the pool compound tasks draw on."""
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"
LEDGER = "python/ledger"

# ---------------------------------------------------------------- flow
make(FLOW, "skipped-counts-as-satisfied",
     spec("python", "logic", 4, """
Tasks are running whose dependencies never produced anything.

In a graph where an optional step is skipped, everything downstream of it runs
anyway and then fails at execution time reading a result that was never
computed. We expect those downstream tasks to be skipped in turn.

A dependency that was skipped has produced no result, so it does not satisfy
anything that needs it.
"""),
     [("flow/scheduler.py",
       """        for upstream in task.depends_on:
            if state.get(upstream) != st.SUCCEEDED:
                return False
        return True""",
       """        for upstream in task.depends_on:
            if not state.is_terminal(upstream):
                return False
        return True""")],
     {"test_skipped_upstream.py": '''
import unittest

from flow import ResourcePool, Scheduler, Task, TaskGraph
from flow import state as st


def graph():
    return Scheduler(TaskGraph([
        Task("a"),
        Task("b", depends_on=frozenset({"a"})),
        Task("c", depends_on=frozenset({"b"})),
    ]), ResourcePool({}))


class TestSkippedDoesNotSatisfy(unittest.TestCase):
    def test_downstream_of_a_skip_is_not_offered(self):
        s = graph()
        state = s.new_state()
        state.set("a", st.SKIPPED)
        self.assertNotIn("b", s.next_batch(state))

    def test_downstream_of_a_skip_settles(self):
        s = graph()
        state = s.new_state()
        state.set("a", st.SKIPPED)
        s.settle_unreachable(state)
        self.assertEqual(state.get("b"), st.SKIPPED)

    def test_failed_upstream_is_not_satisfied(self):
        s = graph()
        state = s.new_state()
        s.start("a", state)
        s.fail("a", state)
        self.assertEqual(s.next_batch(state), [])

    def test_run_with_a_skip_completes(self):
        s = graph()
        state = s.new_state()
        state.set("a", st.SKIPPED)
        for _ in range(3):
            s.settle_unreachable(state)
        self.assertTrue(state.is_complete())


class TestSuccessStillSatisfies(unittest.TestCase):
    def test_successful_upstream_releases_downstream(self):
        s = graph()
        state = s.new_state()
        s.start("a", state)
        s.finish("a", state, True)
        self.assertEqual(s.next_batch(state), ["b"])

    def test_chain_runs_to_the_end(self):
        s = graph()
        state = s.new_state()
        for name in ("a", "b", "c"):
            self.assertEqual(s.next_batch(state), [name])
            s.start(name, state)
            s.finish(name, state, True)
        self.assertTrue(state.is_complete())

    def test_running_upstream_blocks(self):
        s = graph()
        state = s.new_state()
        s.start("a", state)
        self.assertEqual(s.next_batch(state), [])
'''})

make(FLOW, "unfinished-includes-terminal",
     spec("python", "logic", 3, """
Our progress display never reaches zero outstanding work.

The dashboard asks the run state which tasks are still outstanding and shows
that as "remaining". On a run where everything has finished, it still lists
every task, so the bar never completes. The run itself is fine -- it reports
complete, and every task is in a finished state.
"""),
     [("flow/state.py",
       """    def unfinished(self) -> List[str]:
        return sorted(tid for tid, s in self.status.items() if s not in TERMINAL)""",
       """    def unfinished(self) -> List[str]:
        return sorted(self.status)""")],
     {"test_unfinished.py": '''
import unittest

from flow import RunState
from flow import state as st


def state_with(**statuses):
    s = RunState(list(statuses))
    s.status.update(statuses)
    return s


class TestUnfinished(unittest.TestCase):
    def test_finished_tasks_are_excluded(self):
        s = state_with(a=st.SUCCEEDED, b=st.PENDING)
        self.assertEqual(s.unfinished(), ["b"])

    def test_all_finished_is_empty(self):
        s = state_with(a=st.SUCCEEDED, b=st.FAILED, c=st.SKIPPED)
        self.assertEqual(s.unfinished(), [])

    def test_running_counts_as_outstanding(self):
        s = state_with(a=st.RUNNING, b=st.SUCCEEDED)
        self.assertEqual(s.unfinished(), ["a"])

    def test_retrying_counts_as_outstanding(self):
        s = state_with(a=st.RETRYING, b=st.SUCCEEDED)
        self.assertEqual(s.unfinished(), ["a"])


class TestRelatedAccessorsIntact(unittest.TestCase):
    def test_is_complete_still_works(self):
        self.assertTrue(state_with(a=st.SUCCEEDED).is_complete())
        self.assertFalse(state_with(a=st.PENDING).is_complete())

    def test_in_status_filters(self):
        s = state_with(a=st.PENDING, b=st.RUNNING)
        self.assertEqual(s.in_status(st.RUNNING), ["b"])

    def test_counts_totals(self):
        s = state_with(a=st.SUCCEEDED, b=st.SUCCEEDED, c=st.PENDING)
        self.assertEqual(s.counts(), {st.SUCCEEDED: 2, st.PENDING: 1})

    def test_results_are_sorted(self):
        s = state_with(z=st.PENDING, a=st.PENDING)
        self.assertEqual(s.unfinished(), ["a", "z"])
'''})

# ---------------------------------------------------------------- ledger
make(LEDGER, "between-boundary",
     spec("python", "logic", 3, """
Our per-period stock report double-counts events on period boundaries.

Consecutive reports are produced by asking the store for the events between the
previous report's last sequence number and the current one. An event landing
exactly on a boundary shows up in both the earlier report and the later one.

The range is documented as excluding its lower bound and including its upper.
"""),
     [("ledger/store.py",
       """        return [e for e in self._events if low < e.seq <= high]""",
       """        return [e for e in self._events if low <= e.seq <= high]""")],
     {"test_between.py": '''
import unittest

from ledger import EventStore


def store_with(n):
    store = EventStore()
    for i in range(n):
        store.receive(f"sku{i}", 1, 1.0)
    return store


class TestBetweenIsHalfOpen(unittest.TestCase):
    def test_lower_bound_is_excluded(self):
        self.assertEqual([e.seq for e in store_with(5).between(2, 4)], [3, 4])

    def test_consecutive_ranges_do_not_overlap(self):
        store = store_with(6)
        first = {e.seq for e in store.between(0, 3)}
        second = {e.seq for e in store.between(3, 6)}
        self.assertEqual(first & second, set())

    def test_consecutive_ranges_leave_no_gap(self):
        store = store_with(6)
        seen = {e.seq for e in store.between(0, 3)} | {e.seq for e in store.between(3, 6)}
        self.assertEqual(seen, {1, 2, 3, 4, 5, 6})

    def test_empty_range(self):
        self.assertEqual(store_with(5).between(3, 3), [])


class TestBetweenOtherwiseWorks(unittest.TestCase):
    def test_upper_bound_is_included(self):
        self.assertIn(4, [e.seq for e in store_with(5).between(2, 4)])

    def test_full_range(self):
        self.assertEqual(len(store_with(5).between(0, 5)), 5)

    def test_beyond_the_end(self):
        self.assertEqual(len(store_with(3).between(0, 99)), 3)
'''})

# ---------------------------------------------------------------- router
make(ROUTER, "match-order-reversed",
     spec("typescript", "logic", 4, """
The router picks the least specific route that matches.

A request for /users/me is handled by /users/:id even though /users/me is
registered, and /assets/logo.svg is picked up by the catch-all /assets/*path
rather than by /assets/logo.svg. It looks like the ordering of candidate routes
is upside down: the vaguest match wins instead of the sharpest.
"""),
     [("src/trie.ts",
       """    found.sort((a, b) => {
      const bySpecificity = compareSpecificity(b.route.rank, a.route.rank);
      if (bySpecificity !== 0) return bySpecificity;
      return a.route.pattern.localeCompare(b.route.pattern);
    });""",
       """    found.sort((a, b) => {
      const bySpecificity = compareSpecificity(a.route.rank, b.route.rank);
      if (bySpecificity !== 0) return bySpecificity;
      return a.route.pattern.localeCompare(b.route.pattern);
    });""")],
     {"match-order.test.ts": '''
import { test } from 'node:test';
import assert from 'node:assert';
import { RouteTable } from '../src/index.ts';

function table(patterns: string[]) {
  const t = new RouteTable<string>();
  for (const p of patterns) t.add(p, p);
  return t;
}

test('static wins over param', () => {
  assert.strictEqual(table(['/users/:id', '/users/me']).match('/users/me')!.route.value,
                     '/users/me');
});

test('static wins over wildcard', () => {
  assert.strictEqual(table(['/assets/*path', '/assets/logo.svg'])
                       .match('/assets/logo.svg')!.route.value, '/assets/logo.svg');
});

test('param wins over wildcard', () => {
  assert.strictEqual(table(['/a/*rest', '/a/:id']).match('/a/7')!.route.value, '/a/:id');
});

test('matchAll is ordered most specific first', () => {
  const all = table(['/u/*r', '/u/:id', '/u/me']).matchAll('/u/me');
  assert.deepStrictEqual(all.map((m) => m.route.value), ['/u/me', '/u/:id', '/u/*r']);
});

test('non-matching routes are absent', () => {
  assert.strictEqual(table(['/a/b']).match('/x/y'), undefined);
});

test('params still extracted from the winner', () => {
  assert.strictEqual(table(['/u/*r', '/u/:id']).match('/u/7')!.params.id, '7');
});

test('a single matching route still matches', () => {
  assert.strictEqual(table(['/only']).match('/only')!.route.value, '/only');
});
'''})

print("done")