Coverage for app/backend/src/couchers/helpers/community_checks.py: 96%
172 statements
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-23 10:14 +0000
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-23 10:14 +0000
1"""
2Checks that communities fit together: that the parent links form a tree with the right types, and that each boundary is
3valid, lies inside its parent's and does not overlap its neighbours much.
4"""
6import logging
7from collections import Counter, defaultdict
8from collections.abc import Iterable, Iterator, Sequence
9from dataclasses import dataclass
10from datetime import datetime, timedelta
11from typing import Any
13from sqlalchemy import ColumnElement, and_, case, exists, func, select
14from sqlalchemy.orm import Session
16from couchers.models import (
17 Cluster,
18 CommunityCheckRun,
19 CommunityIssue,
20 CommunityIssuePriority,
21 Node,
22 NodeType,
23 User,
24)
26logger = logging.getLogger(__name__)
28CITY_TYPES = {NodeType.locality, NodeType.sublocality}
29MAX_CITY_KM2 = 10_000
30ACTIVE_WINDOW = timedelta(days=90)
32RULES = (
33 "parent_loop",
34 "missing_parent",
35 "official_cluster",
36 "type_by_level",
37 "type_not_below_parent",
38 "duplicate_boundary",
39 "invalid_boundary",
40 "outside_parent",
41 "overlap",
42 "oversized_city",
43)
45# Casting to geography fails on the 180°-long edges of the world's and continents' boundaries, so areas are measured in
46# an equal-area projection instead. Some boundaries reach a little past ±180°, and without +over the projection wraps
47# those points round to the other side of the world, so that a small island group measures as wide as the globe.
48EQUAL_AREA = "+proj=cea +lat_ts=30 +ellps=WGS84 +units=m +over"
51def _km2(geom: Any) -> ColumnElement[Any]:
52 return func.ST_Area(func.ST_Transform(geom, EQUAL_AREA)) / 1e6
55def _area_geojson(geom: Any) -> ColumnElement[str]:
56 return func.ST_AsGeoJSON(func.ST_SimplifyPreserveTopology(func.ST_CollectionExtract(geom, 3), 0.005), 5)
59@dataclass(frozen=True)
60class Community:
61 id: int
62 parent_id: int | None
63 type: NodeType
64 name: str
65 clusters: int
66 invalid_reason: str | None
67 geom_hash: str
68 area_km2: float
70 @property
71 def label(self) -> str:
72 return f"{self.name} ({self.id})"
75@dataclass(frozen=True)
76class Issue:
77 rule: str
78 community: Community
79 other: Community | None = None
80 area_km2: float | None = None
81 share: float | None = None
82 details: str = ""
83 area_geojson: str | None = None
85 @property
86 def priority(self) -> CommunityIssuePriority:
87 if self.rule == "oversized_city":
88 return CommunityIssuePriority.low
89 if self.rule == "outside_parent":
90 if self.community.type == NodeType.region:
91 return CommunityIssuePriority.low
92 return CommunityIssuePriority.medium
93 if self.rule == "overlap": 93 ↛ 102line 93 didn't jump to line 102 because the condition on line 93 was always true
94 assert self.other is not None
95 types = (self.community.type, self.other.type)
96 cities = [t in CITY_TYPES for t in types]
97 if all(cities):
98 return CommunityIssuePriority.high
99 if any(cities) or NodeType.subregion in types:
100 return CommunityIssuePriority.medium
101 return CommunityIssuePriority.low
102 return CommunityIssuePriority.high
104 @property
105 def key(self) -> tuple[str, int, int | None]:
106 return (self.rule, self.community.id, self.other.id if self.other else None)
109def load_communities(session: Session) -> dict[int, Community]:
110 official = (
111 select(
112 Cluster.parent_node_id.label("node_id"),
113 func.count().label("clusters"),
114 func.min(Cluster.name).label("name"),
115 )
116 .where(Cluster.is_official_cluster)
117 .group_by(Cluster.parent_node_id)
118 .subquery()
119 )
120 rows = session.execute(
121 select(
122 Node.id,
123 Node.parent_node_id,
124 Node.node_type,
125 func.coalesce(official.c.clusters, 0).label("clusters"),
126 official.c.name,
127 case((~func.ST_IsValid(Node.geom), func.ST_IsValidReason(Node.geom))).label("invalid_reason"),
128 func.md5(func.ST_AsBinary(Node.geom)).label("geom_hash"),
129 _km2(Node.geom).label("area_km2"),
130 )
131 .outerjoin(official, official.c.node_id == Node.id)
132 .order_by(Node.id)
133 ).all()
134 return {
135 row.id: Community(
136 id=row.id,
137 parent_id=row.parent_node_id,
138 type=row.node_type,
139 name=row.name or f"Community {row.id}",
140 clusters=row.clusters,
141 invalid_reason=row.invalid_reason,
142 geom_hash=row.geom_hash,
143 area_km2=row.area_km2,
144 )
145 for row in rows
146 }
149def _simplified_boundaries() -> Any:
150 # Boundaries simplified to about 100 m, which makes the comparisons much cheaper for large countries without moving
151 # anything near the thresholds.
152 return (
153 select(
154 Node.id,
155 Node.parent_node_id,
156 Node.node_type,
157 func.ST_CollectionExtract(func.ST_MakeValid(func.ST_SimplifyPreserveTopology(Node.geom, 0.001)), 3).label(
158 "geom"
159 ),
160 )
161 .cte("simplified")
162 .prefix_with("MATERIALIZED")
163 )
166def walk_up(communities: dict[int, Community], start: int) -> tuple[list[int], list[int] | None]:
167 """The chain of parents from start upwards, and the loop it ends in, if it ends in one."""
168 path = [start]
169 position = {start: 0}
170 parent = communities[start].parent_id
171 while parent is not None and parent in communities:
172 if parent in position:
173 return path, path[position[parent] :]
174 position[parent] = len(path)
175 path.append(parent)
176 parent = communities[parent].parent_id
177 return path, None
180def structural_issues(communities: dict[int, Community], loops: Iterable[Sequence[int]]) -> Iterator[Issue]:
181 for loop in loops:
182 chain = " → ".join(communities[i].label for i in [*loop, loop[0]])
183 for i in loop:
184 yield Issue("parent_loop", communities[i], details=f"The parent links go round in a loop: {chain}.")
186 worlds = [c for c in communities.values() if c.parent_id is None and c.type == NodeType.world]
187 by_hash = defaultdict(list)
188 for c in communities.values():
189 by_hash[c.geom_hash].append(c)
191 if c.clusters != 1:
192 yield Issue("official_cluster", c, details=f"It has {c.clusters} official clusters.")
193 if c.invalid_reason:
194 yield Issue("invalid_boundary", c, details=f"PostGIS says: {c.invalid_reason}.")
195 if c.type in CITY_TYPES and c.area_km2 > MAX_CITY_KM2:
196 yield Issue("oversized_city", c, area_km2=c.area_km2, details=f"It covers {c.area_km2:,.0f} km².")
198 if c.parent_id is None:
199 if c.type != NodeType.world:
200 yield Issue("missing_parent", c, details=f"It is a {c.type.name} with no parent.")
201 elif c is not worlds[0]: 201 ↛ 202line 201 didn't jump to line 202 because the condition on line 201 was never true
202 yield Issue("missing_parent", c, worlds[0], details=f"{worlds[0].label} is also a world.")
203 continue
204 parent = communities[c.parent_id]
205 if parent.type in (NodeType.world, NodeType.macroregion):
206 expected = NodeType.macroregion if parent.type == NodeType.world else NodeType.region
207 if c.type != expected:
208 yield Issue(
209 "type_by_level",
210 c,
211 parent,
212 details=(
213 f"It is a {c.type.name} directly under the {parent.type.name} {parent.name}, so it should be "
214 f"a {expected.name}."
215 ),
216 )
217 elif c.type.value <= parent.type.value:
218 yield Issue(
219 "type_not_below_parent",
220 c,
221 parent,
222 details=f"It is a {c.type.name}, and its parent {parent.name} is a {parent.type.name}.",
223 )
225 for same in by_hash.values():
226 for c in same[1:]:
227 yield Issue(
228 "duplicate_boundary",
229 c,
230 same[0],
231 details=f"Its boundary is identical to that of {same[0].label}.",
232 )
235def outside_parent_issues(session: Session, communities: dict[int, Community]) -> Iterator[Issue]:
236 simplified = _simplified_boundaries()
237 child = simplified.alias("child")
238 parent = simplified.alias("parent")
239 pairs = (
240 select(
241 child.c.id,
242 parent.c.id.label("parent_id"),
243 child.c.geom,
244 func.ST_Difference(child.c.geom, parent.c.geom).label("outside"),
245 )
246 .select_from(child)
247 .join(parent, parent.c.id == child.c.parent_node_id)
248 .where(parent.c.node_type != NodeType.world)
249 .cte("pairs")
250 .prefix_with("MATERIALIZED")
251 )
252 rows = session.execute(
253 select(
254 pairs.c.id,
255 pairs.c.parent_id,
256 _km2(pairs.c.geom).label("area_km2"),
257 _km2(pairs.c.outside).label("outside_km2"),
258 _area_geojson(pairs.c.outside).label("area_geojson"),
259 )
260 ).all()
261 for row in rows:
262 if not row.area_km2: 262 ↛ 263line 262 didn't jump to line 263 because the condition on line 262 was never true
263 continue
264 share = row.outside_km2 / row.area_km2
265 if row.outside_km2 > 100 or share > 0.01:
266 c = communities[row.id]
267 p = communities[row.parent_id]
268 yield Issue(
269 "outside_parent",
270 c,
271 p,
272 row.outside_km2,
273 share,
274 details=f"{row.outside_km2:,.0f} km² of it, or {share:.1%}, lies outside {p.name}.",
275 area_geojson=row.area_geojson,
276 )
279def overlap_issues(
280 session: Session, communities: dict[int, Community], ancestors: dict[int, set[int]]
281) -> Iterator[Issue]:
282 simplified = _simplified_boundaries()
283 a = simplified.alias("a")
284 b = simplified.alias("b")
285 broad = [NodeType.world, NodeType.macroregion]
286 pairs = (
287 select(
288 a.c.id.label("a_id"),
289 b.c.id.label("b_id"),
290 a.c.geom.label("a_geom"),
291 b.c.geom.label("b_geom"),
292 func.ST_Intersection(a.c.geom, b.c.geom).label("overlap"),
293 )
294 .select_from(a)
295 .join(b, and_(a.c.id < b.c.id, func.ST_Intersects(a.c.geom, b.c.geom)))
296 .where(a.c.node_type.not_in(broad))
297 .where(b.c.node_type.not_in(broad))
298 .where(a.c.parent_node_id.is_distinct_from(b.c.id))
299 .where(b.c.parent_node_id.is_distinct_from(a.c.id))
300 .cte("pairs")
301 .prefix_with("MATERIALIZED")
302 )
303 rows = session.execute(
304 select(
305 pairs.c.a_id,
306 pairs.c.b_id,
307 _km2(pairs.c.a_geom).label("a_km2"),
308 _km2(pairs.c.b_geom).label("b_km2"),
309 _km2(pairs.c.overlap).label("overlap_km2"),
310 _area_geojson(pairs.c.overlap).label("area_geojson"),
311 )
312 ).all()
313 for row in rows:
314 ca, cb = communities[row.a_id], communities[row.b_id]
315 if ca.id in ancestors[cb.id] or cb.id in ancestors[ca.id] or ca.geom_hash == cb.geom_hash:
316 continue
317 smaller_km2 = min(row.a_km2, row.b_km2)
318 if not smaller_km2: 318 ↛ 319line 318 didn't jump to line 319 because the condition on line 318 was never true
319 continue
320 share = row.overlap_km2 / smaller_km2
321 if share > 0.01 and (share > 0.05 or {ca.type, cb.type} & CITY_TYPES): 321 ↛ 313line 321 didn't jump to line 313 because the condition on line 321 was always true
322 small, big = (ca, cb) if row.a_km2 <= row.b_km2 else (cb, ca)
323 yield Issue(
324 "overlap",
325 small,
326 big,
327 row.overlap_km2,
328 share,
329 details=f"{row.overlap_km2:,.0f} km² of it, or {share:.1%}, overlaps {big.name}.",
330 area_geojson=row.area_geojson,
331 )
334def find_issues(session: Session) -> list[Issue]:
335 communities = load_communities(session)
336 ancestors = {}
337 loops = {}
338 for community_id in communities:
339 path, loop = walk_up(communities, community_id)
340 ancestors[community_id] = set(path[1:])
341 if loop:
342 loops[frozenset(loop)] = loop
344 issues = [
345 *structural_issues(communities, loops.values()),
346 *outside_parent_issues(session, communities),
347 *overlap_issues(session, communities, ancestors),
348 ]
349 return list({issue.key: issue for issue in issues}.values())
352@dataclass(frozen=True)
353class ActiveUsers:
354 total: int
355 outside_localities: int
358def count_active_users(session: Session, now: datetime) -> ActiveUsers:
359 in_a_locality = exists().where(Node.node_type == NodeType.locality, func.ST_Contains(Node.geom, User.geom))
360 row = session.execute(
361 select(func.count().label("total"), func.count().filter(~in_a_locality).label("outside_localities"))
362 .select_from(User)
363 .where(User.last_active > now - ACTIVE_WINDOW)
364 .where(User.deleted_at.is_(None))
365 .where(User.banned_at.is_(None))
366 ).one()
367 return ActiveUsers(total=row.total, outside_localities=row.outside_localities)
370def record(session: Session, issues: Iterable[Issue], active_users: ActiveUsers, now: datetime) -> None:
371 open_rows = {
372 (row.rule, row.node_id, row.other_node_id): row
373 for row in session.execute(select(CommunityIssue).where(CommunityIssue.resolved.is_(None))).scalars()
374 }
375 count = 0
376 for issue in issues:
377 count += 1
378 row = open_rows.pop(issue.key, None)
379 if row is None:
380 row = CommunityIssue(
381 rule=issue.rule,
382 priority=issue.priority,
383 node_id=issue.community.id,
384 other_node_id=issue.other.id if issue.other else None,
385 details=issue.details,
386 first_seen=now,
387 last_seen=now,
388 )
389 session.add(row)
390 row.priority = issue.priority
391 row.area_km2 = issue.area_km2
392 row.share = issue.share
393 row.details = issue.details
394 row.area_geojson = issue.area_geojson
395 row.last_seen = now
396 for row in open_rows.values():
397 row.resolved = now
398 session.add(
399 CommunityCheckRun(
400 open_issues=count,
401 active_users=active_users.total,
402 active_users_outside_localities=active_users.outside_localities,
403 )
404 )
407def run_community_checks(session: Session, now: datetime) -> None:
408 issues = find_issues(session)
409 active_users = count_active_users(session, now)
410 record(session, issues, active_users, now)
411 logger.info(f"Community checks found {len(issues)} issues: {dict(Counter(issue.rule for issue in issues))}")