Coverage for geoparser/gazetteer/build/builder.py: 100%
247 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 18:08 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 18:08 +0000
1"""
2Gazetteer builder: compiles a declarative config into a SQLite artifact.
4The build pipeline has three stages, each its own progress group:
61. Preparing sources: resolve (download/extract, cached across builds) and
7 load each source's file into a transient DuckDB table
82. Compiling features: compile and run one projection per feature block,
9 producing canonical (identifier, source, data, geometry) and
10 (identifier, name) rows, then merge rows that share an identifier
113. Building artifact: copy the compiled rows into a temporary SQLite file,
12 build its search structures and metadata, then atomically move it into
13 place
15The staging database and all intermediate tables are discarded after the
16build; the artifact is the only output.
17"""
19import contextlib
20import os
21import shutil
22import typing as t
23from pathlib import Path
25import duckdb
27from geoparser.gazetteer import artifact
28from geoparser.gazetteer.build.progress import (
29 advance,
30 build_display,
31 item,
32 label_suffixes,
33 print_build_header,
34 print_build_summary,
35 stage,
36 track,
37)
38from geoparser.gazetteer.build.schema import FeatureConfig, GazetteerConfig
39from geoparser.gazetteer.build.stages.acquire import Acquirer
40from geoparser.gazetteer.build.stages.compile import ProjectionCompiler
41from geoparser.gazetteer.build.stages.emit import create_artifact_db, emit, finalize
42from geoparser.gazetteer.build.stages.load import Loader, quote_literal
45def _sqlite_temp_env_names() -> t.Tuple[str, ...]:
46 """
47 Environment variables that steer SQLite's temporary-file location.
49 On Unix, SQLite consults ``SQLITE_TMPDIR`` (then ``TMPDIR``, then
50 ``/tmp``). On Windows it ignores those and uses ``GetTempPath()``, which
51 reads ``TMP`` then ``TEMP``. Returning the platform-appropriate names
52 keeps large FTS/VACUUM spills on the build volume everywhere.
53 """
54 if os.name == "nt":
55 return ("TMP", "TEMP")
56 return ("SQLITE_TMPDIR",)
59def _format_bytes(nbytes: int) -> str:
60 """Format a byte count for error messages (decimal GB/MB)."""
61 if nbytes >= 1_000_000_000:
62 return f"{nbytes / 1_000_000_000:.1f} GB"
63 if nbytes >= 1_000_000:
64 return f"{nbytes / 1_000_000:.1f} MB"
65 return f"{nbytes} bytes"
68@contextlib.contextmanager
69def _sqlite_tmpdir(directory: Path) -> t.Iterator[None]:
70 """
71 Temporarily point SQLite's temporary storage at ``directory``.
73 SQLite has no reliable cross-platform per-connection temp-directory
74 setting, so the location is steered through environment variables (see
75 :func:`_sqlite_temp_env_names`). The previous values are restored when
76 the context exits.
78 Args:
79 directory: Directory SQLite should use for temporary files
80 """
81 directory_str = str(directory)
82 names = _sqlite_temp_env_names()
83 previous = {name: os.environ.get(name) for name in names}
84 try:
85 for name in names:
86 os.environ[name] = directory_str
87 yield
88 finally:
89 for name, value in previous.items():
90 if value is None:
91 os.environ.pop(name, None)
92 else:
93 os.environ[name] = value
96class GazetteerBuilder:
97 """
98 Builds gazetteer artifacts from declarative configuration files.
99 """
101 # Fraction of physical memory the staging engine may use before it starts
102 # spilling intermediate data to disk.
103 _MEMORY_FRACTION = 0.6
104 # Headroom always left for the OS, the Python process and the SQLite
105 # writer, so the whole build never approaches the machine's memory cap.
106 _MEMORY_HEADROOM_MB = 1536
107 # Never bound the staging engine below this, or builds become impractically
108 # slow.
109 _MIN_MEMORY_MB = 512
110 # Used when physical RAM cannot be detected, so the staging engine is
111 # still explicitly bounded instead of sizing itself against unknown RAM.
112 _FALLBACK_MEMORY_MB = 2048
113 # Rough per-thread working-set budget used to cap parallelism so thread
114 # count stays proportional to the memory limit on small machines.
115 _MB_PER_THREAD = 1024
117 def build(
118 self, config_path: t.Union[str, Path], keep_downloads: bool = False
119 ) -> Path:
120 """
121 Build and install a gazetteer from a configuration file.
123 Args:
124 config_path: Path to the YAML configuration file
125 keep_downloads: Whether to keep downloaded files after the build
127 Returns:
128 Path of the installed artifact
129 """
130 config = GazetteerConfig.from_yaml(config_path)
131 print_build_header(config.name)
133 target_path = artifact.artifact_path(config.name)
134 target_path.parent.mkdir(parents=True, exist_ok=True)
135 self._check_disk_space(config, target_path.parent)
137 downloads_dir = target_path.parent / ".downloads" / config.name
138 acquirer = Acquirer(downloads_dir)
139 build_dir = target_path.parent / f".build-{config.name}"
140 if build_dir.exists():
141 shutil.rmtree(build_dir)
142 build_dir.mkdir(parents=True)
144 try:
145 with build_display():
146 connection = duckdb.connect(str(build_dir / "staging.duckdb"))
147 try:
148 self._configure_staging(connection, build_dir)
149 if self._needs_spatial(config):
150 with item("Loading spatial extension", total=100) as bar:
151 self._load_spatial_extension(connection)
152 bar.set_progress(100)
153 self._prepare_sources(acquirer, connection, config)
154 self._compile_features(connection, config)
155 feature_count, name_count = self._build_artifact(
156 connection, config, build_dir, target_path
157 )
158 finally:
159 connection.close()
160 finally:
161 shutil.rmtree(build_dir, ignore_errors=True)
162 if not keep_downloads:
163 acquirer.cleanup()
165 print_build_summary(feature_count, name_count)
166 return target_path
168 def _check_disk_space(self, config: GazetteerConfig, directory: Path) -> None:
169 """
170 Fail early when the gazetteers volume lacks the configured free space.
172 Skipped when ``config.disk`` is unset (unmeasured custom configs).
173 """
174 if config.disk is None:
175 return
176 free = shutil.disk_usage(directory).free
177 if free >= config.disk:
178 return
179 raise OSError(
180 f"Not enough free disk space to install gazetteer '{config.name}': "
181 f"need {_format_bytes(config.disk)}, have {_format_bytes(free)} free "
182 f"on {directory}"
183 )
185 def _configure_staging(
186 self, connection: duckdb.DuckDBPyConnection, build_dir: Path
187 ) -> None:
188 """
189 Bound the staging engine's memory and threads, and make it spill to disk.
191 Large gazetteers (GeoNames is ~13M rows) do not fit in memory. By
192 default DuckDB sizes its memory limit to a large fraction of RAM and
193 only spills relative to that limit, so on memory-constrained machines
194 (or WSL, where the reported RAM is the VM's) the process can be killed
195 by the OS before it decides to spill. Capping the limit with headroom,
196 scaling threads to that budget, and pointing the temporary directory
197 at on-disk build storage keeps peak memory bounded regardless of the
198 machine's specs — including Windows, where physical RAM is detected
199 via the Win32 API rather than ``os.sysconf``.
201 Args:
202 connection: DuckDB connection used for staging and projection
203 build_dir: Directory holding the transient build files
204 """
205 # DuckDB tracks query progress internally only while its progress bar
206 # feature is enabled. By default it also prints that progress straight
207 # to the terminal, outside Rich's control, which would desync the live
208 # build display (stray bars flashing in, stage rows appearing to
209 # repeat); ``enable_progress_bar_print`` keeps the tracking without
210 # the printing, so `connection.query_progress()` (used to drive our
211 # own item bars, see ``Loader`` and ``_compile_features``) works while
212 # the terminal stays under our control. ``progress_bar_time = 0``
213 # makes tracking start immediately rather than after DuckDB's default
214 # delay for what it guesses will be a short query.
215 connection.execute("SET enable_progress_bar = true")
216 connection.execute("SET enable_progress_bar_print = false")
217 connection.execute("SET progress_bar_time = 0")
219 temp_dir = build_dir / "duckdb-temp"
220 temp_dir.mkdir(parents=True, exist_ok=True)
221 connection.execute(
222 f"SET temp_directory = {quote_literal(str(temp_dir))}"
223 )
224 # Ordering is established explicitly where it matters (row ids, emit),
225 # so let DuckDB avoid buffering results just to preserve input order.
226 connection.execute("SET preserve_insertion_order = false")
227 # Always set an explicit memory limit and thread cap. Leaving either
228 # at DuckDB's defaults lets it size itself against reported RAM and
229 # use every core, which on Windows (where RAM detection used to fail)
230 # and on small machines can exhaust memory before spilling kicks in.
231 memory_limit_mb = self._memory_limit_mb()
232 connection.execute(f"SET memory_limit = '{memory_limit_mb}MiB'")
233 connection.execute(f"SET threads = {self._thread_count(memory_limit_mb)}")
235 def _memory_limit_mb(self) -> int:
236 """
237 Return a conservative staging memory limit in MiB.
239 When physical RAM can be detected, the limit is a fraction of that
240 total with headroom left for the OS and the rest of the build. When
241 it cannot, a fixed fallback is used so the staging engine is still
242 explicitly bounded.
243 """
244 total_bytes = self._physical_memory_bytes()
245 if total_bytes is None:
246 return self._FALLBACK_MEMORY_MB
247 total_mb = total_bytes / (1024 * 1024)
248 limit_mb = min(
249 total_mb * self._MEMORY_FRACTION,
250 total_mb - self._MEMORY_HEADROOM_MB,
251 )
252 return int(max(limit_mb, self._MIN_MEMORY_MB))
254 def _thread_count(self, memory_limit_mb: int) -> int:
255 """
256 Return how many DuckDB threads to use for the given memory limit.
258 Caps parallelism by both the CPUs available to this process (honoring
259 cpuset / affinity limits from Docker and similar) and the memory
260 budget so small machines do not run one hungry worker per core.
261 """
262 cpu_count = self._available_cpus()
263 by_memory = max(1, memory_limit_mb // self._MB_PER_THREAD)
264 return max(1, min(cpu_count, by_memory))
266 @staticmethod
267 def _available_cpus() -> int:
268 """Return CPUs usable by this process (affinity-aware when possible)."""
269 try:
270 return len(os.sched_getaffinity(0))
271 except (AttributeError, OSError):
272 return os.cpu_count() or 1
274 @staticmethod
275 def _physical_memory_bytes() -> t.Optional[int]:
276 """
277 Return usable physical memory in bytes, if detectable.
279 Prefers a cgroup memory limit when one is set (Docker, systemd
280 scopes, ...), since ``os.sysconf`` reports host RAM and would
281 otherwise let the staging engine size itself above the container
282 budget and get OOM-killed.
283 """
284 candidates: t.List[int] = []
285 for reader in (
286 GazetteerBuilder._physical_memory_bytes_cgroup,
287 GazetteerBuilder._physical_memory_bytes_sysconf,
288 GazetteerBuilder._physical_memory_bytes_windows,
289 ):
290 try:
291 value = reader()
292 except (ValueError, OSError, AttributeError):
293 continue
294 if value is not None and value > 0:
295 candidates.append(value)
296 if not candidates:
297 return None
298 return min(candidates)
300 @staticmethod
301 def _physical_memory_bytes_cgroup() -> t.Optional[int]:
302 """Read this process's cgroup v2 ``memory.max`` limit, if finite."""
303 with open("/proc/self/cgroup", encoding="utf-8") as handle:
304 lines = handle.read().splitlines()
305 relative = None
306 for line in lines:
307 # Unified hierarchy: ``0::/docker/<id>`` (or similar).
308 if line.startswith("0::"):
309 relative = line[3:]
310 break
311 if relative is None:
312 return None
313 # Walk from the process cgroup up to the root; Docker often sets
314 # ``memory.max`` on the container cgroup while parents stay ``max``.
315 directory = Path("/sys/fs/cgroup") / relative.lstrip("/")
316 root = Path("/sys/fs/cgroup")
317 while True:
318 limit_path = directory / "memory.max"
319 if limit_path.is_file():
320 text = limit_path.read_text(encoding="utf-8").strip()
321 if text != "max":
322 return int(text)
323 if directory == root or directory.parent == directory:
324 return None
325 directory = directory.parent
327 @staticmethod
328 def _physical_memory_bytes_sysconf() -> t.Optional[int]:
329 """Read physical memory via ``os.sysconf`` (Linux, macOS, ...)."""
330 return os.sysconf("SC_PHYS_PAGES") * os.sysconf("SC_PAGE_SIZE")
332 @staticmethod
333 def _physical_memory_bytes_windows() -> t.Optional[int]:
334 """Read physical memory via ``GlobalMemoryStatusEx`` (Windows)."""
335 import ctypes
336 import ctypes.wintypes
338 class MEMORYSTATUSEX(ctypes.Structure):
339 _fields_ = [
340 ("dwLength", ctypes.wintypes.DWORD),
341 ("dwMemoryLoad", ctypes.wintypes.DWORD),
342 ("ullTotalPhys", ctypes.c_uint64),
343 ("ullAvailPhys", ctypes.c_uint64),
344 ("ullTotalPageFile", ctypes.c_uint64),
345 ("ullAvailPageFile", ctypes.c_uint64),
346 ("ullTotalVirtual", ctypes.c_uint64),
347 ("ullAvailVirtual", ctypes.c_uint64),
348 ("ullAvailExtendedVirtual", ctypes.c_uint64),
349 ]
351 status = MEMORYSTATUSEX()
352 status.dwLength = ctypes.sizeof(status)
353 if not ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)):
354 return None
355 return int(status.ullTotalPhys)
357 def _needs_spatial(self, config: GazetteerConfig) -> bool:
358 """Whether the build requires DuckDB's spatial extension."""
359 if any(not source_config.is_tabular for source_config in config.sources):
360 return True
361 return any(feature.geometry is not None for feature in config.features)
363 def _load_spatial_extension(self, connection: duckdb.DuckDBPyConnection) -> None:
364 """Install and load the DuckDB spatial extension."""
365 try:
366 connection.install_extension("spatial")
367 connection.load_extension("spatial")
368 except duckdb.Error as error:
369 raise RuntimeError(
370 "Failed to load the DuckDB spatial extension, which is required "
371 "to build gazetteers with geometries. The extension is downloaded "
372 "on first use; make sure you have network access, then try again. "
373 f"Original error: {error}"
374 ) from error
376 def _prepare_sources(
377 self,
378 acquirer: Acquirer,
379 connection: duckdb.DuckDBPyConnection,
380 config: GazetteerConfig,
381 ) -> None:
382 """
383 Resolve, then load, each source's data file in turn.
385 Acquiring (see :mod:`stages.acquire`) and loading (see :mod:`stages.load`) each
386 report their own items as they run their actual downloads,
387 extractions and queries, and advance the stage themselves as each
388 one finishes; how many a given source shows depends on whether it
389 needed downloading/extracting and whether it is spatial, so the
390 estimate below undercounts some sources and overcounts others, but
391 the stage's total grows on the fly to stay ahead of it either way.
392 """
393 loader = Loader(connection, config.crs)
394 total_estimate = sum(
395 1 + (1 if source_config.is_tabular else 2)
396 for source_config in config.sources
397 )
398 with stage("Preparing sources", "Prepared sources", total_estimate):
399 for source_config in config.sources:
400 file_path = acquirer.acquire(source_config)
401 loader.load(source_config, file_path)
403 def _compile_features(
404 self, connection: duckdb.DuckDBPyConnection, config: GazetteerConfig
405 ) -> None:
406 """Run each feature block's projection, then merge across blocks."""
407 # Every source declares its attributes, so the catalog is built
408 # directly from the config; the staged tables carry exactly this schema.
409 catalog = {
410 source_config.name: [
411 attribute.name for attribute in source_config.attributes
412 ]
413 for source_config in config.sources
414 }
415 compiler = ProjectionCompiler(config, catalog)
417 connection.execute(
418 "CREATE TABLE _features (identifier VARCHAR, source VARCHAR, "
419 "data VARCHAR, geometry BLOB)"
420 )
421 connection.execute("CREATE TABLE _names (identifier VARCHAR, text VARCHAR)")
423 # Each feature block shows one item for assembling its features, one
424 # per name it collects, and (only if it has a geometry) one for
425 # checking whether any identifier repeats; the stage's total grows on
426 # the fly to cover the further "merging duplicates" item that shows
427 # up only when duplicates are actually found.
428 total_estimate = 3
429 for feature in config.features:
430 total_estimate += 1 + len(compiler.name_queries(feature))
431 if compiler.duplicate_geometry_query(feature) is not None:
432 total_estimate += 1
434 with stage("Compiling features", "Compiled features", total_estimate):
435 for feature in config.features:
436 self._compile_feature(connection, compiler, feature)
438 # Merging rows across feature blocks (the checks and joins below)
439 # means scanning the whole of _features and _names, which for a
440 # large gazetteer is not instantaneous; each gets its own item
441 # rather than leaving a silent gap after the last feature block.
442 with item("Checking identifiers", total=100) as bar:
443 track(
444 bar,
445 connection.query_progress,
446 lambda: self._check_duplicate_identifiers(connection),
447 )
448 advance()
450 # Deterministic internal ids; names of unknown identifiers (e.g.
451 # from a related names input covering more places) are dropped by
452 # the join below.
453 with item("Assigning feature ids", total=100) as bar:
454 track(
455 bar,
456 connection.query_progress,
457 lambda: connection.execute(
458 "CREATE TABLE _features_final AS "
459 "SELECT row_number() OVER (ORDER BY identifier) AS id, "
460 "* FROM _features"
461 ),
462 )
463 advance()
465 with item("Linking names", total=100) as bar:
466 track(
467 bar,
468 connection.query_progress,
469 lambda: connection.execute(
470 "CREATE TABLE _names_final AS "
471 "SELECT DISTINCT f.id AS feature_id, n.text "
472 "FROM _names n JOIN _features_final f USING (identifier)"
473 ),
474 )
475 advance()
477 total = connection.execute("SELECT count(*) FROM _features_final").fetchone()[0]
478 if total == 0:
479 raise ValueError(
480 "The build produced no features; check the configuration's "
481 "'features' blocks and input files"
482 )
484 def _compile_feature(
485 self,
486 connection: duckdb.DuckDBPyConnection,
487 compiler: ProjectionCompiler,
488 feature: FeatureConfig,
489 ) -> None:
490 """
491 Run one feature block's queries, each reported as its own item.
493 Each item advances the active stage as soon as it finishes, rather
494 than only once every query for this feature block has run.
495 """
496 with item(f"Assembling features from {feature.source}", total=100) as bar:
497 track(
498 bar,
499 connection.query_progress,
500 lambda: connection.execute(
501 f"INSERT INTO _features {compiler.feature_query(feature)}"
502 ),
503 )
504 advance()
505 name_queries = compiler.name_queries(feature)
506 # A feature block commonly collects several names (a primary name,
507 # alternate names, ...), all from the same source, so this loop is
508 # the most common source of identical-looking, back-to-back items;
509 # number them whenever there is more than one, so a repeat reads as
510 # a distinct new item rather than the previous one's bar restarting.
511 name_suffixes = label_suffixes(
512 [f"Collecting names from {feature.source}"] * len(name_queries)
513 )
514 for name_query, name_suffix in zip(name_queries, name_suffixes):
515 with item(
516 f"Collecting names from {feature.source}{name_suffix}", total=100
517 ) as bar:
518 track(
519 bar,
520 connection.query_progress,
521 lambda nq=name_query: connection.execute(
522 f"INSERT INTO _names {nq}"
523 ),
524 )
525 advance()
526 self._merge_duplicate_geometries(connection, compiler, feature)
528 def _merge_duplicate_geometries(
529 self,
530 connection: duckdb.DuckDBPyConnection,
531 compiler: ProjectionCompiler,
532 feature: FeatureConfig,
533 ) -> None:
534 """
535 Union the geometries of identifiers that repeat within a source.
537 The feature query keeps only the first row's geometry (a bounded
538 aggregate); here we recompute the union for the few genuinely
539 duplicated identifiers and patch those rows. Doing this only for
540 duplicates keeps ``ST_Union_Agg``'s unmanaged memory bounded, so the
541 build stays within limits even for very large sources.
542 """
543 query = compiler.duplicate_geometry_query(feature)
544 if query is None:
545 return
546 with item(f"Checking duplicates in {feature.source}", total=100) as bar:
547 track(
548 bar,
549 connection.query_progress,
550 lambda: connection.execute(
551 f"CREATE OR REPLACE TEMP TABLE _dup_geometry AS {query}"
552 ),
553 )
554 advance()
555 try:
556 has_duplicates = connection.execute(
557 "SELECT count(*) FROM _dup_geometry"
558 ).fetchone()[0]
559 if has_duplicates:
560 with item(
561 f"Merging duplicates in {feature.source}", total=100
562 ) as bar:
563 track(
564 bar,
565 connection.query_progress,
566 lambda: connection.execute(
567 "UPDATE _features SET geometry = ("
568 "SELECT geometry FROM _dup_geometry d "
569 "WHERE d.identifier = _features.identifier"
570 ") WHERE identifier IN "
571 "(SELECT identifier FROM _dup_geometry)"
572 ),
573 )
574 advance()
575 finally:
576 connection.execute("DROP TABLE IF EXISTS _dup_geometry")
578 def _check_duplicate_identifiers(
579 self, connection: duckdb.DuckDBPyConnection
580 ) -> None:
581 """Fail the build when an identifier appears in multiple feature blocks."""
582 duplicates = connection.execute(
583 "SELECT identifier, string_agg(DISTINCT source, ', ') "
584 "FROM _features GROUP BY identifier HAVING count(*) > 1 LIMIT 5"
585 ).fetchall()
586 if duplicates:
587 examples = "; ".join(
588 f"'{identifier}' (sources: {sources})"
589 for identifier, sources in duplicates
590 )
591 raise ValueError(
592 "Identifiers must be unique across the whole gazetteer, but the "
593 f"following appear in multiple feature blocks: {examples}. "
594 "Merge the blocks or disambiguate the identifiers with an "
595 "expression (e.g. a source prefix)."
596 )
598 def _build_artifact(
599 self,
600 connection: duckdb.DuckDBPyConnection,
601 config: GazetteerConfig,
602 build_dir: Path,
603 target_path: Path,
604 ) -> t.Tuple[int, int]:
605 """Write the artifact file and atomically move it into place."""
606 temporary_path = build_dir / target_path.name
607 # Keep SQLite's temporary files (FTS rebuild, index sorts, VACUUM) on
608 # the build volume rather than the default location, which on some
609 # systems is a RAM-backed tmpfs (e.g. WSL's /tmp) or a small system
610 # drive (Windows %TEMP%) and would defeat the point of spilling to
611 # disk. See ``_sqlite_tmpdir`` for the platform-specific env vars.
612 sqlite_temp_dir = build_dir / "sqlite-temp"
613 sqlite_temp_dir.mkdir(parents=True, exist_ok=True)
614 with _sqlite_tmpdir(sqlite_temp_dir):
615 sqlite_connection = create_artifact_db(temporary_path)
616 try:
617 with stage("Building artifact", "Built artifact", 6):
618 feature_count, name_count = emit(connection, sqlite_connection)
619 finalize(sqlite_connection, config, feature_count, name_count)
620 finally:
621 sqlite_connection.close()
622 os.replace(temporary_path, target_path)
623 return feature_count, name_count
626def uninstall(gazetteer_name: str) -> bool:
627 """
628 Remove an installed gazetteer artifact.
630 Args:
631 gazetteer_name: Name of the gazetteer to remove
633 Returns:
634 True if an artifact was removed, False if none was installed
635 """
636 path = artifact.artifact_path(gazetteer_name)
637 if path.exists():
638 path.unlink()
639 return True
640 return False