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>
This commit is contained in:
lrnselfreliance 2026-11-01 13:02:26 -07:00 • committed by GitHub
parent 9c258b41ee
commit bfe7b8afbd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 376 additions and 154 deletions

View file

@ -1,4 +1,7 @@
import asyncio
import json
import sys
from unittest import mock
from http import HTTPStatus
import pytest
@ -366,3 +369,108 @@ async def test_delete_zim_waits_for_a_concurrent_writer(async_client, test_sessi
assert not zim_path.exists()
with maker() as session:
assert session.query(Zim).filter_by(id=zim_id).one_or_none() is None
@pytest.mark.asyncio
async def test_estimate_zims_runs_outside_the_api_process(test_session, zim_factory):
"""libzim holds the GIL, so estimates run in a separate process rather than a thread of the API worker."""
zim = zim_factory('test zim')
test_session.commit()
with mock.patch('modules.zim.lib.asyncio.create_subprocess_exec', wraps=asyncio.create_subprocess_exec) as m:
counts = await lib.estimate_zims(test_session, 'one')
assert counts == {zim: 2}
assert m.call_args.args[:2] == (sys.executable, '-I')
@pytest.mark.asyncio
async def test_estimate_zims_skips_a_zim_it_cannot_read(test_session, zim_factory):
"""A Zim the estimate process cannot open is left out of the estimates, like `Zims.get_all` leaves it out."""
good = zim_factory('good zim')
bad = zim_factory('bad zim')
test_session.commit()
bad.path.write_bytes(b'not a zim file')
counts = await lib.estimate_zims(test_session, 'one')
assert counts == {good: 2}
bad.path.unlink()
counts = await lib.estimate_zims(test_session, 'one')
assert counts == {good: 2}
@pytest.mark.asyncio
async def test_zim_search_runs_outside_the_api_process(async_client, test_session, test_zim):
"""Zim searches, like estimates, do all their libzim work in the worker script's process."""
with mock.patch('modules.zim.lib.asyncio.create_subprocess_exec', wraps=asyncio.create_subprocess_exec) as m:
request, response = await async_client.post(f'/api/zim/search/{test_zim.id}', json=dict(search_str='one'))
assert response.status_code == HTTPStatus.OK
assert [i['path'] for i in response.json['zim']['search']] == ['one', 'home']
assert response.json['zim']['metadata']['title'], 'Metadata should come from the worker'
request, response = await async_client.post('/api/zim/search', json=dict(search_str='one'))
assert response.status_code == HTTPStatus.OK
assert [i['path'] for i in response.json['zims'][0]['search']] == ['one', 'home']
assert m.call_count == 2
assert all(call.args[:2] == (sys.executable, '-I') for call in m.call_args_list)
@pytest.mark.asyncio
async def test_search_all_zims_skips_a_zim_it_cannot_read(async_client, test_session, zim_factory):
"""One unreadable Zim does not fail the search of all Zims."""
good = zim_factory('good zim')
bad = zim_factory('bad zim')
test_session.commit()
bad.path.write_bytes(b'not a zim file')
request, response = await async_client.post('/api/zim/search', json=dict(search_str='one'))
assert response.status_code == HTTPStatus.OK
zims = response.json['zims']
assert len(zims) == 1 and zims[0]['path'].endswith('good zim')
assert zims[0]['estimate'] == 2
@pytest.mark.asyncio
async def test_tagged_search_estimates_do_not_open_zims(async_client, test_session, test_zim, tag_factory):
"""Estimates with tags count from the database; the API process never opens a Zim, even for its metadata."""
tag1, tag2 = await tag_factory(), await tag_factory()
test_zim.tag_entry(test_session, tag1.name, 'one')
test_zim.tag_entry(test_session, tag1.name, 'two')
test_zim.tag_entry(test_session, tag2.name, 'one')
test_session.commit()
with mock.patch('modules.zim.models.Zim.get_zim', side_effect=AssertionError('opened a Zim in the API')):
body = dict(search_str='one', tag_names=[tag1.name])
request, response = await async_client.post('/api/zim/search_estimates', json=body)
assert response.status_code == HTTPStatus.OK
assert [(i['estimate'], bool(i['metadata']['title'])) for i in response.json['zims_estimates']] \
== [(2, True)]
body = dict(search_str='', tag_names=[tag1.name, tag2.name])
request, response = await async_client.post('/api/zim/search_estimates', json=body)
assert [i['estimate'] for i in response.json['zims_estimates']] == [1]
@pytest.mark.asyncio
async def test_cancelled_libzim_jobs_kill_the_worker(test_directory):
"""Sanic cancels a handler at its response timeout or on disconnect; the worker process must not outlive it."""
slow_worker = test_directory / 'slow_worker.py'
slow_worker.write_text('import time; time.sleep(60)')
procs = []
create_subprocess_exec = asyncio.create_subprocess_exec
async def spy(*args, **kwargs):
proc = await create_subprocess_exec(*args, **kwargs)
procs.append(proc)
return proc
with mock.patch('modules.zim.lib.LIBZIM_WORKER', slow_worker), \
mock.patch('modules.zim.lib.asyncio.create_subprocess_exec', side_effect=spy):
task = asyncio.create_task(lib.run_libzim_jobs([]))
while not procs:
await asyncio.sleep(0.01)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert procs[0].returncode is not None, 'The worker was killed and reaped'