Jainamshahhh commited on
Commit
148bb09
·
verified ·
1 Parent(s): ff1401a

Upload solver_a.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. solver_a.py +591 -0
solver_a.py ADDED
@@ -0,0 +1,591 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Primary solver. Stdlib `datetime` and `zoneinfo`, plus fedcal for the holiday table.
2
+
3
+ This is the implementation the released scorer calls to recompute gold answers. It also
4
+ produces the working section that the training completions show, because the walk that
5
+ computes the answer is the same walk the working describes; deriving them separately
6
+ would let a completion narrate a computation that did not happen.
7
+
8
+ Solver B (solver_b.py) answers the same questions from scratch with different
9
+ algorithms and different primitives, and verify_rows.py drops any row where the two
10
+ disagree. Everything here is therefore written for clarity rather than for cleverness:
11
+ if a reviewer cannot follow it, it is not doing its job.
12
+
13
+ THE ONE TRAP THAT MATTERS, and the reason the dual-solver gate exists at all.
14
+ `datetime.__sub__` on two aware datetimes SHORT-CIRCUITS when both carry the same
15
+ tzinfo object: it subtracts the wall-clock fields and never calls utcoffset(). Across a
16
+ DST transition that is simply wrong. Verified locally on 2026-07-28:
17
+
18
+ a = datetime(2026, 10, 31, 22, 0, tzinfo=ZoneInfo("America/New_York"))
19
+ b = datetime(2026, 11, 1, 6, 0, tzinfo=ZoneInfo("America/New_York"))
20
+ b - a -> 8:00:00 WRONG
21
+ b.astimezone(utc) - a.astimezone(utc) -> 9:00:00 right
22
+
23
+ Nine hours is correct: 2026-11-01 is the first Sunday in November, the hour from 01:00
24
+ to 02:00 local runs twice, and the offset moves from -04:00 to -05:00. F3 always
25
+ converts both endpoints to UTC first, and `_selftest` keeps that as a regression test.
26
+
27
+ PARAMETER SCHEMAS. Every family's gold answer is a pure function of these fields, which
28
+ is what lets the released scorer recompute all of them from the row file alone.
29
+
30
+ F1 {"family":"F1", "anchor":"YYYY-MM-DD", "n":1..15, "direction":"after"|"before"}
31
+ F2 {"family":"F2", "anchor":"YYYY-MM-DD", "n":1..60, "direction":"after"|"before",
32
+ "roll":"forward"|"backward"}
33
+ F3 {"family":"F3", "start":{"dt":"YYYY-MM-DDTHH:MM","zone":<IANA>},
34
+ "end":{"dt":"YYYY-MM-DDTHH:MM","zone":<IANA>}}
35
+ F4 {"family":"F4", "schedule":{...}, "after":"YYYY-MM-DD", "adjust":"prior"|"next"}
36
+ F5 {"family":"F5", "kind":..., "date":"YYYY-MM-DD", ...}
37
+ """
38
+ from __future__ import annotations
39
+
40
+ import sys
41
+ from datetime import date, datetime, timedelta, timezone
42
+ from pathlib import Path
43
+ from zoneinfo import ZoneInfo
44
+
45
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
46
+
47
+ import fedcal # noqa: E402
48
+
49
+ DAY_ABBR = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
50
+ DAY_FULL = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
51
+ MONTH_FULL = ("January", "February", "March", "April", "May", "June", "July",
52
+ "August", "September", "October", "November", "December")
53
+
54
+ ANSWER_TYPES = {"F1": "date", "F2": "date", "F3": "duration", "F4": "date", "F5": "isoweek"}
55
+
56
+ # Caps declared in the task contract and enforced here, not only in the generator. A
57
+ # generator bug that emitted n=200 would otherwise produce a valid-looking gold answer
58
+ # for a scenario the corpus never promised to cover.
59
+ N_CAPS = {"F1": (1, 15), "F2": (1, 60)}
60
+
61
+
62
+ class SolverError(ValueError):
63
+ """Raised on a scenario the contract does not cover. Never returns a guess."""
64
+
65
+
66
+ def abbr(d: date) -> str:
67
+ return DAY_ABBR[d.weekday()]
68
+
69
+
70
+ def full_weekday(d: date) -> str:
71
+ return DAY_FULL[d.weekday()]
72
+
73
+
74
+ def _d(s: str) -> date:
75
+ return date.fromisoformat(s)
76
+
77
+
78
+ # ---------------------------------------------------------------- business days
79
+
80
+ def _step_business(d: date, forward: bool) -> date:
81
+ step = timedelta(days=1 if forward else -1)
82
+ cur = d + step
83
+ while not fedcal.is_business_day(cur):
84
+ cur += step
85
+ return cur
86
+
87
+
88
+ def business_days_offset(anchor: date, n: int, forward: bool) -> tuple[date, list[str]]:
89
+ """The nth business day strictly after (or before) `anchor`, with a per-day trace.
90
+
91
+ Day-by-day on purpose. Solver B does the same thing in closed form with a holiday
92
+ correction loop, so an off-by-one in either is visible as a disagreement.
93
+ """
94
+ if n < 1:
95
+ raise SolverError(f"n must be at least 1, got {n}")
96
+ lines: list[str] = []
97
+ cur = anchor
98
+ counted = 0
99
+ step = timedelta(days=1 if forward else -1)
100
+ while counted < n:
101
+ cur += step
102
+ name = fedcal.holiday_name(cur)
103
+ if cur.weekday() >= 5:
104
+ lines.append(f"{abbr(cur)} {cur.isoformat()}: weekend, skip")
105
+ elif name:
106
+ lines.append(f"{abbr(cur)} {cur.isoformat()}: holiday ({name}), skip")
107
+ else:
108
+ counted += 1
109
+ lines.append(f"{abbr(cur)} {cur.isoformat()}: business day {counted}")
110
+ return cur, lines
111
+
112
+
113
+ def roll(d: date, forward: bool) -> tuple[date, list[str]]:
114
+ """Move to the nearest business day on or after (or on or before) `d`."""
115
+ lines: list[str] = []
116
+ cur = d
117
+ word = "roll forward" if forward else "roll backward"
118
+ while not fedcal.is_business_day(cur):
119
+ name = fedcal.holiday_name(cur)
120
+ why = f"holiday ({name})" if name else "weekend"
121
+ lines.append(f"{abbr(cur)} {cur.isoformat()}: {why}, {word}")
122
+ cur += timedelta(days=1 if forward else -1)
123
+ lines.append(f"{abbr(cur)} {cur.isoformat()}: business day, stop")
124
+ return cur, lines
125
+
126
+
127
+ # ---------------------------------------------------------------- F1
128
+
129
+ def solve_f1(p: dict) -> tuple[str, list[str]]:
130
+ lo, hi = N_CAPS["F1"]
131
+ if not lo <= p["n"] <= hi:
132
+ raise SolverError(f"F1 n={p['n']} outside the declared cap {lo}..{hi}")
133
+ anchor = _d(p["anchor"])
134
+ forward = p["direction"] == "after"
135
+ end, walk = business_days_offset(anchor, p["n"], forward)
136
+ head = (f"Anchor {abbr(anchor)} {anchor.isoformat()}, count {p['n']} business "
137
+ f"{'day' if p['n'] == 1 else 'days'} "
138
+ f"{'forward' if forward else 'backward'}.")
139
+ return end.isoformat(), [head] + walk
140
+
141
+
142
+ # ---------------------------------------------------------------- F2
143
+
144
+ def _calendar_add_lines(anchor: date, n: int, forward: bool) -> tuple[date, list[str]]:
145
+ """Add or subtract n calendar days, narrated one month boundary at a time.
146
+
147
+ Month-sized chunks rather than n single steps, because n runs to 60 and a
148
+ sixty-arrow chain is a token bill, not an explanation. n <= 60 crosses at most two
149
+ month boundaries, so this is always three lines or fewer.
150
+
151
+ Each chunk is "however many days reach the first of the next month" going forward,
152
+ or "however many reach the first of this month, then whole months" going back. The
153
+ first draft used "days remaining until the end of this month", which is ZERO when
154
+ the anchor is already the last day of a month, and looped forever on the very first
155
+ case the selftest tried (2026-06-30 plus 45 days). Chunk sizes are asserted
156
+ positive below so that class of bug cannot come back silently.
157
+ """
158
+ lines: list[str] = []
159
+ cur = anchor
160
+ rem = n
161
+ while rem > 0:
162
+ if forward:
163
+ avail = fedcal._days_in_month(cur.year, cur.month) - cur.day + 1
164
+ elif cur.day > 1:
165
+ avail = cur.day - 1
166
+ else:
167
+ prev_end = cur - timedelta(days=1)
168
+ avail = fedcal._days_in_month(prev_end.year, prev_end.month)
169
+ assert avail > 0, f"non-advancing chunk at {cur} (forward={forward})"
170
+ k = min(rem, avail)
171
+ nxt = cur + timedelta(days=k if forward else -k)
172
+ word = "day" if k == 1 else "days"
173
+ if k == rem:
174
+ lines.append(f"Then {k} more {word}{'' if forward else ' back'}: "
175
+ f"landing {nxt.isoformat()}.")
176
+ else:
177
+ lines.append(f"{'To' if forward else 'Back to'} {nxt.isoformat()}, the start "
178
+ f"of {MONTH_FULL[nxt.month - 1]}: {k} {word}, {rem - k} remain.")
179
+ rem -= k
180
+ cur = nxt
181
+ return cur, lines
182
+
183
+
184
+ def solve_f2(p: dict) -> tuple[str, list[str]]:
185
+ lo, hi = N_CAPS["F2"]
186
+ if not lo <= p["n"] <= hi:
187
+ raise SolverError(f"F2 n={p['n']} outside the declared cap {lo}..{hi}")
188
+ anchor = _d(p["anchor"])
189
+ forward = p["direction"] == "after"
190
+ landing, add_lines = _calendar_add_lines(anchor, p["n"], forward)
191
+ head = (f"Anchor {abbr(anchor)} {anchor.isoformat()}, "
192
+ f"{'add' if forward else 'subtract'} {p['n']} calendar "
193
+ f"{'day' if p['n'] == 1 else 'days'}.")
194
+ lines = [head] + add_lines
195
+ if fedcal.is_business_day(landing):
196
+ lines.append(f"Landing {abbr(landing)} {landing.isoformat()}: business day, "
197
+ f"no adjustment needed.")
198
+ return landing.isoformat(), lines
199
+ final, roll_lines = roll(landing, p["roll"] == "forward")
200
+ lines.append(f"Landing {abbr(landing)} {landing.isoformat()}.")
201
+ lines.extend(roll_lines)
202
+ return final.isoformat(), lines
203
+
204
+
205
+ # ---------------------------------------------------------------- F3
206
+
207
+ def _offset_str(dt: datetime) -> str:
208
+ off = dt.utcoffset()
209
+ if off is None:
210
+ raise SolverError("naive datetime has no offset")
211
+ total = int(off.total_seconds()) // 60
212
+ sign = "+" if total >= 0 else "-"
213
+ total = abs(total)
214
+ return f"{sign}{total // 60:02d}:{total % 60:02d}"
215
+
216
+
217
+ def _aware(spec: dict) -> datetime:
218
+ naive = datetime.fromisoformat(spec["dt"])
219
+ if naive.second or naive.microsecond:
220
+ raise SolverError("F3 endpoints must land on a whole minute")
221
+ return naive.replace(tzinfo=ZoneInfo(spec["zone"]))
222
+
223
+
224
+ def endpoint_is_unambiguous(spec: dict) -> bool:
225
+ """True when the local time exists exactly once in its zone.
226
+
227
+ fold=0 and fold=1 must give the same offset. That is false during a fall-back
228
+ repeat (the hour happens twice) and, for a spring-forward gap, the roundtrip
229
+ through UTC does not return the original wall clock. Both are rejected as
230
+ ENDPOINTS. Intervals are still free to SPAN a transition, which is the whole
231
+ point of the family.
232
+ """
233
+ naive = datetime.fromisoformat(spec["dt"])
234
+ zone = ZoneInfo(spec["zone"])
235
+ a = naive.replace(tzinfo=zone, fold=0)
236
+ b = naive.replace(tzinfo=zone, fold=1)
237
+ if a.utcoffset() != b.utcoffset():
238
+ return False
239
+ back = a.astimezone(timezone.utc).astimezone(zone)
240
+ return back.replace(tzinfo=None) == naive
241
+
242
+
243
+ def format_hmm(total_minutes: int) -> str:
244
+ """H:MM. Hours may exceed 24, minutes always two digits, hours never zero-padded."""
245
+ if total_minutes < 0:
246
+ raise SolverError("negative elapsed time is not part of the contract")
247
+ return f"{total_minutes // 60}:{total_minutes % 60:02d}"
248
+
249
+
250
+ def solve_f3(p: dict) -> tuple[str, list[str]]:
251
+ for side in ("start", "end"):
252
+ if not endpoint_is_unambiguous(p[side]):
253
+ raise SolverError(f"F3 {side} endpoint {p[side]} is ambiguous or does not exist")
254
+ a, b = _aware(p["start"]), _aware(p["end"])
255
+ au, bu = a.astimezone(timezone.utc), b.astimezone(timezone.utc)
256
+ delta = bu - au
257
+ if delta.total_seconds() < 0:
258
+ raise SolverError("end precedes start")
259
+ minutes = int(delta.total_seconds()) // 60
260
+ fmt = "%Y-%m-%dT%H:%M"
261
+ lines = [
262
+ f"Start {a.strftime(fmt)} {p['start']['zone']}, UTC offset {_offset_str(a)}, "
263
+ f"so {au.strftime(fmt)} UTC.",
264
+ f"End {b.strftime(fmt)} {p['end']['zone']}, UTC offset {_offset_str(b)}, "
265
+ f"so {bu.strftime(fmt)} UTC.",
266
+ f"Elapsed {bu.strftime(fmt)} UTC minus {au.strftime(fmt)} UTC = {minutes} minutes.",
267
+ f"{minutes} minutes = {minutes // 60} "
268
+ f"{'hour' if minutes // 60 == 1 else 'hours'} {minutes % 60} "
269
+ f"{'minute' if minutes % 60 == 1 else 'minutes'}.",
270
+ ]
271
+ return format_hmm(minutes), lines
272
+
273
+
274
+ # ---------------------------------------------------------------- F4
275
+
276
+ def _month_iter(start: date, months: int):
277
+ y, m = start.year, start.month
278
+ for _ in range(months):
279
+ yield y, m
280
+ m += 1
281
+ if m == 13:
282
+ y, m = y + 1, 1
283
+
284
+
285
+ def nominal_dates(schedule: dict, y: int, m: int) -> list[date]:
286
+ """The scheduled days in one month, before any business-day adjustment."""
287
+ k = schedule["kind"]
288
+ dim = fedcal._days_in_month(y, m)
289
+ if k == "day_of_month":
290
+ return [date(y, m, schedule["day"])]
291
+ if k == "month_end":
292
+ return [date(y, m, dim)]
293
+ if k == "semimonthly":
294
+ return [date(y, m, schedule["day"]), date(y, m, dim)]
295
+ if k == "quarter_end":
296
+ return [date(y, m, dim)] if m in (3, 6, 9, 12) else []
297
+ if k == "nth_weekday":
298
+ return [fedcal._nth_weekday(y, m, schedule["weekday"], schedule["n"])]
299
+ raise SolverError(f"unknown F4 schedule kind {k!r}")
300
+
301
+
302
+ def adjust(d: date, mode: str) -> date:
303
+ """Unchanged on a business day, otherwise the nearest business day in `mode`."""
304
+ if fedcal.is_business_day(d):
305
+ return d
306
+ step = timedelta(days=-1 if mode == "prior" else 1)
307
+ cur = d + step
308
+ while not fedcal.is_business_day(cur):
309
+ cur += step
310
+ return cur
311
+
312
+
313
+ def solve_f4(p: dict) -> tuple[str, list[str]]:
314
+ after = _d(p["after"])
315
+ mode = p["adjust"]
316
+ if mode not in ("prior", "next"):
317
+ raise SolverError(f"unknown adjust mode {mode!r}")
318
+ # Start a month early: an occurrence nominally in the previous month can be pushed
319
+ # forward past `after`, and one nominally after `after` can be pulled back before it.
320
+ start = date(after.year, after.month, 1) - timedelta(days=1)
321
+ start = date(start.year, start.month, 1)
322
+
323
+ pairs: list[tuple[date, date]] = []
324
+ for y, m in _month_iter(start, 18):
325
+ for nom in nominal_dates(p["schedule"], y, m):
326
+ pairs.append((nom, adjust(nom, mode)))
327
+ pairs.sort()
328
+ hits = sorted({occ for _, occ in pairs if occ > after})
329
+ if not hits:
330
+ raise SolverError("no occurrence found in the 18 month search window")
331
+ answer = hits[0]
332
+
333
+ lines: list[str] = []
334
+ shown = 0
335
+ for nom, occ in pairs:
336
+ # Narrate from a little before the answer through it, not the whole window.
337
+ if occ < after - timedelta(days=40):
338
+ continue
339
+ word = "moved back to" if mode == "prior" else "moved forward to"
340
+ if occ == nom:
341
+ lines.append(f"Nominal {abbr(nom)} {nom.isoformat()}: business day, "
342
+ f"occurrence {occ.isoformat()}.")
343
+ else:
344
+ why = fedcal.holiday_name(nom)
345
+ why = f"holiday ({why})" if why else "weekend"
346
+ lines.append(f"Nominal {abbr(nom)} {nom.isoformat()}: {why}, {word} "
347
+ f"{abbr(occ)} {occ.isoformat()}, occurrence {occ.isoformat()}.")
348
+ shown += 1
349
+ if occ >= answer or shown >= 6:
350
+ break
351
+ lines.append(f"Earliest occurrence strictly after {after.isoformat()} "
352
+ f"is {answer.isoformat()}.")
353
+ return answer.isoformat(), lines
354
+
355
+
356
+ # ---------------------------------------------------------------- F5
357
+
358
+ def _iso_label(d: date) -> str:
359
+ iso = d.isocalendar()
360
+ return f"{iso[0]}-W{iso[1]:02d}"
361
+
362
+
363
+ def solve_f5(p: dict) -> tuple[str, list[str]]:
364
+ base = _d(p["date"])
365
+ kind = p["kind"]
366
+ lines: list[str] = []
367
+ if kind == "of_date":
368
+ target = base
369
+ lines.append(f"Target {target.isoformat()} {abbr(target)}.")
370
+ elif kind == "of_offset_days":
371
+ target = base + timedelta(days=p["offset_days"])
372
+ sign = "plus" if p["offset_days"] >= 0 else "minus"
373
+ lines.append(f"{base.isoformat()} {sign} {abs(p['offset_days'])} calendar days "
374
+ f"= {target.isoformat()} {abbr(target)}.")
375
+ elif kind == "of_offset_weeks":
376
+ target = base + timedelta(weeks=p["offset_weeks"])
377
+ sign = "plus" if p["offset_weeks"] >= 0 else "minus"
378
+ lines.append(f"{base.isoformat()} {sign} {abs(p['offset_weeks'])} weeks "
379
+ f"= {abs(p['offset_weeks']) * 7} calendar days = "
380
+ f"{target.isoformat()} {abbr(target)}.")
381
+ elif kind == "of_nth_weekday":
382
+ target = fedcal._nth_weekday(base.year, base.month, p["weekday"], p["n"])
383
+ lines.append(f"The {['first', 'second', 'third', 'fourth', 'fifth'][p['n'] - 1]} "
384
+ f"{DAY_FULL[p['weekday']]} of {MONTH_FULL[base.month - 1]} "
385
+ f"{base.year} is {target.isoformat()}.")
386
+ else:
387
+ raise SolverError(f"unknown F5 kind {kind!r}")
388
+
389
+ monday = target - timedelta(days=target.weekday())
390
+ sunday = monday + timedelta(days=6)
391
+ thursday = monday + timedelta(days=3)
392
+ iso_year = thursday.year
393
+ jan_first = date(iso_year, 1, 1)
394
+ first_thu = jan_first + timedelta(days=(3 - jan_first.weekday()) % 7)
395
+ week1_monday = first_thu - timedelta(days=3)
396
+ span = (monday - week1_monday).days
397
+ week = span // 7 + 1
398
+
399
+ lines.append(f"ISO weeks run Monday to Sunday, so this week is {monday.isoformat()} "
400
+ f"Mon to {sunday.isoformat()} Sun.")
401
+ lines.append(f"The Thursday of that week is {thursday.isoformat()}, which falls in "
402
+ f"{iso_year}, so the ISO year is {iso_year}.")
403
+ lines.append(f"The first Thursday of {iso_year} is {first_thu.isoformat()}, so ISO "
404
+ f"week 01 of {iso_year} starts {week1_monday.isoformat()} Mon.")
405
+ lines.append(f"{monday.isoformat()} minus {week1_monday.isoformat()} = {span} "
406
+ f"{'day' if span == 1 else 'days'} = {span // 7} "
407
+ f"{'week' if span // 7 == 1 else 'weeks'}, "
408
+ f"so the week number is {week}.")
409
+
410
+ label = f"{iso_year}-W{week:02d}"
411
+ if label != _iso_label(target):
412
+ raise SolverError(f"F5 internal disagreement: first-Thursday {label} vs "
413
+ f"isocalendar {_iso_label(target)} for {target}")
414
+ return label, lines
415
+
416
+
417
+ # ---------------------------------------------------------------- entry point
418
+
419
+ _DISPATCH = {"F1": solve_f1, "F2": solve_f2, "F3": solve_f3, "F4": solve_f4, "F5": solve_f5}
420
+
421
+
422
+ def solve(params: dict) -> dict:
423
+ """{"answer_type", "answer", "working"} for one scenario. Raises on anything odd."""
424
+ fam = params.get("family")
425
+ if fam not in _DISPATCH:
426
+ raise SolverError(f"unknown family {fam!r}")
427
+ answer, working = _DISPATCH[fam](params)
428
+ return {"answer_type": ANSWER_TYPES[fam], "answer": answer, "working": working}
429
+
430
+
431
+ def answer_of(params: dict) -> str:
432
+ return solve(params)["answer"]
433
+
434
+
435
+ def _selftest() -> None:
436
+ ok = 0
437
+
438
+ # 1. The card's worked example. Ten business days after Friday 2026-11-20 is
439
+ # Monday 2026-12-07; the walk skips Thanksgiving on Thursday 2026-11-26, and a
440
+ # no-holiday walk would land on Friday 2026-12-04.
441
+ r = solve({"family": "F1", "anchor": "2026-11-20", "n": 10, "direction": "after"})
442
+ assert r["answer"] == "2026-12-07", r
443
+ assert any("Thanksgiving Day" in l for l in r["working"])
444
+ naive, _ = business_days_offset(date(2026, 11, 20), 10, True) # with holidays
445
+ assert naive.isoformat() == "2026-12-07"
446
+ ok += 1
447
+
448
+ # 2. F1 backward, and n=1 on a Friday lands on the Monday.
449
+ assert answer_of({"family": "F1", "anchor": "2026-11-20", "n": 1,
450
+ "direction": "after"}) == "2026-11-23"
451
+ assert answer_of({"family": "F1", "anchor": "2026-11-23", "n": 1,
452
+ "direction": "before"}) == "2026-11-20"
453
+ # Anchor on a holiday still counts from the day after.
454
+ assert answer_of({"family": "F1", "anchor": "2026-07-03", "n": 1,
455
+ "direction": "after"}) == "2026-07-06"
456
+ ok += 1
457
+
458
+ # 3. F1 rejects an out-of-cap n rather than answering it.
459
+ for bad in (0, 16):
460
+ try:
461
+ solve({"family": "F1", "anchor": "2026-11-20", "n": bad, "direction": "after"})
462
+ raise AssertionError(f"expected SolverError for n={bad}")
463
+ except SolverError:
464
+ pass
465
+ ok += 1
466
+
467
+ # 4. F2 forward across a month boundary with no adjustment.
468
+ r = solve({"family": "F2", "anchor": "2026-06-30", "n": 45, "direction": "after",
469
+ "roll": "forward"})
470
+ assert r["answer"] == "2026-08-14", r
471
+ assert (date(2026, 6, 30) + timedelta(days=45)).isoformat() == "2026-08-14"
472
+ # F2 landing on the Saturday of an observed-Friday holiday, both roll directions.
473
+ fwd = solve({"family": "F2", "anchor": "2026-07-01", "n": 3, "direction": "after",
474
+ "roll": "forward"})
475
+ assert fwd["answer"] == "2026-07-06", fwd # Sat 07-04 -> Mon 07-06
476
+ bwd = solve({"family": "F2", "anchor": "2026-07-01", "n": 3, "direction": "after",
477
+ "roll": "backward"})
478
+ assert bwd["answer"] == "2026-07-02", bwd # Sat 07-04 -> skip observed Fri 07-03
479
+ assert any("Independence Day" in l for l in bwd["working"])
480
+ ok += 1
481
+
482
+ # 5. F2 backward arithmetic matches a plain timedelta for every n in the cap.
483
+ for n in range(1, 61):
484
+ got, _ = _calendar_add_lines(date(2026, 8, 12), n, False)
485
+ assert got == date(2026, 8, 12) - timedelta(days=n), (n, got)
486
+ got, _ = _calendar_add_lines(date(2026, 1, 15), n, True)
487
+ assert got == date(2026, 1, 15) + timedelta(days=n), (n, got)
488
+ ok += 1
489
+
490
+ # 6. THE DST TRAP. Regression test for the bug the dual-solver gate caught.
491
+ ny = ZoneInfo("America/New_York")
492
+ a = datetime(2026, 10, 31, 22, 0, tzinfo=ny)
493
+ b = datetime(2026, 11, 1, 6, 0, tzinfo=ny)
494
+ assert (b - a) == timedelta(hours=8), "Python changed same-zone subtraction"
495
+ r = solve({"family": "F3",
496
+ "start": {"dt": "2026-10-31T22:00", "zone": "America/New_York"},
497
+ "end": {"dt": "2026-11-01T06:00", "zone": "America/New_York"}})
498
+ assert r["answer"] == "9:00", r
499
+ ok += 1
500
+
501
+ # 7. H:MM semantics: over 24 hours, no days component, no leading zero on hours.
502
+ assert format_hmm(0) == "0:00"
503
+ assert format_hmm(45) == "0:45"
504
+ assert format_hmm(9 * 60) == "9:00"
505
+ assert format_hmm(30 * 60 + 45) == "30:45"
506
+ assert format_hmm(100 * 60 + 5) == "100:05"
507
+ try:
508
+ format_hmm(-1)
509
+ raise AssertionError("negative elapsed must raise")
510
+ except SolverError:
511
+ pass
512
+ ok += 1
513
+
514
+ # 8. Endpoint existence and unambiguity, in both failure directions.
515
+ assert endpoint_is_unambiguous({"dt": "2026-11-01T06:00", "zone": "America/New_York"})
516
+ assert not endpoint_is_unambiguous(
517
+ {"dt": "2026-11-01T01:30", "zone": "America/New_York"}), "repeated hour"
518
+ assert not endpoint_is_unambiguous(
519
+ {"dt": "2026-03-08T02:30", "zone": "America/New_York"}), "spring-forward gap"
520
+ assert endpoint_is_unambiguous({"dt": "2026-06-15T12:00", "zone": "Asia/Kolkata"})
521
+ ok += 1
522
+
523
+ # 9. F3 across zones and across a spring-forward transition.
524
+ r = solve({"family": "F3",
525
+ "start": {"dt": "2026-03-07T20:00", "zone": "America/New_York"},
526
+ "end": {"dt": "2026-03-08T09:00", "zone": "America/New_York"}})
527
+ assert r["answer"] == "12:00", r # 13 wall-clock hours, one hour skipped
528
+ r = solve({"family": "F3",
529
+ "start": {"dt": "2026-05-04T09:00", "zone": "America/Los_Angeles"},
530
+ "end": {"dt": "2026-05-05T01:30", "zone": "Asia/Tokyo"}})
531
+ # 2026-05-04 09:00 PDT = 16:00 UTC; 2026-05-05 01:30 JST = 2026-05-04 16:30 UTC
532
+ assert r["answer"] == "0:30", r
533
+ ok += 1
534
+
535
+ # 10. F4: semimonthly, moved to the prior business day.
536
+ r = solve({"family": "F4", "schedule": {"kind": "semimonthly", "day": 15},
537
+ "after": "2026-05-20", "adjust": "prior"})
538
+ assert r["answer"] == "2026-05-29", r # nominal Sun 2026-05-31 -> Fri 2026-05-29
539
+ r = solve({"family": "F4", "schedule": {"kind": "month_end"},
540
+ "after": "2026-05-20", "adjust": "next"})
541
+ assert r["answer"] == "2026-06-01", r # nominal Sun 2026-05-31 -> Mon 2026-06-01
542
+ r = solve({"family": "F4", "schedule": {"kind": "day_of_month", "day": 4},
543
+ "after": "2026-06-10", "adjust": "prior"})
544
+ assert r["answer"] == "2026-07-02", r # nominal Sat 07-04 -> Fri 07-03 is the
545
+ # observed holiday -> Thu 07-02
546
+ r = solve({"family": "F4", "schedule": {"kind": "quarter_end"},
547
+ "after": "2026-04-01", "adjust": "prior"})
548
+ assert r["answer"] == "2026-06-30", r
549
+ r = solve({"family": "F4", "schedule": {"kind": "nth_weekday", "weekday": 0, "n": 1},
550
+ "after": "2026-08-15", "adjust": "next"})
551
+ assert r["answer"] == "2026-09-08", r # Mon 2026-09-07 is Labor Day -> Tue 09-08
552
+ ok += 1
553
+
554
+ # 11. F5 against isocalendar over a decade, boundaries included. solve_f5 already
555
+ # raises on an internal disagreement, so this drives every day through it.
556
+ d = date(2020, 1, 1)
557
+ n = 0
558
+ while d <= date(2030, 12, 31):
559
+ lab = solve({"family": "F5", "kind": "of_date", "date": d.isoformat()})["answer"]
560
+ iso = d.isocalendar()
561
+ assert lab == f"{iso[0]}-W{iso[1]:02d}", (d, lab)
562
+ d += timedelta(days=1)
563
+ n += 1
564
+ assert n > 4000
565
+ assert solve({"family": "F5", "kind": "of_date",
566
+ "date": "2026-11-20"})["answer"] == "2026-W47"
567
+ assert solve({"family": "F5", "kind": "of_date",
568
+ "date": "2022-01-01"})["answer"] == "2021-W52"
569
+ assert solve({"family": "F5", "kind": "of_offset_days", "date": "2026-12-28",
570
+ "offset_days": 7})["answer"] == "2027-W01"
571
+ assert solve({"family": "F5", "kind": "of_nth_weekday", "date": "2027-03-01",
572
+ "weekday": 0, "n": 3})["answer"] == "2027-W11"
573
+ ok += 1
574
+
575
+ # 12. Unknown families and unknown kinds raise rather than returning a guess.
576
+ for bad in ({"family": "F9"},
577
+ {"family": "F5", "kind": "nope", "date": "2026-01-01"},
578
+ {"family": "F4", "schedule": {"kind": "nope"}, "after": "2026-01-01",
579
+ "adjust": "prior"}):
580
+ try:
581
+ solve(bad)
582
+ raise AssertionError(f"expected SolverError for {bad}")
583
+ except SolverError:
584
+ pass
585
+ ok += 1
586
+
587
+ print(f"solver_a selftest: {ok}/12 OK")
588
+
589
+
590
+ if __name__ == "__main__":
591
+ _selftest()