test: commit the differential harness that found the two tz bugs
tests/run.sh pins the epochs it was written from, which catches a regression but cannot catch a shared wrong belief: if the plugin and the suite author both think 2040-07-01 in New York is EST, the suite is green and the answer is still wrong. That is exactly how the post-2037 POSIX handover and the southern DST rule survived 194 passing assertions. tests/tz_diff.py asks an independent implementation instead - Python's zoneinfo over the host's own tz database - and compares get_current_time and convert_time field by field, including the skipped-hour error, both fold readings of a repeated hour, and the time_difference string. make tzdiff # full sweep: 555 zones x 112 instants python3 tests/tz_diff.py --quick # one instant, for the offline suite Measured here: 62 160 get_current_time + 93 240 convert_time comparisons, 0 mismatches. run.sh runs the --quick form (1 assertion) and skips cleanly when zoneinfo or a tz database is absent, so it never blocks a node without them. Suite 204 / 0.
AuthorPico <picobot@scorpioplayer.com>
Date2026-11-14 03:31:51
Commit59d0e3c5
Parentse4278db7
Changed files
Makefile+4−1■■■■■
README.md+3−2■■■■■
tests/run.sh+22−0■■■■■
tests/tz_diff.py+275−0■■■■■
4 files+304−3
Diff
Makefile+4−1■■■■■
index f5929a4..6d99893 100644
--- a/Makefile
+++ b/Makefile
@@ -70,10 +70,13 @@ install: plugin_time
7070 mkdir -p "$$PDIR" && cp plugin_time "$$PDIR/plugin_time" && chmod 0755 "$$PDIR/plugin_time" && \
7171 echo "installed $$PDIR/plugin_time (no restart needed: the node rescans plugins per request)"
7272
73+tzdiff: plugin_time
74+ python3 tests/tz_diff.py
75+
7376 test: plugin_time
7477 sh tests/run.sh
7578
7679 clean:
7780 rm -f plugin_time plugin_time.musl plugin_time.arm64 plugin_time.exe plugin_time.asan
7881
79-.PHONY: all musl arm64 win64 macos asan tzdata ui install test clean
82+.PHONY: all musl arm64 win64 macos asan tzdata ui install test tzdiff clean
README.md+3−2■■■■■
index 22cb177..db30e74 100644
--- a/README.md
+++ b/README.md
@@ -17,8 +17,9 @@ make macos # Apple clang (on macOS) -> ./plugin_time
1717 make tzdata # regenerate src/tzdata.h from the host tz database
1818 make ui # regenerate src/ui_html.h from src/ui.html
1919 make install # copy the binary into ~/.scorpiox/plugins (no restart needed)
20-make test # offline suite (200+ assertions)
21-python3 tests/e2e.py # Playwright viewport suite (1440 / 1024 / 390, dark + light)
20+make test # offline suite (204 assertions)
21+python3 tests/tz_diff.py # differential run against the host's own tz database
22+python3 tests/e2e.py # Playwright viewport suite (1440 / 1024 / 390, dark + light)
2223 ```
2324
2425 ## Why the database is embedded
tests/run.sh+22−0■■■■■
index 75818f2..efb1cf9 100755
--- a/tests/run.sh
+++ b/tests/run.sh
@@ -463,6 +463,28 @@ json_ok "--win-tz answers with a key tz_find accepts" \
463463 grep -q 'TZ_WIN_COUNT 1' src/tzdata.h && pass "the generator embedded the Windows map" \
464464 || fail "the Windows map is missing from src/tzdata.h"
465465
466+# ---------------------------------------------------------------- differential
467+#
468+# The suite pins the epochs it was written from, which catches a regression but
469+# cannot catch a shared wrong belief. tests/tz_diff.py asks an independent
470+# implementation (Python's zoneinfo over the host's own tz database) instead;
471+# it is what found the post-2037 POSIX handover and the southern-rule bugs, and
472+# nothing else in this file could have. It skips cleanly when zoneinfo or a tz
473+# database is absent, so it never blocks a node without them.
474+section "differential run against the host tz database"
475+if python3 -c "import zoneinfo; zoneinfo.ZoneInfo('UTC')" >/dev/null 2>&1; then
476+ DOUT=$(python3 tests/tz_diff.py --quick 2>&1)
477+ if printf '%s' "$DOUT" | grep -q 'every comparison matches zoneinfo'; then
478+ pass "zoneinfo and plugin_time agree on every embedded zone"
479+ else
480+ fail "the differential run reported a mismatch"
481+ printf '%s\n' "$DOUT" | grep -E 'FAIL|error' | head -5 | sed 's/^/ /'
482+ fi
483+ echo " (full sweep: python3 tests/tz_diff.py - every zone x 112 instants, 2026-2040)"
484+else
485+ echo " skip differential run (no zoneinfo or no tz database here)"
486+fi
487+
466488 # ---------------------------------------------------------------- source guards
467489 section "source guards"
468490 SRC="src/plugin_time.c src/timeutil.c src/tz.c src/plugintime.h src/tz.h"
tests/tz_diff.py+275−0■■■■■
11new file mode 100755
index 0000000..b398c20
--- /dev/null
+++ b/tests/tz_diff.py
@@ -0,0 +1,275 @@
1+#!/usr/bin/env python3
2+"""tests/tz_diff.py - differential test of plugin_time against real tzdata.
3+
4+`tests/run.sh` pins epochs it was written from. That catches regressions, but it
5+cannot catch a *belief*: if the plugin and the suite author both think 2040-07-01
6+in New York is EST, the suite passes and the answer is still wrong. This harness
7+asks a second, independent implementation instead - Python's `zoneinfo` over the
8+host's own tz database - and compares field by field.
9+
10+It is what found the two bugs the offline suite could not:
11+ * the post-2037 transition list was returned as-is instead of handing over to
12+ the zone's POSIX rule, so every northern zone answered "standard time" for
13+ every date after 2038 (401 mismatches);
14+ * a southern-hemisphere DST rule was tested as a window rather than as sorted
15+ events, so 60 zones reported DST through their winter (60 more).
16+
17+Skips cleanly (exit 0) when `zoneinfo` is unavailable or has no tz database, so
18+a node without Python's tzdata is never blocked by it.
19+
20+ python3 tests/tz_diff.py # default sweep, ~40 s
21+ python3 tests/tz_diff.py --quick # one instant, ~5 s
22+ python3 tests/tz_diff.py --strict # exit 2 when zoneinfo is missing
23+"""
24+
25+import argparse
26+import datetime
27+import json
28+import os
29+import subprocess
30+import sys
31+
32+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
33+BIN = os.path.join(ROOT, "plugin_time")
34+
35+# Instants chosen to land on both sides of the transitions that matter: the
36+# spring and autumn changes in each hemisphere, a leap year, and two dates well
37+# past the point where the compiled tz table stops generating transitions
38+# (2037), where only each zone's own POSIX rule can answer.
39+DATES = [
40+ datetime.datetime(2026, 1, 15, tzinfo=datetime.timezone.utc),
41+ datetime.datetime(2026, 3, 29, tzinfo=datetime.timezone.utc),
42+ datetime.datetime(2026, 7, 15, tzinfo=datetime.timezone.utc),
43+ datetime.datetime(2026, 10, 25, tzinfo=datetime.timezone.utc),
44+ datetime.datetime(2028, 2, 29, tzinfo=datetime.timezone.utc),
45+ datetime.datetime(2038, 3, 28, tzinfo=datetime.timezone.utc),
46+ datetime.datetime(2038, 7, 1, tzinfo=datetime.timezone.utc),
47+ datetime.datetime(2040, 6, 1, tzinfo=datetime.timezone.utc),
48+]
49+QUICK_DATES = [datetime.datetime(2026, 11, 14, tzinfo=datetime.timezone.utc)]
50+
51+# Hours around each date, so a transition that lands mid-day is crossed too.
52+HOUR_OFFSETS = list(range(-36, 60, 7))
53+QUICK_HOURS = [0]
54+
55+# convert_time: wall times that only exist once, once-twice (fall back) and
56+# never (spring forward) depending on the zone.
57+WALL_TIMES = [(0, 0), (1, 30), (2, 30), (3, 30), (9, 0), (12, 30), (23, 59)]
58+CONVERT_TARGETS = ["UTC", "Asia/Kathmandu", "Australia/Lord_Howe"]
59+
60+FAILS = []
61+
62+
63+def ok(desc):
64+ print(" ok %s" % desc)
65+
66+
67+def bad(desc, detail=""):
68+ FAILS.append(desc)
69+ print(" FAIL %s%s" % (desc, (" " + str(detail)[:300]) if detail else ""))
70+
71+
72+def mcp(requests, now=None):
73+ """Run one --mcp session and return the parsed responses, in order."""
74+ env = dict(os.environ)
75+ if now:
76+ env["SX_TIME_NOW"] = now
77+ payload = "\n".join(json.dumps(r) for r in requests) + "\n"
78+ out = subprocess.run([BIN, "--mcp"], input=payload.encode(),
79+ capture_output=True, env=env, timeout=300).stdout
80+ return [json.loads(l) for l in out.decode("utf-8", "replace").splitlines() if l.strip()]
81+
82+
83+def struct_of(resp):
84+ result = resp.get("result", {})
85+ if result.get("isError"):
86+ return {"error": result.get("content", [{}])[0].get("text", "")}
87+ return result.get("structuredContent", {})
88+
89+
90+def iso(obj, key):
91+ return obj.get(key, "") if isinstance(obj, dict) else ""
92+
93+
94+def diff_current(zones, dates, hours):
95+ total = 0
96+ for date in dates:
97+ for h in hours:
98+ now = date + datetime.timedelta(hours=h)
99+ stamp = now.strftime("%Y-%m-%dT%H:%M:%SZ")
100+ reqs = [{"jsonrpc": "2.0", "id": i + 1, "method": "tools/call",
101+ "params": {"name": "get_current_time",
102+ "arguments": {"timezone": z}}}
103+ for i, z in enumerate(zones)]
104+ out = mcp(reqs, now=stamp)
105+ if len(out) != len(zones):
106+ bad("get_current_time @ %s returned %d of %d responses"
107+ % (stamp, len(out), len(zones)))
108+ continue
109+ epoch = int(now.timestamp())
110+ for z, resp in zip(zones, out):
111+ got = struct_of(resp)
112+ ref = datetime.datetime.fromtimestamp(epoch, datetime.timezone.utc)\
113+ .astimezone(__import__("zoneinfo").ZoneInfo(z))
114+ expect = {
115+ "timezone": z,
116+ "datetime": ref.isoformat(timespec="seconds"),
117+ "day_of_week": ref.strftime("%A"),
118+ "is_dst": bool(ref.dst()),
119+ }
120+ total += 1
121+ for key, want in expect.items():
122+ if got.get(key) != want:
123+ bad("get_current_time %s @ %s: %s = %r, zoneinfo says %r"
124+ % (z, stamp, key, got.get(key), want))
125+ break
126+ return total
127+
128+
129+def diff_convert(zones, dates):
130+ from zoneinfo import ZoneInfo
131+
132+ total = 0
133+ for date in dates:
134+ stamp = date.strftime("%Y-%m-%dT%H:%M:%SZ")
135+ reqs, meta = [], []
136+ for z in zones:
137+ for target in CONVERT_TARGETS:
138+ for hh, mm in WALL_TIMES:
139+ reqs.append({"jsonrpc": "2.0", "id": len(reqs) + 1,
140+ "method": "tools/call",
141+ "params": {"name": "convert_time",
142+ "arguments": {
143+ "source_timezone": z,
144+ "time": "%02d:%02d" % (hh, mm),
145+ "target_timezone": target}}})
146+ meta.append((z, target, hh, mm))
147+ out = mcp(reqs, now=stamp)
148+ if len(out) != len(meta):
149+ bad("convert_time @ %s returned %d of %d responses"
150+ % (stamp, len(out), len(meta)))
151+ continue
152+ for (src, dst, hh, mm), resp in zip(meta, out):
153+ total += 1
154+ zs, zt = ZoneInfo(src), ZoneInfo(dst)
155+ # "Today" in the source zone, at the requested wall time.
156+ now_src = date.astimezone(zs)
157+ wall = datetime.datetime(now_src.year, now_src.month, now_src.day,
158+ hh, mm, tzinfo=zs)
159+ # A wall time skipped by a clock change does not survive a round
160+ # trip through UTC; the reference server errors on it.
161+ round_trip = datetime.datetime.fromtimestamp(wall.timestamp(), zs)
162+ skipped = round_trip.replace(tzinfo=None) != wall.replace(tzinfo=None)
163+ # A wall time repeated by a clock change has a second reading at a
164+ # different offset (Python's fold=1).
165+ fold1 = wall.replace(fold=1)
166+ ambiguous = fold1.utcoffset() != wall.utcoffset()
167+
168+ got = struct_of(resp)
169+ if skipped:
170+ if not got.get("error"):
171+ bad("convert_time %s %02d:%02d @ %s should be an error "
172+ "(the wall time does not exist)" % (src, hh, mm, stamp))
173+ elif "does not exist" not in got["error"]:
174+ bad("convert_time %s %02d:%02d: skipped-hour error text is %r"
175+ % (src, hh, mm, got["error"]))
176+ continue
177+ if got.get("error"):
178+ bad("convert_time %s %02d:%02d @ %s errored: %r"
179+ % (src, hh, mm, stamp, got["error"]))
180+ continue
181+
182+ target = wall.astimezone(zt)
183+ if iso(got.get("source"), "datetime") != wall.isoformat(timespec="seconds"):
184+ bad("convert_time %s %02d:%02d @ %s: source %r, zoneinfo %r"
185+ % (src, hh, mm, stamp, iso(got.get("source"), "datetime"),
186+ wall.isoformat(timespec="seconds")))
187+ continue
188+ if iso(got.get("target"), "datetime") != target.isoformat(timespec="seconds"):
189+ bad("convert_time %s %02d:%02d -> %s @ %s: target %r, zoneinfo %r"
190+ % (src, hh, mm, dst, stamp, iso(got.get("target"), "datetime"),
191+ target.isoformat(timespec="seconds")))
192+ continue
193+ hours = (target.utcoffset() - wall.utcoffset()).total_seconds() / 3600
194+ want = ("%+.1fh" % hours) if float(hours).is_integer() \
195+ else ("%+.2f" % hours).rstrip("0").rstrip(".") + "h"
196+ if got.get("time_difference") != want:
197+ bad("convert_time %s -> %s @ %s: difference %r, expected %r"
198+ % (src, dst, stamp, got.get("time_difference"), want))
199+ continue
200+
201+ later = got.get("later_occurrence")
202+ if ambiguous:
203+ if not later:
204+ bad("convert_time %s %02d:%02d @ %s: the hour repeats but no "
205+ "later_occurrence was reported" % (src, hh, mm, stamp))
206+ continue
207+ later_target = fold1.astimezone(zt)
208+ if iso(later.get("source"), "datetime") != fold1.isoformat(timespec="seconds"):
209+ bad("convert_time %s %02d:%02d @ %s: later source %r, zoneinfo %r"
210+ % (src, hh, mm, stamp, iso(later.get("source"), "datetime"),
211+ fold1.isoformat(timespec="seconds")))
212+ elif iso(later.get("target"), "datetime") != later_target.isoformat(timespec="seconds"):
213+ bad("convert_time %s %02d:%02d -> %s @ %s: later target %r, "
214+ "zoneinfo %r" % (src, hh, mm, dst, stamp,
215+ iso(later.get("target"), "datetime"),
216+ later_target.isoformat(timespec="seconds")))
217+ elif later:
218+ bad("convert_time %s %02d:%02d @ %s: reported a later_occurrence "
219+ "for an unambiguous time" % (src, hh, mm, stamp))
220+ return total
221+
222+
223+def main():
224+ ap = argparse.ArgumentParser()
225+ ap.add_argument("--quick", action="store_true",
226+ help="one instant instead of the full sweep (~5 s)")
227+ ap.add_argument("--strict", action="store_true",
228+ help="exit 2 when zoneinfo is unavailable instead of skipping")
229+ args = ap.parse_args()
230+
231+ try:
232+ from zoneinfo import ZoneInfo, available_timezones
233+ except ImportError:
234+ print("zoneinfo is not available (Python < 3.9) - skipping the differential run")
235+ return 2 if args.strict else 0
236+
237+ if not os.access(BIN, os.X_OK):
238+ bad("plugin_time is missing - run make first")
239+ return 1
240+
241+ # `localtime` is a symlink on some hosts and not an IANA key; the plugin
242+ # refuses it on purpose, so it is not a comparison candidate.
243+ zones = sorted(z for z in available_timezones()
244+ if z != "localtime" and "/" in z or z in ("UTC", "GMT"))
245+ if not zones:
246+ print("no tz database on this host - skipping the differential run")
247+ return 2 if args.strict else 0
248+
249+ dates = QUICK_DATES if args.quick else DATES
250+ hours = QUICK_HOURS if args.quick else HOUR_OFFSETS
251+
252+ print("differential run: %d zones x %d instants" % (len(zones), len(dates) * len(hours)))
253+ before = len(FAILS)
254+ n_current = diff_current(zones, dates, hours)
255+ print(" get_current_time: %d comparisons, %d failures so far"
256+ % (n_current, len(FAILS) - before))
257+
258+ if args.quick:
259+ print(" convert_time: skipped in --quick mode")
260+ else:
261+ before = len(FAILS)
262+ n_convert = diff_convert(zones, dates)
263+ print(" convert_time: %d comparisons, %d failures so far"
264+ % (n_convert, len(FAILS) - before))
265+
266+ print("")
267+ if FAILS:
268+ print("FAILED %d comparison(s) against zoneinfo" % len(FAILS))
269+ return 1
270+ print("every comparison matches zoneinfo")
271+ return 0
272+
273+
274+if __name__ == "__main__":
275+ sys.exit(main())
0276
Makefile+4−1■■■■■
index f5929a4..6d99893 100644index f5929a4..6d99893 100644
--- a/Makefile--- a/Makefile
+++ b/Makefile+++ b/Makefile
@@ -70,10 +70,13 @@ install: plugin_time@@ -70,10 +70,13 @@ install: plugin_time
70 mkdir -p "$$PDIR" && cp plugin_time "$$PDIR/plugin_time" && chmod 0755 "$$PDIR/plugin_time" && \70 mkdir -p "$$PDIR" && cp plugin_time "$$PDIR/plugin_time" && chmod 0755 "$$PDIR/plugin_time" && \
71 echo "installed $$PDIR/plugin_time (no restart needed: the node rescans plugins per request)"71 echo "installed $$PDIR/plugin_time (no restart needed: the node rescans plugins per request)"
72 72
73+tzdiff: plugin_time
74+ python3 tests/tz_diff.py
75+
73 test: plugin_time76 test: plugin_time
74 sh tests/run.sh77 sh tests/run.sh
75 78
76 clean:79 clean:
77 rm -f plugin_time plugin_time.musl plugin_time.arm64 plugin_time.exe plugin_time.asan80 rm -f plugin_time plugin_time.musl plugin_time.arm64 plugin_time.exe plugin_time.asan
78 81
79-.PHONY: all musl arm64 win64 macos asan tzdata ui install test clean82+.PHONY: all musl arm64 win64 macos asan tzdata ui install test tzdiff clean
README.md+3−2■■■■■
index 22cb177..db30e74 100644index 22cb177..db30e74 100644
--- a/README.md--- a/README.md
+++ b/README.md+++ b/README.md
@@ -17,8 +17,9 @@ make macos # Apple clang (on macOS) -> ./plugin_time@@ -17,8 +17,9 @@ make macos # Apple clang (on macOS) -> ./plugin_time
17 make tzdata # regenerate src/tzdata.h from the host tz database17 make tzdata # regenerate src/tzdata.h from the host tz database
18 make ui # regenerate src/ui_html.h from src/ui.html18 make ui # regenerate src/ui_html.h from src/ui.html
19 make install # copy the binary into ~/.scorpiox/plugins (no restart needed)19 make install # copy the binary into ~/.scorpiox/plugins (no restart needed)
20-make test # offline suite (200+ assertions)20+make test # offline suite (204 assertions)
21-python3 tests/e2e.py # Playwright viewport suite (1440 / 1024 / 390, dark + light)21+python3 tests/tz_diff.py # differential run against the host's own tz database
22+python3 tests/e2e.py # Playwright viewport suite (1440 / 1024 / 390, dark + light)
22 ```23 ```
23 24
24 ## Why the database is embedded25 ## Why the database is embedded
tests/run.sh+22−0■■■■■
index 75818f2..efb1cf9 100755index 75818f2..efb1cf9 100755
--- a/tests/run.sh--- a/tests/run.sh
+++ b/tests/run.sh+++ b/tests/run.sh
@@ -463,6 +463,28 @@ json_ok "--win-tz answers with a key tz_find accepts" \@@ -463,6 +463,28 @@ json_ok "--win-tz answers with a key tz_find accepts" \
463 grep -q 'TZ_WIN_COUNT 1' src/tzdata.h && pass "the generator embedded the Windows map" \463 grep -q 'TZ_WIN_COUNT 1' src/tzdata.h && pass "the generator embedded the Windows map" \
464 || fail "the Windows map is missing from src/tzdata.h"464 || fail "the Windows map is missing from src/tzdata.h"
465 465
466+# ---------------------------------------------------------------- differential
467+#
468+# The suite pins the epochs it was written from, which catches a regression but
469+# cannot catch a shared wrong belief. tests/tz_diff.py asks an independent
470+# implementation (Python's zoneinfo over the host's own tz database) instead;
471+# it is what found the post-2037 POSIX handover and the southern-rule bugs, and
472+# nothing else in this file could have. It skips cleanly when zoneinfo or a tz
473+# database is absent, so it never blocks a node without them.
474+section "differential run against the host tz database"
475+if python3 -c "import zoneinfo; zoneinfo.ZoneInfo('UTC')" >/dev/null 2>&1; then
476+ DOUT=$(python3 tests/tz_diff.py --quick 2>&1)
477+ if printf '%s' "$DOUT" | grep -q 'every comparison matches zoneinfo'; then
478+ pass "zoneinfo and plugin_time agree on every embedded zone"
479+ else
480+ fail "the differential run reported a mismatch"
481+ printf '%s\n' "$DOUT" | grep -E 'FAIL|error' | head -5 | sed 's/^/ /'
482+ fi
483+ echo " (full sweep: python3 tests/tz_diff.py - every zone x 112 instants, 2026-2040)"
484+else
485+ echo " skip differential run (no zoneinfo or no tz database here)"
486+fi
487+
466 # ---------------------------------------------------------------- source guards488 # ---------------------------------------------------------------- source guards
467 section "source guards"489 section "source guards"
468 SRC="src/plugin_time.c src/timeutil.c src/tz.c src/plugintime.h src/tz.h"490 SRC="src/plugin_time.c src/timeutil.c src/tz.c src/plugintime.h src/tz.h"
tests/tz_diff.py+275−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..b398c20index 0000000..b398c20
--- /dev/null--- /dev/null
+++ b/tests/tz_diff.py+++ b/tests/tz_diff.py
@@ -0,0 +1,275 @@@@ -0,0 +1,275 @@
1+#!/usr/bin/env python3
2+"""tests/tz_diff.py - differential test of plugin_time against real tzdata.
3+
4+`tests/run.sh` pins epochs it was written from. That catches regressions, but it
5+cannot catch a *belief*: if the plugin and the suite author both think 2040-07-01
6+in New York is EST, the suite passes and the answer is still wrong. This harness
7+asks a second, independent implementation instead - Python's `zoneinfo` over the
8+host's own tz database - and compares field by field.
9+
10+It is what found the two bugs the offline suite could not:
11+ * the post-2037 transition list was returned as-is instead of handing over to
12+ the zone's POSIX rule, so every northern zone answered "standard time" for
13+ every date after 2038 (401 mismatches);
14+ * a southern-hemisphere DST rule was tested as a window rather than as sorted
15+ events, so 60 zones reported DST through their winter (60 more).
16+
17+Skips cleanly (exit 0) when `zoneinfo` is unavailable or has no tz database, so
18+a node without Python's tzdata is never blocked by it.
19+
20+ python3 tests/tz_diff.py # default sweep, ~40 s
21+ python3 tests/tz_diff.py --quick # one instant, ~5 s
22+ python3 tests/tz_diff.py --strict # exit 2 when zoneinfo is missing
23+"""
24+
25+import argparse
26+import datetime
27+import json
28+import os
29+import subprocess
30+import sys
31+
32+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
33+BIN = os.path.join(ROOT, "plugin_time")
34+
35+# Instants chosen to land on both sides of the transitions that matter: the
36+# spring and autumn changes in each hemisphere, a leap year, and two dates well
37+# past the point where the compiled tz table stops generating transitions
38+# (2037), where only each zone's own POSIX rule can answer.
39+DATES = [
40+ datetime.datetime(2026, 1, 15, tzinfo=datetime.timezone.utc),
41+ datetime.datetime(2026, 3, 29, tzinfo=datetime.timezone.utc),
42+ datetime.datetime(2026, 7, 15, tzinfo=datetime.timezone.utc),
43+ datetime.datetime(2026, 10, 25, tzinfo=datetime.timezone.utc),
44+ datetime.datetime(2028, 2, 29, tzinfo=datetime.timezone.utc),
45+ datetime.datetime(2038, 3, 28, tzinfo=datetime.timezone.utc),
46+ datetime.datetime(2038, 7, 1, tzinfo=datetime.timezone.utc),
47+ datetime.datetime(2040, 6, 1, tzinfo=datetime.timezone.utc),
48+]
49+QUICK_DATES = [datetime.datetime(2026, 11, 14, tzinfo=datetime.timezone.utc)]
50+
51+# Hours around each date, so a transition that lands mid-day is crossed too.
52+HOUR_OFFSETS = list(range(-36, 60, 7))
53+QUICK_HOURS = [0]
54+
55+# convert_time: wall times that only exist once, once-twice (fall back) and
56+# never (spring forward) depending on the zone.
57+WALL_TIMES = [(0, 0), (1, 30), (2, 30), (3, 30), (9, 0), (12, 30), (23, 59)]
58+CONVERT_TARGETS = ["UTC", "Asia/Kathmandu", "Australia/Lord_Howe"]
59+
60+FAILS = []
61+
62+
63+def ok(desc):
64+ print(" ok %s" % desc)
65+
66+
67+def bad(desc, detail=""):
68+ FAILS.append(desc)
69+ print(" FAIL %s%s" % (desc, (" " + str(detail)[:300]) if detail else ""))
70+
71+
72+def mcp(requests, now=None):
73+ """Run one --mcp session and return the parsed responses, in order."""
74+ env = dict(os.environ)
75+ if now:
76+ env["SX_TIME_NOW"] = now
77+ payload = "\n".join(json.dumps(r) for r in requests) + "\n"
78+ out = subprocess.run([BIN, "--mcp"], input=payload.encode(),
79+ capture_output=True, env=env, timeout=300).stdout
80+ return [json.loads(l) for l in out.decode("utf-8", "replace").splitlines() if l.strip()]
81+
82+
83+def struct_of(resp):
84+ result = resp.get("result", {})
85+ if result.get("isError"):
86+ return {"error": result.get("content", [{}])[0].get("text", "")}
87+ return result.get("structuredContent", {})
88+
89+
90+def iso(obj, key):
91+ return obj.get(key, "") if isinstance(obj, dict) else ""
92+
93+
94+def diff_current(zones, dates, hours):
95+ total = 0
96+ for date in dates:
97+ for h in hours:
98+ now = date + datetime.timedelta(hours=h)
99+ stamp = now.strftime("%Y-%m-%dT%H:%M:%SZ")
100+ reqs = [{"jsonrpc": "2.0", "id": i + 1, "method": "tools/call",
101+ "params": {"name": "get_current_time",
102+ "arguments": {"timezone": z}}}
103+ for i, z in enumerate(zones)]
104+ out = mcp(reqs, now=stamp)
105+ if len(out) != len(zones):
106+ bad("get_current_time @ %s returned %d of %d responses"
107+ % (stamp, len(out), len(zones)))
108+ continue
109+ epoch = int(now.timestamp())
110+ for z, resp in zip(zones, out):
111+ got = struct_of(resp)
112+ ref = datetime.datetime.fromtimestamp(epoch, datetime.timezone.utc)\
113+ .astimezone(__import__("zoneinfo").ZoneInfo(z))
114+ expect = {
115+ "timezone": z,
116+ "datetime": ref.isoformat(timespec="seconds"),
117+ "day_of_week": ref.strftime("%A"),
118+ "is_dst": bool(ref.dst()),
119+ }
120+ total += 1
121+ for key, want in expect.items():
122+ if got.get(key) != want:
123+ bad("get_current_time %s @ %s: %s = %r, zoneinfo says %r"
124+ % (z, stamp, key, got.get(key), want))
125+ break
126+ return total
127+
128+
129+def diff_convert(zones, dates):
130+ from zoneinfo import ZoneInfo
131+
132+ total = 0
133+ for date in dates:
134+ stamp = date.strftime("%Y-%m-%dT%H:%M:%SZ")
135+ reqs, meta = [], []
136+ for z in zones:
137+ for target in CONVERT_TARGETS:
138+ for hh, mm in WALL_TIMES:
139+ reqs.append({"jsonrpc": "2.0", "id": len(reqs) + 1,
140+ "method": "tools/call",
141+ "params": {"name": "convert_time",
142+ "arguments": {
143+ "source_timezone": z,
144+ "time": "%02d:%02d" % (hh, mm),
145+ "target_timezone": target}}})
146+ meta.append((z, target, hh, mm))
147+ out = mcp(reqs, now=stamp)
148+ if len(out) != len(meta):
149+ bad("convert_time @ %s returned %d of %d responses"
150+ % (stamp, len(out), len(meta)))
151+ continue
152+ for (src, dst, hh, mm), resp in zip(meta, out):
153+ total += 1
154+ zs, zt = ZoneInfo(src), ZoneInfo(dst)
155+ # "Today" in the source zone, at the requested wall time.
156+ now_src = date.astimezone(zs)
157+ wall = datetime.datetime(now_src.year, now_src.month, now_src.day,
158+ hh, mm, tzinfo=zs)
159+ # A wall time skipped by a clock change does not survive a round
160+ # trip through UTC; the reference server errors on it.
161+ round_trip = datetime.datetime.fromtimestamp(wall.timestamp(), zs)
162+ skipped = round_trip.replace(tzinfo=None) != wall.replace(tzinfo=None)
163+ # A wall time repeated by a clock change has a second reading at a
164+ # different offset (Python's fold=1).
165+ fold1 = wall.replace(fold=1)
166+ ambiguous = fold1.utcoffset() != wall.utcoffset()
167+
168+ got = struct_of(resp)
169+ if skipped:
170+ if not got.get("error"):
171+ bad("convert_time %s %02d:%02d @ %s should be an error "
172+ "(the wall time does not exist)" % (src, hh, mm, stamp))
173+ elif "does not exist" not in got["error"]:
174+ bad("convert_time %s %02d:%02d: skipped-hour error text is %r"
175+ % (src, hh, mm, got["error"]))
176+ continue
177+ if got.get("error"):
178+ bad("convert_time %s %02d:%02d @ %s errored: %r"
179+ % (src, hh, mm, stamp, got["error"]))
180+ continue
181+
182+ target = wall.astimezone(zt)
183+ if iso(got.get("source"), "datetime") != wall.isoformat(timespec="seconds"):
184+ bad("convert_time %s %02d:%02d @ %s: source %r, zoneinfo %r"
185+ % (src, hh, mm, stamp, iso(got.get("source"), "datetime"),
186+ wall.isoformat(timespec="seconds")))
187+ continue
188+ if iso(got.get("target"), "datetime") != target.isoformat(timespec="seconds"):
189+ bad("convert_time %s %02d:%02d -> %s @ %s: target %r, zoneinfo %r"
190+ % (src, hh, mm, dst, stamp, iso(got.get("target"), "datetime"),
191+ target.isoformat(timespec="seconds")))
192+ continue
193+ hours = (target.utcoffset() - wall.utcoffset()).total_seconds() / 3600
194+ want = ("%+.1fh" % hours) if float(hours).is_integer() \
195+ else ("%+.2f" % hours).rstrip("0").rstrip(".") + "h"
196+ if got.get("time_difference") != want:
197+ bad("convert_time %s -> %s @ %s: difference %r, expected %r"
198+ % (src, dst, stamp, got.get("time_difference"), want))
199+ continue
200+
201+ later = got.get("later_occurrence")
202+ if ambiguous:
203+ if not later:
204+ bad("convert_time %s %02d:%02d @ %s: the hour repeats but no "
205+ "later_occurrence was reported" % (src, hh, mm, stamp))
206+ continue
207+ later_target = fold1.astimezone(zt)
208+ if iso(later.get("source"), "datetime") != fold1.isoformat(timespec="seconds"):
209+ bad("convert_time %s %02d:%02d @ %s: later source %r, zoneinfo %r"
210+ % (src, hh, mm, stamp, iso(later.get("source"), "datetime"),
211+ fold1.isoformat(timespec="seconds")))
212+ elif iso(later.get("target"), "datetime") != later_target.isoformat(timespec="seconds"):
213+ bad("convert_time %s %02d:%02d -> %s @ %s: later target %r, "
214+ "zoneinfo %r" % (src, hh, mm, dst, stamp,
215+ iso(later.get("target"), "datetime"),
216+ later_target.isoformat(timespec="seconds")))
217+ elif later:
218+ bad("convert_time %s %02d:%02d @ %s: reported a later_occurrence "
219+ "for an unambiguous time" % (src, hh, mm, stamp))
220+ return total
221+
222+
223+def main():
224+ ap = argparse.ArgumentParser()
225+ ap.add_argument("--quick", action="store_true",
226+ help="one instant instead of the full sweep (~5 s)")
227+ ap.add_argument("--strict", action="store_true",
228+ help="exit 2 when zoneinfo is unavailable instead of skipping")
229+ args = ap.parse_args()
230+
231+ try:
232+ from zoneinfo import ZoneInfo, available_timezones
233+ except ImportError:
234+ print("zoneinfo is not available (Python < 3.9) - skipping the differential run")
235+ return 2 if args.strict else 0
236+
237+ if not os.access(BIN, os.X_OK):
238+ bad("plugin_time is missing - run make first")
239+ return 1
240+
241+ # `localtime` is a symlink on some hosts and not an IANA key; the plugin
242+ # refuses it on purpose, so it is not a comparison candidate.
243+ zones = sorted(z for z in available_timezones()
244+ if z != "localtime" and "/" in z or z in ("UTC", "GMT"))
245+ if not zones:
246+ print("no tz database on this host - skipping the differential run")
247+ return 2 if args.strict else 0
248+
249+ dates = QUICK_DATES if args.quick else DATES
250+ hours = QUICK_HOURS if args.quick else HOUR_OFFSETS
251+
252+ print("differential run: %d zones x %d instants" % (len(zones), len(dates) * len(hours)))
253+ before = len(FAILS)
254+ n_current = diff_current(zones, dates, hours)
255+ print(" get_current_time: %d comparisons, %d failures so far"
256+ % (n_current, len(FAILS) - before))
257+
258+ if args.quick:
259+ print(" convert_time: skipped in --quick mode")
260+ else:
261+ before = len(FAILS)
262+ n_convert = diff_convert(zones, dates)
263+ print(" convert_time: %d comparisons, %d failures so far"
264+ % (n_convert, len(FAILS) - before))
265+
266+ print("")
267+ if FAILS:
268+ print("FAILED %d comparison(s) against zoneinfo" % len(FAILS))
269+ return 1
270+ print("every comparison matches zoneinfo")
271+ return 0
272+
273+
274+if __name__ == "__main__":
275+ sys.exit(main())
0276