SPB Git

Repository Public

integration.py 23.7 KB 459 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : KA Maps Engine10# File             : server/km-tiler/tests/integration.py11# Description      : Test d'intégration de km-tiler : tuiles réelles en milieu12#                    urbain dense, en banlieue et en région éloignée, à tous13#                    les zooms.14# Module           : server15# Repository       : https://git.spboucher.ai/ka-maps-engine16# Created          : 2026-12-0117# Last Modified    : 2026-12-0118#19# =============================================================================20# AUTHOR & PROFESSIONAL AFFILIATION21# =============================================================================22#23# Author           : Simon-Pierre Boucher24# Position         : Professor of Finance25# Institution      : Université du Québec en Outaouais (UQO)26# Department       : Département des sciences administratives27# Organization     : SP Boucher28#29# Website          : https://spboucher.ai30# Git              : https://git.spboucher.ai31#32# =============================================================================33# OFFICIAL CONTACT DIRECTORY34# =============================================================================35#36# General          : info@spboucher.ai37# Professional     : contact@spboucher.ai38# Direct           : simon@spboucher.ai39# Research         : research@spboucher.ai40# Development      : dev@spboucher.ai41# Support          : support@spboucher.ai42# Security/Admin   : admin@spboucher.ai43# Notifications    : notifications@spboucher.ai44#45# Preferred Contact: support@spboucher.ai46#47# =============================================================================48# COPYRIGHT & INTELLECTUAL PROPERTY49# =============================================================================50#51# Copyright (c) 202652# Simon-Pierre Boucher53#54# All rights reserved where applicable.55#56# This file is governed by the applicable project license,57# copyright notices, institutional agreements and relevant law.58#59# Unless expressly authorized by the applicable license or60# rights holder, copying, redistribution, sublicensing,61# publication and commercial exploitation are not permitted.62#63# Existing third-party rights and notices remain unaffected.64#65# =============================================================================66# CONFIDENTIALITY & SECURITY67# =============================================================================68#69# Classification   : Public70# Distribution     : Public repository; use is governed by the project license71# Security Contact : admin@spboucher.ai72#73# Access to this source does not independently grant permission74# to redistribute or disclose confidential materials.75#76# Do not embed credentials, private keys, access tokens,77# certificates or confidential personal information.78#79# =============================================================================80# LICENSE & MAINTENANCE81# =============================================================================82#83# License          : None specified (no license file in this repository)84# Maintainer       : Simon-Pierre Boucher85# Technical Contact: dev@spboucher.ai86#87# =============================================================================88# END OF SP BOUCHER SOURCE HEADER89# =============================================================================9091"""Test d'intégration de km-tiler : tuiles réelles en milieu urbain dense, en banlieue et en région éloignée,92à tous les zooms. Vérifie les codes HTTP, les en-têtes du contrat (ETag, Cache-Control, gzip, CORS, 204/304/400),93la conformité au schéma ka1 (couches, attributs, énumérations, zooms) et les tailles (cible 150 Ko, plafond94500 Ko gzip). Mesure la latence à froid (génération) et à chaud (cache).9596  integration.py --url http://127.0.0.1:8901 [--cache /var/lib/kamaps/cache --purge] [--json out.json]9798`--purge` (local, droits d'écriture sur le cache) retire d'abord les tuiles de l'échantillon pour mesurer99la génération à froid ; sans cela, la latence « à froid » n'est mesurée que pour les tuiles absentes du cache.100Code de sortie non nul si une assertion échoue.101"""102import argparse103import gzip104import json105import math106import os107import statistics108import subprocess109import sys110import tempfile111import time112import urllib.error113import urllib.request114115ap = argparse.ArgumentParser()116ap.add_argument("--url", default="http://127.0.0.1:8901")117ap.add_argument("--tiler", default="/usr/local/bin/km-tiler")118ap.add_argument("--cache", default=None)119ap.add_argument("--purge", action="store_true")120ap.add_argument("--json", default=None)121ap.add_argument("--determinism", type=int, default=0, help="nombre de tuiles générées deux fois (cache purgé entre les deux) pour vérifier que les octets et l'ETag sont identiques ; exige --cache")122ap.add_argument("--cold-sample", type=int, default=0, help="tuiles aléatoires par zoom, retirées du cache puis demandées (latence à froid) ; exige --cache et les droits d'écriture")123args = ap.parse_args()124125SOFT, HARD = 150 * 1024, 500 * 1024126POINTS = [  # nom, milieu, lat, lon127    ("Montréal centre", "urbain dense", 45.5019, -73.5674),128    ("Québec centre", "urbain dense", 46.8139, -71.2080),129    ("Laval (Sainte-Rose)", "banlieue", 45.6120, -73.7900),130    ("Lévis (Saint-Nicolas)", "banlieue", 46.7000, -71.3900),131    ("Lac-Saint-Jean", "rural éloigné", 48.5, -71.9),132    ("Côte-Nord", "rural éloigné", 50.2, -66.4),133    ("Nunavik", "rural éloigné", 58.1, -68.4),134]135SCHEMA = {  # couche → (zoom min, zoom max, attributs permis, énumération de kind ou None)136    "water": (0, 14, {"kind", "name", "name_en"}, {"ocean", "lake", "river", "reservoir", "basin"}),137    "waterway": (8, 14, {"kind", "name", "name_en", "tunnel"}, {"river", "stream", "canal", "drain"}),138    "landcover": (4, 14, {"kind"}, {"forest", "grass", "farmland", "wetland", "rock", "sand", "scrub", "glacier"}),139    "landuse": (9, 14, {"kind", "name", "name_en"}, {"residential", "commercial", "industrial", "park", "cemetery", "school", "university", "hospital", "pitch", "golf", "parking", "airport", "military", "quarry"}),140    "boundary": (0, 14, {"level", "maritime"}, None),141    "road": (4, 14, {"kind", "link", "struct", "name", "name_en", "ref", "oneway", "layer"}, {"motorway", "trunk", "primary", "secondary", "tertiary", "minor", "service", "path", "cycleway", "track", "rail", "ferry"}),142    "transit": (10, 14, {"kind", "name", "network", "colour"}, {"subway", "light_rail", "tram", "train", "metro", "rem", "bus_terminal"}),143    "building": (13, 14, {"h", "mh", "hs", "kind", "id", "hy"}, None),144    "place": (0, 14, {"kind", "name", "name_en", "pop", "rank"}, {"country", "province", "city", "town", "village", "suburb", "neighbourhood", "hamlet"}),145    "poi": (13, 14, {"kind", "name", "name_en", "rank"}, {"university", "college", "school", "hospital", "clinic", "grocery", "pharmacy", "park", "library", "station", "airport", "mall"}),146    "housenum": (14, 14, {"num"}, None),147    "parcel": (14, 14, {"id", "area"}, None),148}149INT_ENUMS = {("boundary", "level"): {2, 4, 6, 8, 10}, ("boundary", "maritime"): {0, 1}, ("road", "link"): {0, 1},150             ("road", "struct"): {0, 1, 2}, ("road", "oneway"): {0, 1}, ("building", "hs"): {1, 2, 3, 4},151             ("waterway", "tunnel"): {0, 1}}152153failures, rows = [], []154155156def check(cond, msg):157    if not cond:158        failures.append(msg)159    return cond160161162def tile_xy(lat, lon, z):163    n = 2 ** z164    return int((lon + 180) / 360 * n), int((1 - math.asinh(math.tan(math.radians(lat))) / math.pi) / 2 * n)165166167def fetch(path, headers=None, method="GET"):168    req = urllib.request.Request(args.url.rstrip("/") + path, headers={"Accept-Encoding": "gzip", **(headers or {})}, method=method)169    t0 = time.perf_counter()170    try:171        with urllib.request.urlopen(req, timeout=60) as r:172            body = r.read()173            return r.status, dict((k.lower(), v) for k, v in r.getheaders()), body, (time.perf_counter() - t0) * 1000174    except urllib.error.HTTPError as e:175        body = e.read()176        return e.code, dict((k.lower(), v) for k, v in e.headers.items()), body, (time.perf_counter() - t0) * 1000177178179def inspect(body):180    with tempfile.NamedTemporaryFile(suffix=".mvt") as f:181        f.write(body)182        f.flush()183        r = subprocess.run([args.tiler, "inspect", f.name], capture_output=True, text=True)184    if r.returncode != 0:185        return None186    return json.loads(r.stdout)187188189# ---------------------------------------------------------------- service190st, h, body, _ = fetch("/healthz")191check(st == 200 and json.loads(body)["status"] == "ok", "healthz")192version = json.loads(body).get("data_version")193st, h, body, _ = fetch("/v1/base.json")194tj = json.loads(body)195check(st == 200 and tj["minzoom"] == 0 and tj["maxzoom"] == 14, "TileJSON zooms")196check([l["id"] for l in tj["vector_layers"]] == list(SCHEMA), "TileJSON : couches du schéma dans l'ordre")197check(tj["data_version"] == version, "TileJSON : version de données")198check(h.get("access-control-allow-origin") == "*", "CORS sur base.json")199for bad in ("/v1/base/15/0/0.mvt", "/v1/base/3/8/0.mvt", "/v1/base/-1/0/0.mvt", "/v1/base/2/1/1.pbf", "/v1/base/2/x/1.mvt", "/v1/base/02/1/1.mvt"):200    st, _, _, _ = fetch(bad)201    check(st == 400, f"requête invalide {bad} → 400 (reçu {st})")202st, _, _, _ = fetch("/metrics")203check(st == 404, "/metrics n'est pas exposé sur le port public")204st, _, _, _ = fetch("/v1/glyphs/..%2f..%2fetc%2fpasswd")205check(st in (400, 404), "traversée de répertoire refusée")206st, h, _, _ = fetch("/v1/base/0/0/0.mvt", method="OPTIONS")207check(st == 204 and "GET" in h.get("access-control-allow-methods", ""), "pré-vol CORS")208st, h, _, _ = fetch("/v1/base/14/1/1.mvt")209check(st == 204 and "etag" in h and "max-age=86400" in h.get("cache-control", ""), f"tuile vide → 204 avec ETag et Cache-Control (reçu {st})")210211# ---------------------------------------------------------------- tuiles212cold, warm, sizes = [], [], []213for name, kind, lat, lon in POINTS:214    for z in range(0, 15):215        x, y = tile_xy(lat, lon, z)216        path = f"/v1/base/{z}/{x}/{y}.mvt"217        cached = False218        if args.cache and version:219            p = os.path.join(args.cache, version, str(z), str(x), f"{y}.mvt")220            if args.purge and os.path.exists(p):221                os.remove(p)222            cached = os.path.exists(p)223        st, h, body, ms1 = fetch(path)224        if not check(st in (200, 204), f"{name} {z}/{x}/{y} : HTTP {st}"):225            continue226        st2, h2, body2, ms2 = fetch(path)227        st3, _, _, _ = fetch(path, {"If-None-Match": h.get("etag", "")})228        check(st2 == st and body2 == body, f"{name} {z}/{x}/{y} : réponse instable")229        check(st3 == 304, f"{name} {z}/{x}/{y} : If-None-Match → 304 (reçu {st3})")230        check("etag" in h and h.get("cache-control") == "public, max-age=86400, stale-while-revalidate=604800", f"{name} {z}/{x}/{y} : en-têtes de cache")231        check(h.get("access-control-allow-origin") == "*", f"{name} {z}/{x}/{y} : CORS")232        row = {"point": name, "milieu": kind, "z": z, "x": x, "y": y, "status": st, "bytes": len(body), "first_ms": round(ms1, 2), "warm_ms": round(ms2, 2), "was_cached": cached}233        if not cached:234            cold.append(ms1)235        warm.append(ms2)236        if st == 200:237            check(h.get("content-encoding") == "gzip" and body[:2] == b"\x1f\x8b", f"{name} {z}/{x}/{y} : gzip")238            check(h.get("content-type") == "application/vnd.mapbox-vector-tile", f"{name} {z}/{x}/{y} : type de contenu")239            check(len(body) <= HARD, f"{name} {z}/{x}/{y} : {len(body)} octets > plafond 500 Ko")240            sizes.append(len(body))241            info = inspect(body)242            if check(info is not None, f"{name} {z}/{x}/{y} : MVT indécodable"):243                row["raw_bytes"] = info["raw_bytes"]244                row["layers"] = {l["name"]: l["features"] for l in info["layers"]}245                order = [l["name"] for l in info["layers"]]246                check(order == [n for n in SCHEMA if n in order], f"{name} {z}/{x}/{y} : ordre ou doublon de couches {order}")247                for l in info["layers"]:248                    spec = SCHEMA.get(l["name"])249                    if not check(spec is not None, f"{name} {z}/{x}/{y} : couche hors schéma {l['name']}"):250                        continue251                    zmin, zmax, keys, enum = spec252                    check(zmin <= z <= zmax, f"{name} {z}/{x}/{y} : couche {l['name']} hors de sa plage de zooms")253                    check(l["extent"] == 4096 and l["version"] == 2, f"{name} {z}/{x}/{y} : {l['name']} étendue/version")254                    check(l["features"] > 0, f"{name} {z}/{x}/{y} : couche {l['name']} vide encodée")255                    extra = set(l["attributes"]) - keys256                    check(not extra, f"{name} {z}/{x}/{y} : {l['name']} attributs hors schéma {sorted(extra)}")257                    if enum and "kind" in l["attributes"]:258                        vals = {v[2:] for v in l["attributes"]["kind"]}259                        check(vals <= enum, f"{name} {z}/{x}/{y} : {l['name']}.kind hors schéma {sorted(vals - enum)}")260                    for (ln, key), allowed in INT_ENUMS.items():261                        if ln == l["name"] and key in l["attributes"]:262                            vals = {int(v[2:]) for v in l["attributes"][key] if v.startswith("i:")}263                            check(vals <= allowed and len(vals) == len(l["attributes"][key]), f"{name} {z}/{x}/{y} : {ln}.{key} = {sorted(l['attributes'][key])}")264                    if l["name"] == "water" and z < 8:265                        check("name" not in l["attributes"], f"{name} {z}/{x}/{y} : water.name avant z8")266        elif z <= 6:267            check(False, f"{name} {z}/{x}/{y} : tuile vide à bas zoom")268        rows.append(row)269270# présence attendue aux endroits habités271for r in rows:272    if r["milieu"] != "rural éloigné" and r["status"] == 200:273        L = r.get("layers", {})274        if r["z"] == 14:275            check({"road", "building"} <= set(L), f"{r['point']} z14 : routes et bâtiments attendus, reçu {sorted(L)}")276        if 6 <= r["z"] <= 12:277            check("road" in L and "place" in L or r["z"] > 9 and "road" in L, f"{r['point']} z{r['z']} : routes attendues")278    if r["z"] <= 5:279        check(r["status"] == 200 and "water" in r.get("layers", {}), f"{r['point']} z{r['z']} : contexte (eau) attendu")280281282# ---------------------------------------------------------------- continuité des grands plans d'eau283# Le fleuve doit être de l'eau, sans trou, des Grands Lacs au golfe, à chaque zoom où sa largeur dépasse284# quelques unités de tuile ; idem Outaouais, Saguenay, Richelieu, lac Saint-Jean.285WATER_POINTS = [  # nom, lat, lon, premier zoom exigé286    # Points pris sur l'axe des cours d'eau (relations waterway d'OSM), vérifiés dans l'eau dans la base.287    ("Saint-Laurent, Cornwall (lac Saint-François)", 45.0443, -74.5572, 5),288    ("Saint-Laurent, Montréal (aval du pont Jacques-Cartier)", 45.5332, -73.5347, 5),289    ("Saint-Laurent, Sorel", 46.0590, -73.0985, 5),290    ("Saint-Laurent, lac Saint-Pierre", 46.200, -72.830, 4),291    ("Saint-Laurent, Trois-Rivières", 46.3315, -72.5321, 5),292    ("Saint-Laurent, Portneuf", 46.6626, -71.8934, 5),293    ("Saint-Laurent, Québec (ponts)", 46.7438, -71.3019, 6),294    ("Saint-Laurent, Québec (Vieux-Port)", 46.8162, -71.1913, 6),295    ("Saint-Laurent, île d'Orléans (chenal sud)", 46.870, -70.960, 5),296    ("Estuaire, Rivière-du-Loup", 47.900, -69.700, 3),297    ("Golfe, Sept-Îles", 50.000, -66.300, 0),298    ("Outaouais, Gatineau–Ottawa", 45.4399, -75.7012, 7),299    ("Outaouais, lac des Deux Montagnes", 45.450, -74.000, 5),300    ("Saguenay, Chicoutimi", 48.4338, -71.0585, 7),301    ("Saguenay, fjord", 48.3791, -70.7294, 6),302    ("Richelieu, Saint-Jean-sur-Richelieu", 45.3110, -73.2485, 9),303    ("Richelieu, bassin de Chambly", 45.4515, -73.2722, 8),304    ("Lac Saint-Jean", 48.600, -72.000, 3),305    ("Lac Champlain (baie Missisquoi)", 45.030, -73.130, 5),306]307water_rows = []308for wname, lat, lon, zreq in WATER_POINTS:309    seen = {}310    for z in range(0, 15):311        x, y = tile_xy(lat, lon, z)312        st, h, body, _ = fetch(f"/v1/base/{z}/{x}/{y}.mvt")313        ok = False314        if st == 200:315            with tempfile.NamedTemporaryFile(suffix=".mvt") as f:316                f.write(body)317                f.flush()318                r = subprocess.run([args.tiler, "inspect", f.name, "--tile", f"{z}/{x}/{y}", "--at", f"{lon},{lat}"], capture_output=True, text=True)319            if r.returncode == 0:320                ok = any(hit["layer"] == "water" for hit in json.loads(r.stdout)["hits"])321        seen[z] = ok322        if z >= zreq:323            check(ok, f"eau absente : {wname} à z{z} ({z}/{x}/{y})")324    water_rows.append({"point": wname, "required_from": zreq, "water_at_zoom": "".join("1" if seen[z] else "0" for z in range(0, 15)),325                       "first_zoom_with_water": next((z for z in range(0, 15) if seen[z]), None)})326327# ---------------------------------------------------------------- largeur visible du fleuve aux petites échelles328# Présent ne suffit pas : à z3–z6 le fleuve fait moins d'un pixel entre Montréal et Québec et ne se voyait pas329# (retour L14). Le pipeline l'épaissit ; on exige de l'eau sur au moins 6 des 8 points d'un cercle de 4 unités de330# tuile (un demi-pixel d'une tuile de 512) autour de points pris sur l'axe du chenal.331def water_at(z, lat, lon):332    x, y = tile_xy(lat, lon, z)333    st, h, body, _ = fetch(f"/v1/base/{z}/{x}/{y}.mvt")334    if st != 200:335        return False336    with tempfile.NamedTemporaryFile(suffix=".mvt") as f:337        f.write(body)338        f.flush()339        r = subprocess.run([args.tiler, "inspect", f.name, "--tile", f"{z}/{x}/{y}", "--at", f"{lon},{lat}"], capture_output=True, text=True)340    return r.returncode == 0 and any(hit["layer"] == "water" for hit in json.loads(r.stdout)["hits"])341342343WIDTH_POINTS = [("Montréal (aval du pont Jacques-Cartier)", 45.5332, -73.5347), ("Sorel", 46.0590, -73.0985),344                ("Trois-Rivières", 46.3315, -72.5321), ("Portneuf", 46.6626, -71.8934), ("Québec (ponts)", 46.7438, -71.3019)]345width_rows = []346for wname, lat, lon in WIDTH_POINTS:347    res = {}348    for z in range(3, 8):349        r_m = 4 * 40075016.686 / 4096 / 2 ** z  # mètres Mercator350        hits = 0351        for k in range(8):352            a = math.pi * k / 4353            dlon = r_m * math.cos(a) / 111319.49354            dlat = r_m * math.sin(a) / 111319.49 * math.cos(math.radians(lat))355            hits += water_at(z, lat + dlat, lon + dlon)356        res[z] = hits357        if z >= 4:358            check(hits >= 6, f"fleuve trop mince pour être vu : {wname} à z{z} ({hits}/8 points à 4 unités de l'axe)")359    width_rows.append({"point": wname, "points_in_water_of_8": {f"z{z}": n for z, n in res.items()}})360361# ---------------------------------------------------------------- latence à froid sur un échantillon aléatoire362cold_rows = []363if args.cold_sample and args.cache and version:364    import random365    rnd = random.Random(20261201)366    W, S, E, N = -79.77, 44.99, -57.10, 62.59367    for z in range(0, 15):368        lat_ms = []369        sizes_z = []370        tiles_z = set()371        tries = 0372        while len(tiles_z) < min(args.cold_sample, 4 ** z) and tries < args.cold_sample * 50:373            tries += 1  # aux zooms moyens l'emprise compte moins de tuiles distinctes que l'échantillon demandé374            if z <= 5:375                tiles_z.add((rnd.randrange(2 ** z), rnd.randrange(2 ** z)))376            else:377                # deux tiers de l'échantillon dans le Québec habité (sud), un tiers sur tout le territoire378                if rnd.random() < 0.66:379                    tiles_z.add(tile_xy(rnd.uniform(45.0, 48.8), rnd.uniform(-79.4, -64.5), z))380                else:381                    tiles_z.add(tile_xy(rnd.uniform(S, N), rnd.uniform(W, E), z))382        for x, y in sorted(tiles_z):383            pth = os.path.join(args.cache, version, str(z), str(x), f"{y}.mvt")384            try:385                os.remove(pth)386            except FileNotFoundError:387                pass388            st, h, body, ms = fetch(f"/v1/base/{z}/{x}/{y}.mvt")389            check(st in (200, 204), f"à froid {z}/{x}/{y} : HTTP {st}")390            check(len(body) <= HARD, f"à froid {z}/{x}/{y} : {len(body)} octets > 500 Ko")391            lat_ms.append(ms)392            sizes_z.append(len(body))393        lat_ms.sort()394        row = {"z": z, "n": len(lat_ms), "p50_ms": round(lat_ms[len(lat_ms) // 2], 1), "p95_ms": round(lat_ms[min(len(lat_ms) - 1, int(len(lat_ms) * 0.95))], 1),395               "max_ms": round(lat_ms[-1], 1), "max_bytes": max(sizes_z), "median_bytes": int(statistics.median(sizes_z))}396        check(row["p95_ms"] < 1000, f"à froid z{z} : p95 {row['p95_ms']} ms ≥ 1 s")397        cold_rows.append(row)398399400# ---------------------------------------------------------------- octets déterministes401det = None402if args.determinism and args.cache and version:403    import hashlib, random as _r404    rnd2 = _r.Random(4242)405    centres = [(45.5019, -73.5674), (46.8139, -71.2080), (45.57, -73.75), (45.44, -75.70), (48.43, -71.07), (45.40, -71.90),406               (46.35, -72.55), (48.24, -79.02), (50.2, -66.4), (48.45, -68.52), (47.0, -70.6), (53.5, -73.5)]407    todo = set()408    while len(todo) < args.determinism:409        lat, lon = centres[rnd2.randrange(len(centres))]410        z = rnd2.randrange(3, 15)411        span = 360 / 2 ** z412        x, y = tile_xy(lat + rnd2.uniform(-2, 2) * span * 0.7, lon + rnd2.uniform(-3, 3) * span, z)413        todo.add((z, x, y))414    same = diff = empty = 0415    diffs = []416    for z, x, y in sorted(todo):417        pth = os.path.join(args.cache, version, str(z), str(x), f"{y}.mvt")418        res = []419        for _ in range(2):420            try:421                os.remove(pth)422            except FileNotFoundError:423                pass424            st, h, body, _ms = fetch(f"/v1/base/{z}/{x}/{y}.mvt")425            res.append((st, h.get("etag"), hashlib.sha256(body).hexdigest(), len(body)))426        if res[0] == res[1]:427            same += 1428            empty += res[0][3] == 0429        else:430            diff += 1431            diffs.append(f"{z}/{x}/{y} {res[0][3]} vs {res[1][3]} octets")432            check(False, f"tuile non déterministe {z}/{x}/{y}")433    det = {"tiles": len(todo), "identical": same, "different": diff, "of_which_empty": empty, "examples": diffs[:10]}434435436def pct(v, p):437    v = sorted(v)438    return round(v[min(len(v) - 1, int(len(v) * p))], 2) if v else None439440441over_soft = [r for r in rows if r["bytes"] > SOFT]442summary = {443    "url": args.url, "data_version": version, "tiles": len(rows), "failures": failures,444    "status_200": sum(r["status"] == 200 for r in rows), "status_204": sum(r["status"] == 204 for r in rows),445    "bytes_median": int(statistics.median(sizes)) if sizes else 0, "bytes_p95": pct(sizes, 0.95), "bytes_max": max(sizes) if sizes else 0,446    "over_150k": [f"{r['point']} {r['z']}/{r['x']}/{r['y']} = {r['bytes']}" for r in over_soft],447    "over_500k": sum(r["bytes"] > HARD for r in rows),448    "cold_n": len(cold), "cold_ms_median": round(statistics.median(cold), 2) if cold else None, "cold_ms_p95": pct(cold, 0.95), "cold_ms_max": round(max(cold), 2) if cold else None,449    "warm_n": len(warm), "warm_ms_median": round(statistics.median(warm), 2) if warm else None, "warm_ms_p95": pct(warm, 0.95), "warm_ms_max": round(max(warm), 2) if warm else None,450}451summary["determinism"] = det452summary["water_continuity"] = water_rows453summary["river_visible_width"] = width_rows454summary["cold_random_sample"] = cold_rows455if args.json:456    json.dump({"summary": summary, "tiles": rows}, open(args.json, "w"), ensure_ascii=False, indent=1)457print(json.dumps(summary, ensure_ascii=False, indent=1))458sys.exit(1 if failures else 0)459
Files main
Menu

Theme