Make the monthly place check compare like with like, fail loudly on a bad outline download, and bring twelve placements up to date
The 2026-12-01 run reported 440 differences, but the outlines had not changed: a fresh download on 2026-12-03 matched the 2026-11-20 files byte for byte. The check counted every new download date as a difference, counted stated placements of trails with no track before but not after (so Zion, Arches and others read as "down to 0 trails"), and let the Montana and British Columbia Glacier parks push each other to suffixed slugs. A download date alone is no longer a difference; both sides of the 3-trail line count stated placements; Glacier National Park, Montana keeps the plain slug. An ArcGIS download now asks the service for its count and must bring exactly that many features, a service error body is raised, a source that yields no outlines is an error, and a registered place whose outline is gone stops the check naming it (exit 3), never "0 trails". The twelve real differences left are applied: ten trails gain a place the tool measures (Sheltowee Trace in Big South Fork; nine trails in the parent range left when a child range was dropped on 2026-11-20), and two wilderness twins of a same-named park are taken off the Brooks Range Traverse and the Guadalupe Ridge Trail and out of places.toml. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
05284f87a1
commit
41019c81e1
16 files changed
+402
-78
No files matched your search
+115
-35
@@ -195,33 +195,68 @@ def cache_dir():
|
||||
return d
|
||||
|
||||
|
||||
class SourceError(RuntimeError):
|
||||
"""An outline source failed, came back empty, or came back short. The check stops on
|
||||
this, naming the source: a missing outline must never read as a trail in no place."""
|
||||
|
||||
|
||||
def _download(url, dest):
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "longhikes place_trails.py"})
|
||||
got = 0
|
||||
with urllib.request.urlopen(req, timeout=600) as r, open(dest + ".part", "wb") as f:
|
||||
want = r.headers.get("Content-Length")
|
||||
while True:
|
||||
chunk = r.read(1 << 20)
|
||||
if not chunk:
|
||||
break
|
||||
got += len(chunk)
|
||||
f.write(chunk)
|
||||
if got == 0 or (want and int(want) != got):
|
||||
os.remove(dest + ".part")
|
||||
raise SourceError(f"{url}: download came back with {got} bytes"
|
||||
+ (f", not the {want} the server announced" if want else ""))
|
||||
os.rename(dest + ".part", dest)
|
||||
|
||||
|
||||
def _arcgis_get(query_url, params):
|
||||
"""One ArcGIS query as JSON. ArcGIS answers some failures with HTTP 200 and an
|
||||
{"error": ...} body; that is raised, not read as no features."""
|
||||
url = query_url + "?" + urllib.parse.urlencode(params)
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "longhikes place_trails.py"})
|
||||
with urllib.request.urlopen(req, timeout=300) as r:
|
||||
page = json.load(r)
|
||||
if not isinstance(page, dict) or page.get("error"):
|
||||
raise SourceError(f"{query_url}: the service answered with an error: "
|
||||
f"{(page or {}).get('error') if isinstance(page, dict) else page!r}")
|
||||
return page
|
||||
|
||||
|
||||
def _arcgis_geojson(query_url, where, out_fields, dest):
|
||||
"""Page an ArcGIS query into one cached GeoJSON file, in lon/lat."""
|
||||
"""Page an ArcGIS query into one cached GeoJSON file, in lon/lat.
|
||||
|
||||
The service is first asked how many features match; the download must bring exactly
|
||||
that many, or it raises. A page is never taken as the last one just because it is short
|
||||
(a service may cap a page below the size asked for); paging stops when a page is empty
|
||||
or the count is reached."""
|
||||
count = _arcgis_get(query_url, {"where": where, "returnCountOnly": "true", "f": "json"})
|
||||
want = count.get("count")
|
||||
if not isinstance(want, int) or want <= 0:
|
||||
raise SourceError(f"{query_url}: the service reports {want!r} features for {where!r}")
|
||||
features, offset = [], 0
|
||||
while True:
|
||||
while len(features) < want:
|
||||
params = {"where": where, "outFields": out_fields, "returnGeometry": "true",
|
||||
"outSR": "4326", "f": "geojson", "resultRecordCount": "1000",
|
||||
"resultOffset": str(offset), "orderByFields": "OBJECTID"}
|
||||
url = query_url + "?" + urllib.parse.urlencode(params)
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "longhikes place_trails.py"})
|
||||
with urllib.request.urlopen(req, timeout=300) as r:
|
||||
page = json.load(r)
|
||||
got = page.get("features") or []
|
||||
features.extend(got)
|
||||
if len(got) < 1000:
|
||||
got = _arcgis_get(query_url, params).get("features") or []
|
||||
if not got:
|
||||
break
|
||||
features.extend(got)
|
||||
offset += len(got)
|
||||
if len(features) != want:
|
||||
raise SourceError(f"{query_url}: downloaded {len(features)} features, but the service "
|
||||
f"reports {want}")
|
||||
if not any(f.get("geometry") for f in features):
|
||||
raise SourceError(f"{query_url}: every feature came back with no geometry")
|
||||
with open(dest, "w", encoding="utf-8") as f:
|
||||
json.dump({"type": "FeatureCollection", "features": features}, f)
|
||||
|
||||
@@ -338,8 +373,7 @@ def _read_vector(path, columns=None, bbox=None):
|
||||
import pyogrio
|
||||
import pyogrio.raw
|
||||
from pyproj import Transformer
|
||||
from shapely import from_wkb
|
||||
from shapely.ops import transform
|
||||
from shapely import from_wkb, transform
|
||||
if str(path).endswith(".zip"):
|
||||
import zipfile
|
||||
with zipfile.ZipFile(path) as z:
|
||||
@@ -361,7 +395,7 @@ def _read_vector(path, columns=None, bbox=None):
|
||||
for row, wkb in zip(rows, geoms):
|
||||
g = from_wkb(wkb) if wkb is not None else None
|
||||
if g is not None and transformer is not None:
|
||||
g = transform(transformer.transform, g)
|
||||
g = transform(g, transformer.transform, interleaved=False)
|
||||
row["_geometry"] = g if g is None or g.is_valid else g.buffer(0)
|
||||
return rows
|
||||
|
||||
@@ -491,6 +525,9 @@ def default_allowlist_path():
|
||||
# permanent, so this is a decision made once.
|
||||
SLUG_KEEPS_PLAIN = {
|
||||
("wilderness", "wilderness-connect", "239"), # Hells Canyon Wilderness, Idaho and Oregon
|
||||
# Glacier National Park, Montana; CPCAD's "Glacier National Park Of Canada" (British
|
||||
# Columbia, no trails here) cleans to the same name and takes glacier-national-park-bc.
|
||||
("park", "nps", "GLAC"),
|
||||
}
|
||||
|
||||
|
||||
@@ -590,6 +627,15 @@ def merge_same_name(outlines):
|
||||
return out
|
||||
|
||||
|
||||
def _read_source(key, cache):
|
||||
"""A source's outlines, or SourceError when it yields none."""
|
||||
path, _ver = fetch(SOURCES[key], cache)
|
||||
rows = SOURCES[key].read(path)
|
||||
if not rows:
|
||||
raise SourceError(f"{key} ({SOURCES[key].url}): the downloaded file holds no outlines")
|
||||
return rows
|
||||
|
||||
|
||||
def catalogue(cache, allowlist=None):
|
||||
"""The outlines to measure: parks whole, wilderness whole, ranges allow-listed only."""
|
||||
allowlist = allowlist if allowlist is not None else load_allowlist(default_allowlist_path())
|
||||
@@ -598,8 +644,8 @@ def catalogue(cache, allowlist=None):
|
||||
joined = [p for p in allowlist["park"] if isinstance(p.get("source_id"), list)]
|
||||
joined_ids = {str(s) for p in joined for s in p["source_id"]}
|
||||
out = []
|
||||
path, _ver = fetch(SOURCES["nps"], cache)
|
||||
for o in SOURCES["nps"].read(path):
|
||||
nps = _read_source("nps", cache)
|
||||
for o in nps:
|
||||
if str(o.source_id) in joined_ids:
|
||||
continue
|
||||
extra = extras.get(str(o.source_id))
|
||||
@@ -610,17 +656,15 @@ def catalogue(cache, allowlist=None):
|
||||
o.where_hand = tuple(extra.get("where") or ())
|
||||
out.append(o)
|
||||
for p in joined:
|
||||
parts = [o for o in SOURCES["nps"].read(path) if str(o.source_id) in [str(s) for s in p["source_id"]]]
|
||||
parts = [o for o in nps if str(o.source_id) in [str(s) for s in p["source_id"]]]
|
||||
if parts:
|
||||
out.append(Outline("park", "nps", [str(s) for s in p["source_id"]],
|
||||
p.get("name") or parts[0].name,
|
||||
sorted({h for o in parts for h in o.state_codes_hint}),
|
||||
_union_geoms(o.geometry for o in parts),
|
||||
slug=p.get("slug") or "", where_hand=tuple(p.get("where") or ())))
|
||||
path, _ver = fetch(SOURCES["cpcad"], cache)
|
||||
out.extend(SOURCES["cpcad"].read(path))
|
||||
path, _ver = fetch(SOURCES["wilderness-connect"], cache)
|
||||
out.extend(SOURCES["wilderness-connect"].read(path))
|
||||
out.extend(_read_source("cpcad", cache))
|
||||
out.extend(_read_source("wilderness-connect", cache))
|
||||
wanted = {str(r.get("gmba_id")): r for r in allowlist["range"]}
|
||||
if wanted:
|
||||
for g in gmba_ranges(cache):
|
||||
@@ -642,8 +686,7 @@ _GMBA_CACHE = {}
|
||||
|
||||
def gmba_ranges(cache):
|
||||
if cache not in _GMBA_CACHE:
|
||||
path, _ver = fetch(SOURCES["gmba-v2"], cache)
|
||||
_GMBA_CACHE[cache] = SOURCES["gmba-v2"].read(path)
|
||||
_GMBA_CACHE[cache] = _read_source("gmba-v2", cache)
|
||||
return _GMBA_CACHE[cache]
|
||||
|
||||
|
||||
@@ -1239,22 +1282,61 @@ def stamp_none(root, rid, today):
|
||||
_save(doc, path)
|
||||
|
||||
|
||||
def missing_from_sources(entries, outlines):
|
||||
"""Registry entries measured from a track whose outline the sources no longer hold, as
|
||||
"kind/slug (source id)". An outline that went missing (a failed or short download, a
|
||||
renamed field, a moved layer) is an error to fix, never a place with no trails."""
|
||||
have = set()
|
||||
for o in outlines:
|
||||
for i in (o.source_id if isinstance(o.source_id, list) else [o.source_id]):
|
||||
have.add((o.source, str(i)))
|
||||
out = []
|
||||
for e in entries:
|
||||
if e.get("source") not in SOURCES:
|
||||
continue
|
||||
ids = e.get("source_id")
|
||||
for i in (ids if isinstance(ids, list) else [ids]):
|
||||
if (e["source"], str(i)) not in have:
|
||||
out.append(f"{e.get('kind')}/{e.get('slug')} ({e['source']} {i})")
|
||||
return out
|
||||
|
||||
|
||||
def check(root, cache, outlines=None, versions=None, records=None):
|
||||
"""Re-measure every track against the current outlines; one difference per line."""
|
||||
"""Re-measure every track against the current outlines; one difference per line.
|
||||
|
||||
A source_version that differs is not a difference: every source here is versioned by
|
||||
its download date, so a fresh download always differs. What the outline does to the
|
||||
trails is what is compared; `apply` stamps the new date when a difference is applied.
|
||||
`versions` is accepted and unused, for callers that still pass it."""
|
||||
if outlines is None:
|
||||
outlines = catalogue(cache)
|
||||
if versions is None:
|
||||
versions = source_versions(cache)
|
||||
if records is None:
|
||||
records = load_records(root)
|
||||
lost = missing_from_sources(registry_entries(root), outlines)
|
||||
if lost:
|
||||
raise SourceError("the sources no longer hold the outline of " + str(len(lost))
|
||||
+ " registered place(s): " + ", ".join(lost))
|
||||
p = propose(records, outlines, {(e.get("kind"), e.get("slug")): e.get("where")
|
||||
for e in registry_entries(root)})
|
||||
diffs = []
|
||||
current_counts = {}
|
||||
# Both counts are taken the same way: a record's places as stored (no parents), with
|
||||
# the track's measured places in place of its stored track places. Stated places (hand
|
||||
# placements from a cited page) are on both sides; a check that left them off one side
|
||||
# reported every park held up by stated trails as losing them.
|
||||
current_counts, new_counts = {}, {}
|
||||
for r in records:
|
||||
for pl in (r.get("rec") or {}).get("place") or []:
|
||||
current_counts[(pl.get("kind"), pl.get("slug"))] = \
|
||||
current_counts.get((pl.get("kind"), pl.get("slug")), 0) + 1
|
||||
rec = r.get("rec") or {}
|
||||
stored = {(pl.get("kind"), pl.get("slug")) for pl in rec.get("place") or []}
|
||||
for k in stored:
|
||||
current_counts[k] = current_counts.get(k, 0) + 1
|
||||
if r.get("track") is None:
|
||||
now = stored
|
||||
else:
|
||||
now = {(pl.get("kind"), pl.get("slug")) for pl in rec.get("place") or []
|
||||
if pl.get("basis") != "track"}
|
||||
now |= {k for k, _km in p.per_trail.get(r["id"], [])}
|
||||
for k in now:
|
||||
new_counts[k] = new_counts.get(k, 0) + 1
|
||||
for r in records:
|
||||
rec = r.get("rec") or {}
|
||||
if r.get("track") is None:
|
||||
@@ -1272,7 +1354,6 @@ def check(root, cache, outlines=None, versions=None, records=None):
|
||||
tdir = os.path.join(root, r["id"])
|
||||
if rec.get("places_track") and line_file_of(tdir) and track_hash(tdir) != rec["places_track"]:
|
||||
diffs.append(f"{r['id']}: the track has changed since its places were measured")
|
||||
new_counts = {k: len(h.trails) for k, h in p.per_place.items()}
|
||||
for k in sorted(set(current_counts) | set(new_counts)):
|
||||
was, now = current_counts.get(k, 0) >= 3, new_counts.get(k, 0) >= 3
|
||||
if was != now:
|
||||
@@ -1287,11 +1368,6 @@ def check(root, cache, outlines=None, versions=None, records=None):
|
||||
for k in sorted(doubled_places(final, shown)):
|
||||
diffs.append(f"{k[0]}/{k[1]}: holds exactly the trails of a park of the same name; "
|
||||
f"list the park only")
|
||||
for e in registry_entries(root):
|
||||
v = versions.get(e.get("source"))
|
||||
if v and e.get("source_version") and e["source_version"] != v:
|
||||
diffs.append(f"{e.get('kind')}/{e.get('slug')}: source_version changed "
|
||||
f"from {e['source_version']} to {v}")
|
||||
return diffs
|
||||
|
||||
|
||||
@@ -1393,7 +1469,11 @@ def main(argv=None):
|
||||
return 1
|
||||
return 0
|
||||
if cmd == "--check":
|
||||
diffs = check(ROOT, cache_dir())
|
||||
try:
|
||||
diffs = check(ROOT, cache_dir())
|
||||
except SourceError as e:
|
||||
print(f"place_trails.py: an outline source failed: {e}", file=sys.stderr)
|
||||
return 3
|
||||
for d in diffs:
|
||||
print(d)
|
||||
print(f"{len(diffs)} difference(s)" if diffs else "no differences")
|
||||
|
||||
@@ -670,7 +670,9 @@ class ApplyTest(unittest.TestCase):
|
||||
records=records)
|
||||
text = "\n".join(diffs)
|
||||
self.assertIn("measurement changed", text) # the moved boundary
|
||||
gone = outline("park", "P9", "Elsewhere Park",
|
||||
# The same outline, redrawn away from every track (a missing outline is an error:
|
||||
# FailedSourceTest).
|
||||
gone = outline("park", "P1", "Alpha Park",
|
||||
Polygon([(-100, 43), (-99, 43), (-99, 44), (-100, 44)]), hint=["WY"])
|
||||
diffs = P.check(self.root, None, outlines=[gone], versions={"nps": "2026-11-20"},
|
||||
records=records)
|
||||
@@ -693,5 +695,104 @@ class ApplyTest(unittest.TestCase):
|
||||
self.assertEqual(errors, [])
|
||||
|
||||
|
||||
@unittest.skipUnless(HAVE, "shapely (the .venv-places venv) is not installed")
|
||||
class FailedSourceTest(unittest.TestCase):
|
||||
"""The 2026-12-01 monthly check: a missing outline or a stated placement must never
|
||||
read as a park with no trails, and a fresh download date alone is no difference."""
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.root = self.tmp.name
|
||||
make_repo(self.root)
|
||||
self.park = outline("park", "P1", "Alpha Park",
|
||||
Polygon([(-110, 43), (-109, 43), (-109, 44), (-110, 44)]), hint=["WY"])
|
||||
track = LineString([(-109.5, 43.2), (-109.5, 43.29)])
|
||||
p = P.propose([rec(r, ["WY"], track) for r in ("aa", "bb", "cc")] + [rec("zz", ["WY"], None)],
|
||||
[self.park])
|
||||
p.versions = {"nps": "2026-11-20"}
|
||||
pdir = os.path.join(self.root, "out")
|
||||
P.render_proposal(p, os.path.join(pdir, "proposal.md"))
|
||||
P.apply(os.path.join(pdir, "proposal.json"), self.root, "2026-11-20")
|
||||
self.records = P.load_records(self.root)
|
||||
|
||||
def tearDown(self):
|
||||
self.tmp.cleanup()
|
||||
|
||||
def test_an_outline_missing_from_the_sources_fails_naming_it_instead_of_zero_trails(self):
|
||||
elsewhere = outline("park", "P9", "Elsewhere Park",
|
||||
Polygon([(-100, 43), (-99, 43), (-99, 44), (-100, 44)]), hint=["WY"])
|
||||
with self.assertRaises(P.SourceError) as e:
|
||||
P.check(self.root, None, outlines=[elsewhere], records=self.records)
|
||||
self.assertIn("park/alpha-park (nps P1)", str(e.exception))
|
||||
|
||||
def test_an_empty_source_file_fails_naming_the_source(self):
|
||||
with tempfile.TemporaryDirectory() as cache:
|
||||
src = P.SOURCES["nps"]
|
||||
with open(os.path.join(cache, src.filename), "w") as f:
|
||||
json.dump({"type": "FeatureCollection", "features": []}, f)
|
||||
with self.assertRaises(P.SourceError) as e:
|
||||
P.catalogue(cache, {"park": [], "range": []})
|
||||
self.assertIn("nps", str(e.exception))
|
||||
|
||||
def test_a_short_or_failed_arcgis_download_fails(self):
|
||||
def feats(n):
|
||||
return [{"type": "Feature", "properties": {"UNIT_CODE": "X"},
|
||||
"geometry": {"type": "Point", "coordinates": [0, 0]}}] * n
|
||||
real = P._arcgis_get
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
dest = os.path.join(d, "out.geojson")
|
||||
try:
|
||||
# The service caps a page at 600 though 1000 were asked: all 1500 still come.
|
||||
pages = iter([{"count": 1500}, {"features": feats(600)},
|
||||
{"features": feats(600)}, {"features": feats(300)}])
|
||||
P._arcgis_get = lambda url, params: next(pages)
|
||||
P._arcgis_geojson("u", "1=1", "*", dest)
|
||||
with open(dest) as f:
|
||||
self.assertEqual(len(json.load(f)["features"]), 1500)
|
||||
# The service stops answering features partway: an error, not a short file.
|
||||
pages = iter([{"count": 1500}, {"features": feats(1000)}, {"features": []}])
|
||||
P._arcgis_get = lambda url, params: next(pages)
|
||||
with self.assertRaises(P.SourceError):
|
||||
P._arcgis_geojson("u", "1=1", "*", dest + "2")
|
||||
self.assertFalse(os.path.exists(dest + "2"))
|
||||
finally:
|
||||
P._arcgis_get = real
|
||||
|
||||
def test_stated_placements_count_on_both_sides_of_the_three_trail_line(self):
|
||||
# Alpha Park holds two measured trails and one stated (cc has no track): three, a page.
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
make_repo(root)
|
||||
cc = os.path.join(root, "cc", "trail.toml")
|
||||
with open(cc) as f:
|
||||
text = f.read()
|
||||
with open(cc, "w") as f:
|
||||
f.write(text.replace('line_file = "line.geojson"', 'line_file = ""'))
|
||||
track = LineString([(-109.5, 43.2), (-109.5, 43.29)])
|
||||
p = P.propose([rec("aa", ["WY"], track), rec("bb", ["WY"], track),
|
||||
rec("cc", ["WY"], None), rec("zz", ["WY"], None)], [self.park])
|
||||
p.versions = {"nps": "2026-11-20"}
|
||||
P.render_proposal(p, os.path.join(root, "out", "proposal.md"))
|
||||
P.apply(os.path.join(root, "out", "proposal.json"), root, "2026-11-20")
|
||||
P.add_stated(root, "cc", "park", "alpha-park", "https://example.org/cc",
|
||||
"The trail runs through Alpha Park.", "2026-11-20")
|
||||
records = P.load_records(root)
|
||||
self.assertEqual(P.check(root, None, outlines=[self.park],
|
||||
versions={"nps": "2026-11-20"}, records=records), [])
|
||||
|
||||
def test_a_new_download_date_alone_is_no_difference(self):
|
||||
self.assertEqual(P.check(self.root, None, outlines=[self.park],
|
||||
versions={"nps": "2026-12-01"}, records=self.records), [])
|
||||
|
||||
def test_montanas_glacier_keeps_the_plain_slug_beside_canadas(self):
|
||||
geom = Polygon([(-110, 43), (-109, 43), (-109, 44), (-110, 44)])
|
||||
mt = outline("park", "GLAC", "Glacier National Park", geom,
|
||||
slug="glacier-national-park", hint=["MT"])
|
||||
bc = outline("park", "713700000", "Glacier National Park", geom, slug="", hint=["BC"])
|
||||
bc.slug = ""
|
||||
bc.source = "cpcad"
|
||||
P.assign_slugs([mt, bc])
|
||||
self.assertEqual((mt.slug, bc.slug), ("glacier-national-park", "glacier-national-park-bc"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user