wrolpi/modules/zim/libzim_worker.py

113 lines
4.4 KiB
Python
Raw Normal View History

Zim estimates and searches run in a libzim worker process so a cold Zim cannot stall the API worker (#928) * Zim search estimates run in a separate process so a cold estimate cannot stall the API worker The global search estimates every auto-search Zim on each keystroke. On a large library that estimate took tens of seconds when the Zims' pages were not cached, and every other request routed to the same Sanic worker, such as the channel suggestions, waited behind it. Two things held the worker: opening a large Zim cold takes seconds (ten for a 75 GB Zim) and `Zims.get_all` did that on the event loop; and python-libzim never releases the GIL, so the estimate offloaded with asyncio.to_thread still froze the worker. Everything libzim does for an estimate now runs in a standalone script started as a subprocess (Sanic workers are daemonic, so a multiprocessing pool cannot be forked from them). It reads the Zim paths and search string on stdin and writes the counts on stdout. A Zim it cannot read is reported and left out, as `Zims.get_all` would leave it out. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * Zim searches run in the libzim worker process too The /api/zim/search endpoints had the same stall as the estimate: they opened every Zim through Zims.get_all and searched them with libzim, which holds the GIL, so a thread offload still froze the Sanic worker. The estimate script is now a general libzim worker with estimate, search and entries jobs. A search of all Zims sends every Zim's job to one worker process; the API worker only headlines the returned HTML and looks up tags. The worker also returns each Zim's metadata so Zim.__json__ does not open the Zim again on the event loop. Zim.entries_with_tags is split so the tagged paths come from the database without opening the Zim. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * Tagged Zim estimates count from the database, and a cancelled request kills the libzim worker Review of the earlier commits found two gaps. Estimates with tags selected still went through Zims.entries_with_tags, which opened every Zim in the API process, and after the thread offload was removed it did so on the event loop; they now count the tagged paths in SQL and ask the worker only for metadata. And Sanic cancels a handler at its response timeout or on disconnect, which left the worker process running until its stdout pipe filled; the runner now kills and reaps it on cancellation. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-01 13:02:26 -07:00
#!/usr/bin/env python3
"""Run libzim jobs (estimate, search, fetch entries) for the API.
Run by `modules.zim.lib.run_libzim_jobs` as a separate process: python-libzim never releases the GIL, and merely
opening a large Zim whose pages are not cached takes seconds (ten for a 75 GB Zim), so doing this in the API
worker would freeze every other request that worker is handling.
Reads `{"jobs": [...]}` from stdin and writes one result per job, in order, to stdout. Every job names the Zim
`path` and an `op`:
{"op": "estimate", "search_str": ...} -> {"estimate": int}
{"op": "search", "search_str": ..., "offset": ..., "limit": ...}
-> {"estimate": int, "entries": [{"path", "title", "content"}]}
{"op": "entries", "paths": [...]} -> {"entries": [{"path", "title", "content"}]}
iNaturalist species map (#1033) * Add iNaturalist species pack build script Builds one `inat-<region>-<version>.species.db` per map region from the iNaturalist research-grade GBIF export (CC BY-NC 4.0). Each species row links to its English Wikipedia article (via Wikidata) so Kiwix supplies the details, and carries its range as compressed per-cell dots (0.1° from all observations, 0.02° from precise ones only). A cell lookup table answers "what lives near here", and FTS5 searches names. Packs, meta4 files and a signed manifest are written for upload to the CDN. modules/map/species.py holds the pack format shared with WROLPi. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Download iNaturalist species packs by subscription A species subscription is one recurring (30 day) `species_catalog` Download of the signed species manifest, saved in the downloads config like map subscriptions. Each run creates a `species_pack` Download per subscribed region, which aria2c checks against the manifest's signed hash before the pack is moved into map/inat/; only then are the region's older packs deleted. The map's Manage tab gets a Species section: subscribe, unsubscribe (the pack is kept), and delete a downloaded pack. Pack file names are built and parsed in modules/map/species.py, shared with the build script. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Search the downloaded species packs, with their range and Wikipedia article - GET /api/map/species: search by name (every word a prefix), and/or what was seen within radius_km of lat/lon. Nearby species come first, most seen nearby first; an exact name match comes first of all. - GET /api/map/species/<taxon_id>: details, and the species' article in the best English Wikipedia Zim (maxi, nopic, mini; newest), found by the libzim worker's new `find` op, else a search link for its name. - GET /api/map/species/<taxon_id>/range?grid=low|high: GeoJSON dots. Packs are read directly and read-only; a species in several regions is merged (counts summed, bbox and range unioned). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Use iNaturalist's common names in the species packs Wikidata's P1843 holds many English names per species and the one we got was arbitrary ("black-tailed deer" for mule deer, "Greek milkweed" for showy milkweed). The build now reads iNaturalist's taxonomy archive (VernacularNames-english.csv) and takes each species' first name not tied to a place ("quaking aspen", not Canada's "trembling aspen"), else its first name; Wikidata's is only a fallback. In us-west this names 30,642 of 52,015 species, up from 17,805. --version publishes a rebuild of the same observations under a new version, and --reuse-split rebuilds from the last build's region work files instead of reading the observations again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species panel on the map: what lives here, and a species' range as dots A 🌿 button opens the Species panel (it and nuclear mode share the panel's place, so one closes the other). It lists the species seen within 10/30/100 km of the middle of the map, following the map as it moves, with how often each was seen nearby; it can search by name and filter by group. Choosing a species draws its range: the 0.1° grid of every observation below zoom 7, the 0.02° grid of precise ones from it (or the 0.1° grid at every zoom when there is none), put back after a style change and erased on Back or close. "Zoom to range" fits its bbox, and its Wikipedia article opens from the best Wikipedia Zim (or a search, or where to download Wikipedia). The panel is at most half the screen tall and clears the map's buttons, so the range stays in sight on a phone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species tests: neutral Oregon fixtures Bend, Prineville (~47 km apart) and Crater Lake replace the earlier fixture points; the cases are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species: zoom to a range without its outliers, beside the panel "Zoom to range" fitted the species' bbox, so a few planted trees far away (giant sequoias in Seattle and Los Angeles) zoomed the map out to the whole coast, and the panel covered part of the range. It now fits the range's dots less the outermost 2% on each side (from 20 dots), and pads by the panel: beside it on a wide map, above it on a narrow one. The outlying dots are still drawn. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Help: the Species page Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species: months seen, a popup on each dot, and review fixes Months: packs now keep how many observations each species had in each month, and the months it was seen in each ~11 km square (a bit per month). The species details show a bar per month; clicking a range dot opens a popup of that square: how often the species was seen there and in which months, and the other species seen there, any of which can be opened (GET /api/map/species/here). Packs without months still work. Review fixes: - Common names: the archive's first listed English name, not the first without a place (which was an alias: "Robin Redbreast", "Wanderer", "Duck Hawk"); every other English name is kept in `other_names` and is searchable, and shown as "Also called". - Only the newest pack of each region is read, so a version left beside a newer one is not counted twice; a finished download also removes older versions. A name one pack lacks is taken from another. - No bbox for a species whose packs are on both sides of the antimeridian; Zoom to range takes the short way across it, drops at least one outlier on each side from 20 dots, waits for the dots, and measures the panel against the map. - Wikipedia Zims are tried one at a time, best first, all of Wikipedia before a selection of it. - A failed search keeps the last list and says so; failed details no longer suggest downloading Wikipedia, and the range is still drawn. - Species range dots are left out of PDF exports. - Unsubscribe (species and map regions) is red again; the Manage table refreshes until a subscribed pack arrives; a refused Delete fails. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species: less work for the WROLPi per search and range Measured on a Pi 4 with the us-west pack, the panel's search (species within 30 km, asked each time the map stops moving) took 146 ms, and a wide species' fine range 280 ms and 2.7 MB of GeoJSON. - Search ranks the matching species from bare (taxon, names, counts) tuples and reads only the species it returns in full: 30 km 87 ms, 100 km 445 -> 277 ms, a broad name prefix 480 -> 200 ms. - The range is sent as its sorted cells, as differences, and the browser makes the dots: the red-tailed hawk's fine range 34 ms and 95 KB, its coarse range 87 -> 10 ms and 939 -> 29 KB. A dot's popup asks for the species clicked, and always shows how often and in which months it was seen in that square, not only when it is among the most seen there. The popup is drawn over the Species panel. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species: a planet pack, every region in one file `--planet` merges every region's pack into `inat-planet-<version>` (counts and months summed, ranges, bboxes and lookup cells joined, the first name a pack has), and adds it to the manifest; `--merge-only` makes it from the region packs of a finished build. An observation exactly on a shared region edge is in both regions' packs, so the planet counts it twice; that is rare enough to leave. On the device the planet is a choice in the Species catalog, and when its pack is downloaded it is the only one read, so the regions it holds are not counted again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species: sizes of the 20261129 packs; no hang re-signing a manifest The packs grew about 15% with months and other names; the planet pack is 993 MB. Re-signing a manifest (--planet --merge-only) hung: gpg asks before replacing an existing signature and nothing could answer. The old signature is now removed first. Help: a dot's popup, months, other names, and the planet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species: the planet from each observation once; overlaps counted once Map regions overlap, some widely (southern Arizona is in us-west and mexico, north Africa in five regions): about 42M of 173M observations are in two or more. Merging the region packs counted those twice, so the planet is now built like a region from every observation once. Its work is split into 8 files by species and built a file at a time (all at once its sets would need ~25 GB). `planet` is a region for --regions, built by default, and the manifest lists every pack of the version in the folder, so a planet-only run keeps the regions. The merge and its flags are gone. On a device with overlapping region packs, a square both hold was counted twice in "near" and in a dot's popup; each square now counts the larger of the packs' counts. Species totals still add up across overlapping packs; the planet pack is exact. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Help: Species screenshots from the planet pack Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species: Zoom to range fits the cluster of dots nearest the view On the planet pack, giant sequoia (planted in Britain, New Zealand and elsewhere) zoomed out to the whole world: far more than the 2% of dots the zoom left out were planted away from its groves. Dots in touching 2° squares (about 220 km, also across the antimeridian) are now one cluster, and Zoom to range fits the cluster nearest the middle of the map: California from Yosemite, the planted trees from London. A range spread across a continent is one cluster. Help updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species: Planet is listed first on the Manage tab Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 19:24:01 -07:00
{"op": "find", "paths": [...]} -> {"found": path or None, "title": str or None}
Zim estimates and searches run in a libzim worker process so a cold Zim cannot stall the API worker (#928) * Zim search estimates run in a separate process so a cold estimate cannot stall the API worker The global search estimates every auto-search Zim on each keystroke. On a large library that estimate took tens of seconds when the Zims' pages were not cached, and every other request routed to the same Sanic worker, such as the channel suggestions, waited behind it. Two things held the worker: opening a large Zim cold takes seconds (ten for a 75 GB Zim) and `Zims.get_all` did that on the event loop; and python-libzim never releases the GIL, so the estimate offloaded with asyncio.to_thread still froze the worker. Everything libzim does for an estimate now runs in a standalone script started as a subprocess (Sanic workers are daemonic, so a multiprocessing pool cannot be forked from them). It reads the Zim paths and search string on stdin and writes the counts on stdout. A Zim it cannot read is reported and left out, as `Zims.get_all` would leave it out. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * Zim searches run in the libzim worker process too The /api/zim/search endpoints had the same stall as the estimate: they opened every Zim through Zims.get_all and searched them with libzim, which holds the GIL, so a thread offload still froze the Sanic worker. The estimate script is now a general libzim worker with estimate, search and entries jobs. A search of all Zims sends every Zim's job to one worker process; the API worker only headlines the returned HTML and looks up tags. The worker also returns each Zim's metadata so Zim.__json__ does not open the Zim again on the event loop. Zim.entries_with_tags is split so the tagged paths come from the database without opening the Zim. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * Tagged Zim estimates count from the database, and a cancelled request kills the libzim worker Review of the earlier commits found two gaps. Estimates with tags selected still went through Zims.entries_with_tags, which opened every Zim in the API process, and after the thread offload was removed it did so on the event loop; they now count the tagged paths in SQL and ask the worker only for metadata. And Sanic cancels a handler at its response timeout or on disconnect, which left the worker process running until its stdout pipe filled; the runner now kills and reaps it on cancellation. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-01 13:02:26 -07:00
{"op": "metadata"} -> {} (with the metadata below)
Any job may add `"metadata": true` to also get the Zim's metadata. A job that fails returns `{"error": str}`
so one bad Zim does not hide the rest. Imports only the standard library and libzim; it is run with
`python -I` from any working directory.
"""
import json
import sys
from libzim.reader import Archive
from libzim.search import Query, Searcher
from libzim.suggestion import SuggestionSearcher
METADATA_KEYS = ('Date', 'Creator', 'Description', 'Name', 'Publisher', 'Tags', 'Title')
def get_metadata(archive: Archive) -> dict:
metadata = dict()
for key in METADATA_KEYS:
try:
metadata[key.lower()] = archive.get_metadata(key).decode()
except RuntimeError:
metadata[key.lower()] = None
return metadata
def unique_paths(*paths: str) -> list:
"""The first of any paths that differ only in case, dashes, underscores or slashes (disambiguation or
redirect entries)."""
seen, unique = set(), list()
for path in paths:
key = path.replace('-', '').replace('_', '').replace('/', '').lower()
if key not in seen:
seen.add(key)
unique.append(path)
return unique
def entry_dict(archive: Archive, path: str) -> dict:
entry = archive.get_entry_by_path(path)
return dict(path=entry.path, title=entry.title, content=bytes(entry.get_item().content).decode('UTF-8'))
def run_job(job: dict) -> dict:
archive = Archive(job['path'])
op = job['op']
result = dict()
if op == 'estimate':
query = Query().set_query(job['search_str'])
result['estimate'] = Searcher(archive).search(query).getEstimatedMatches()
elif op == 'search':
search_str, offset, limit = job['search_str'], job['offset'], job['limit']
query = Query().set_query(search_str)
# Suggestions search the titles.
suggested = list(SuggestionSearcher(archive).suggest(search_str).getResults(offset, limit))
search = Searcher(archive).search(query)
found = list(search.getResults(offset, limit))
paths = unique_paths(*suggested, *found)[:limit]
result['estimate'] = search.getEstimatedMatches()
result['entries'] = [entry_dict(archive, i) for i in paths]
elif op == 'entries':
result['entries'] = [entry_dict(archive, i) for i in job['paths']]
iNaturalist species map (#1033) * Add iNaturalist species pack build script Builds one `inat-<region>-<version>.species.db` per map region from the iNaturalist research-grade GBIF export (CC BY-NC 4.0). Each species row links to its English Wikipedia article (via Wikidata) so Kiwix supplies the details, and carries its range as compressed per-cell dots (0.1° from all observations, 0.02° from precise ones only). A cell lookup table answers "what lives near here", and FTS5 searches names. Packs, meta4 files and a signed manifest are written for upload to the CDN. modules/map/species.py holds the pack format shared with WROLPi. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Download iNaturalist species packs by subscription A species subscription is one recurring (30 day) `species_catalog` Download of the signed species manifest, saved in the downloads config like map subscriptions. Each run creates a `species_pack` Download per subscribed region, which aria2c checks against the manifest's signed hash before the pack is moved into map/inat/; only then are the region's older packs deleted. The map's Manage tab gets a Species section: subscribe, unsubscribe (the pack is kept), and delete a downloaded pack. Pack file names are built and parsed in modules/map/species.py, shared with the build script. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Search the downloaded species packs, with their range and Wikipedia article - GET /api/map/species: search by name (every word a prefix), and/or what was seen within radius_km of lat/lon. Nearby species come first, most seen nearby first; an exact name match comes first of all. - GET /api/map/species/<taxon_id>: details, and the species' article in the best English Wikipedia Zim (maxi, nopic, mini; newest), found by the libzim worker's new `find` op, else a search link for its name. - GET /api/map/species/<taxon_id>/range?grid=low|high: GeoJSON dots. Packs are read directly and read-only; a species in several regions is merged (counts summed, bbox and range unioned). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Use iNaturalist's common names in the species packs Wikidata's P1843 holds many English names per species and the one we got was arbitrary ("black-tailed deer" for mule deer, "Greek milkweed" for showy milkweed). The build now reads iNaturalist's taxonomy archive (VernacularNames-english.csv) and takes each species' first name not tied to a place ("quaking aspen", not Canada's "trembling aspen"), else its first name; Wikidata's is only a fallback. In us-west this names 30,642 of 52,015 species, up from 17,805. --version publishes a rebuild of the same observations under a new version, and --reuse-split rebuilds from the last build's region work files instead of reading the observations again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species panel on the map: what lives here, and a species' range as dots A 🌿 button opens the Species panel (it and nuclear mode share the panel's place, so one closes the other). It lists the species seen within 10/30/100 km of the middle of the map, following the map as it moves, with how often each was seen nearby; it can search by name and filter by group. Choosing a species draws its range: the 0.1° grid of every observation below zoom 7, the 0.02° grid of precise ones from it (or the 0.1° grid at every zoom when there is none), put back after a style change and erased on Back or close. "Zoom to range" fits its bbox, and its Wikipedia article opens from the best Wikipedia Zim (or a search, or where to download Wikipedia). The panel is at most half the screen tall and clears the map's buttons, so the range stays in sight on a phone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species tests: neutral Oregon fixtures Bend, Prineville (~47 km apart) and Crater Lake replace the earlier fixture points; the cases are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species: zoom to a range without its outliers, beside the panel "Zoom to range" fitted the species' bbox, so a few planted trees far away (giant sequoias in Seattle and Los Angeles) zoomed the map out to the whole coast, and the panel covered part of the range. It now fits the range's dots less the outermost 2% on each side (from 20 dots), and pads by the panel: beside it on a wide map, above it on a narrow one. The outlying dots are still drawn. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Help: the Species page Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species: months seen, a popup on each dot, and review fixes Months: packs now keep how many observations each species had in each month, and the months it was seen in each ~11 km square (a bit per month). The species details show a bar per month; clicking a range dot opens a popup of that square: how often the species was seen there and in which months, and the other species seen there, any of which can be opened (GET /api/map/species/here). Packs without months still work. Review fixes: - Common names: the archive's first listed English name, not the first without a place (which was an alias: "Robin Redbreast", "Wanderer", "Duck Hawk"); every other English name is kept in `other_names` and is searchable, and shown as "Also called". - Only the newest pack of each region is read, so a version left beside a newer one is not counted twice; a finished download also removes older versions. A name one pack lacks is taken from another. - No bbox for a species whose packs are on both sides of the antimeridian; Zoom to range takes the short way across it, drops at least one outlier on each side from 20 dots, waits for the dots, and measures the panel against the map. - Wikipedia Zims are tried one at a time, best first, all of Wikipedia before a selection of it. - A failed search keeps the last list and says so; failed details no longer suggest downloading Wikipedia, and the range is still drawn. - Species range dots are left out of PDF exports. - Unsubscribe (species and map regions) is red again; the Manage table refreshes until a subscribed pack arrives; a refused Delete fails. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species: less work for the WROLPi per search and range Measured on a Pi 4 with the us-west pack, the panel's search (species within 30 km, asked each time the map stops moving) took 146 ms, and a wide species' fine range 280 ms and 2.7 MB of GeoJSON. - Search ranks the matching species from bare (taxon, names, counts) tuples and reads only the species it returns in full: 30 km 87 ms, 100 km 445 -> 277 ms, a broad name prefix 480 -> 200 ms. - The range is sent as its sorted cells, as differences, and the browser makes the dots: the red-tailed hawk's fine range 34 ms and 95 KB, its coarse range 87 -> 10 ms and 939 -> 29 KB. A dot's popup asks for the species clicked, and always shows how often and in which months it was seen in that square, not only when it is among the most seen there. The popup is drawn over the Species panel. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species: a planet pack, every region in one file `--planet` merges every region's pack into `inat-planet-<version>` (counts and months summed, ranges, bboxes and lookup cells joined, the first name a pack has), and adds it to the manifest; `--merge-only` makes it from the region packs of a finished build. An observation exactly on a shared region edge is in both regions' packs, so the planet counts it twice; that is rare enough to leave. On the device the planet is a choice in the Species catalog, and when its pack is downloaded it is the only one read, so the regions it holds are not counted again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species: sizes of the 20261129 packs; no hang re-signing a manifest The packs grew about 15% with months and other names; the planet pack is 993 MB. Re-signing a manifest (--planet --merge-only) hung: gpg asks before replacing an existing signature and nothing could answer. The old signature is now removed first. Help: a dot's popup, months, other names, and the planet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species: the planet from each observation once; overlaps counted once Map regions overlap, some widely (southern Arizona is in us-west and mexico, north Africa in five regions): about 42M of 173M observations are in two or more. Merging the region packs counted those twice, so the planet is now built like a region from every observation once. Its work is split into 8 files by species and built a file at a time (all at once its sets would need ~25 GB). `planet` is a region for --regions, built by default, and the manifest lists every pack of the version in the folder, so a planet-only run keeps the regions. The merge and its flags are gone. On a device with overlapping region packs, a square both hold was counted twice in "near" and in a dot's popup; each square now counts the larger of the packs' counts. Species totals still add up across overlapping packs; the planet pack is exact. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Help: Species screenshots from the planet pack Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species: Zoom to range fits the cluster of dots nearest the view On the planet pack, giant sequoia (planted in Britain, New Zealand and elsewhere) zoomed out to the whole world: far more than the 2% of dots the zoom left out were planted away from its groves. Dots in touching 2° squares (about 220 km, also across the antimeridian) are now one cluster, and Zoom to range fits the cluster nearest the middle of the map: California from Yosemite, the planted trees from London. A range spread across a continent is one cluster. Help updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Species: Planet is listed first on the Manage tab Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 19:24:01 -07:00
elif op == 'find':
# The first of `paths` that is an entry, following a redirect.
result['found'] = result['title'] = None
for path in job['paths']:
try:
entry = archive.get_entry_by_path(path)
except KeyError:
continue
if entry.is_redirect:
entry = entry.get_redirect_entry()
result['found'], result['title'] = entry.path, entry.title
break
Zim estimates and searches run in a libzim worker process so a cold Zim cannot stall the API worker (#928) * Zim search estimates run in a separate process so a cold estimate cannot stall the API worker The global search estimates every auto-search Zim on each keystroke. On a large library that estimate took tens of seconds when the Zims' pages were not cached, and every other request routed to the same Sanic worker, such as the channel suggestions, waited behind it. Two things held the worker: opening a large Zim cold takes seconds (ten for a 75 GB Zim) and `Zims.get_all` did that on the event loop; and python-libzim never releases the GIL, so the estimate offloaded with asyncio.to_thread still froze the worker. Everything libzim does for an estimate now runs in a standalone script started as a subprocess (Sanic workers are daemonic, so a multiprocessing pool cannot be forked from them). It reads the Zim paths and search string on stdin and writes the counts on stdout. A Zim it cannot read is reported and left out, as `Zims.get_all` would leave it out. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * Zim searches run in the libzim worker process too The /api/zim/search endpoints had the same stall as the estimate: they opened every Zim through Zims.get_all and searched them with libzim, which holds the GIL, so a thread offload still froze the Sanic worker. The estimate script is now a general libzim worker with estimate, search and entries jobs. A search of all Zims sends every Zim's job to one worker process; the API worker only headlines the returned HTML and looks up tags. The worker also returns each Zim's metadata so Zim.__json__ does not open the Zim again on the event loop. Zim.entries_with_tags is split so the tagged paths come from the database without opening the Zim. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * Tagged Zim estimates count from the database, and a cancelled request kills the libzim worker Review of the earlier commits found two gaps. Estimates with tags selected still went through Zims.entries_with_tags, which opened every Zim in the API process, and after the thread offload was removed it did so on the event loop; they now count the tagged paths in SQL and ask the worker only for metadata. And Sanic cancels a handler at its response timeout or on disconnect, which left the worker process running until its stdout pipe filled; the runner now kills and reaps it on cancellation. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-01 13:02:26 -07:00
elif op == 'metadata':
job['metadata'] = True
else:
raise ValueError(f'Unknown op {op!r}')
if job.get('metadata'):
result['metadata'] = get_metadata(archive)
return result
def main():
request = json.load(sys.stdin)
results = list()
for job in request['jobs']:
try:
results.append(run_job(job))
except Exception as e:
print(f'{job.get("path")}: {e}', file=sys.stderr)
results.append(dict(error=str(e)))
json.dump(results, sys.stdout)
if __name__ == '__main__':
main()