zim: recompute the outdated-Zims flag after startup and on Delete (#706)
Some checks are pending
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run

* zim: recompute the outdated-Zims flag after startup and on Delete

The Dashboard shows the "Outdated Zim Files" banner from the persisted
`outdated_zims` flag, but the modal lists files from a live scan.  The two
disagreed: the flag was restored from the DB on startup and never
recomputed once the outdated file had been removed, so the banner showed
with nothing to delete, and the modal displayed an endless placeholder.

- The startup recompute now runs after the DB is up and configs are
  imported, so it overrides the value `init_flags` restored from the DB.
  Previously it ran before the DB was up, and the restored value won.
- DELETE /api/zim/outdated always recomputes the flag, even when nothing
  was deleted, so clicking Delete clears a stale banner.
- The modal re-scans when opened and says when nothing was found instead
  of showing a placeholder.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* zim: enforce restore-then-scan ordering; no Kiwix restart on empty delete

- Startup calls flags.init_flags() then flag_outdated_zim_files() right
  after db_up, before the DB config import, so the disk scan always
  overwrites the DB-restored value in one local sequence.
- DELETE /api/zim/outdated recomputes the flag in a finally.
- remove_outdated_zim_files skips refresh and the Kiwix restart when no
  file was deleted.
- Trim narrative comments to the constraint they enforce.

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-09-12 15:18:13 -06:00 • committed by Roland
parent 8008cd1fd8
commit e0fdb762fc
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
8 changed files with 106 additions and 15 deletions

View file

@ -58,10 +58,16 @@ import {HeadlineText} from "./Headline";
export const OutdatedZimsMessage = ({onClick}) => {
const [open, setOpen] = React.useState(false);
const {outdated, current} = useOutdatedZims();
const {outdated, current, fetchOutdatedZims} = useOutdatedZims();
const onClose = () => setOpen(false);
const onOpen = async () => {
setOpen(true);
// The list must reflect disk now, not page load.
await fetchOutdatedZims();
}
const handleDelete = async () => {
try {
const success = await deleteOutdatedZims();
@ -102,13 +108,17 @@ export const OutdatedZimsMessage = ({onClick}) => {
<Header as='h3'>To Keep</Header>
{current.map(i => <pre key={i}>{i}</pre>)}
</>
} else if (outdated && outdated.length === 0) {
modalContent = <p>
No outdated Zim files were found. Click Delete to clear this message.
</p>
}
return <Message kind='info' icon='question' title='Outdated Zim Files'>
New Zim files have been downloaded. Outdated Zim files can be removed.
<p></p>
<Button role='danger' onClick={() => setOpen(true)}>Delete</Button>
<Button role='danger' onClick={onOpen}>Delete</Button>
<Modal size='small' open={open}
onClose={onClose}
title='Delete'

View file

@ -73,3 +73,43 @@ describe('the Zim catalog language dropdown', () => {
expect(screen.getByPlaceholderText('Language')).toBeInTheDocument();
});
});
// The Dashboard's "Outdated Zim Files" banner: its modal must always show a fresh scan, and say when it is empty.
import {OutdatedZimsMessage} from './Zim';
import {fireEvent, waitFor} from '@testing-library/react';
import {getOutdatedZims} from '../api';
jest.mock('../api', () => ({
...jest.requireActual('../api'),
getOutdatedZims: jest.fn(),
deleteOutdatedZims: jest.fn(),
}));
describe('the outdated Zims banner', () => {
beforeEach(() => getOutdatedZims.mockReset());
it('tells the user when the live scan finds nothing to delete', async () => {
getOutdatedZims.mockResolvedValue({outdated: [], current: ['zims/wikipedia_en_all_maxi_2024-01.zim']});
render(<OutdatedZimsMessage/>);
fireEvent.click(screen.getByRole('button', {name: 'Delete'}));
await waitFor(() => expect(screen.getByText(/No outdated Zim files were found/)).toBeInTheDocument());
});
it('re-scans when the modal is opened, so the list is not the one from page load', async () => {
getOutdatedZims.mockResolvedValue({outdated: [], current: []});
render(<OutdatedZimsMessage/>);
await waitFor(() => expect(getOutdatedZims).toHaveBeenCalledTimes(1));
getOutdatedZims.mockResolvedValue({
outdated: ['zims/wikipedia_en_all_maxi_2023-12.zim'],
current: ['zims/wikipedia_en_all_maxi_2024-01.zim'],
});
fireEvent.click(screen.getByRole('button', {name: 'Delete'}));
await waitFor(() => expect(getOutdatedZims).toHaveBeenCalledTimes(2));
expect(await screen.findByText('zims/wikipedia_en_all_maxi_2023-12.zim')).toBeInTheDocument();
expect(screen.getByText('zims/wikipedia_en_all_maxi_2024-01.zim')).toBeInTheDocument();
});
});

View file

@ -1981,7 +1981,7 @@ export const useOutdatedZims = () => {
localFetchOutdatedZims();
}, []);
return {outdated, current}
return {outdated, current, fetchOutdatedZims: localFetchOutdatedZims}
}
export const useVINDecoder = (defaultVINNumber = '') => {

14
main.py
View file

@ -282,16 +282,18 @@ async def start_single_tasks(app: Sanic):
get_download_cache_config().import_config()
logger.debug('download cache config imported')
from modules.zim.lib import flag_outdated_zim_files
try:
flag_outdated_zim_files()
except Exception as e:
logger.error('Failed to flag outdated Zims', exc_info=e)
logger.debug('start_single_tasks waiting for db...')
async with flags.db_up.wait_for():
logger.debug('start_single_tasks db is up')
# The disk scan must overwrite the DB-restored `outdated_zims` value, so restore first (idempotent), then scan.
from modules.zim.lib import flag_outdated_zim_files
try:
flags.init_flags()
flag_outdated_zim_files()
except Exception as e:
logger.error('Failed to flag outdated Zims', exc_info=e)
# Import configs that require the database.
if wrolpi_config.successful_import and not wrolpi_config.wrol_mode:
from wrolpi.common import import_all_db_configs

View file

@ -200,9 +200,12 @@ async def get_outdated_zims(_: Request):
summary='Remove all outdated Zims, if any.'
)
async def delete_outdated_zims(_: Request):
deleted_count = await lib.remove_outdated_zim_files()
if deleted_count:
try:
deleted_count = await lib.remove_outdated_zim_files()
finally:
# The flag must match disk whether or not the delete succeeded.
lib.flag_outdated_zim_files()
if deleted_count:
Events.send_deleted(f'Deleted {deleted_count} outdated Zims')
return response.empty(HTTPStatus.NO_CONTENT)

View file

@ -593,11 +593,12 @@ async def remove_outdated_zim_files(path: pathlib.Path = None) -> int:
file.unlink()
deleted_count += 1
# Refresh synchronously to clean up DB before returning.
await file_worker.refresh_sync(list(outdated))
if deleted_count:
# Refresh synchronously to clean up DB before returning.
await file_worker.refresh_sync(list(outdated))
# Trigger Kiwix restart so the deleted zim files are no longer served.
restart_kiwix_handler.activate_switch()
# Trigger Kiwix restart so the deleted zim files are no longer served.
restart_kiwix_handler.activate_switch()
return deleted_count

View file

@ -5,6 +5,7 @@ import pytest
from modules.zim import lib
from modules.zim.models import Zim
from wrolpi import flags
from wrolpi.downloader import Download
@ -249,6 +250,23 @@ async def test_find_outdated_zim_files(test_session, test_directory, test_zim_by
assert empty.is_file()
@pytest.mark.asyncio
async def test_delete_outdated_zims_clears_stale_flag(test_session, test_directory, test_zim_bytes, async_client,
flags_lock):
"""Deleting outdated Zims always leaves the `outdated_zims` flag matching disk, even when nothing was deleted."""
(test_directory / 'zims').mkdir(parents=True)
(test_directory / 'zims/wikipedia_en_all_maxi_2023-02.zim').write_bytes(test_zim_bytes)
flags.outdated_zims.set()
request, response = await async_client.get('/api/zim/outdated')
assert response.status_code == HTTPStatus.OK
assert response.json['outdated'] == []
request, response = await async_client.delete('/api/zim/outdated')
assert response.status_code == HTTPStatus.NO_CONTENT
assert not flags.outdated_zims.is_set(), 'Flag should be recomputed even when nothing was deleted'
@pytest.mark.asyncio
async def test_search_estimates(test_session, async_client, zim_factory):
zim_factory('test zim')

View file

@ -128,3 +128,20 @@ async def test_remove_outdated_zim_files_triggers_restart(async_client, test_ses
# Verify the switch was activated
switches = dict(api_app.shared_ctx.switches) if api_app.shared_ctx.switches else {}
assert 'restart_kiwix' in switches
@pytest.mark.asyncio
async def test_remove_outdated_zim_files_no_restart_when_nothing_deleted(async_client, test_session, test_directory,
zim_path_factory, await_switches):
"""Clearing a stale flag must not restart Kiwix when no file was deleted."""
zim_dir = test_directory / 'zims'
zim_dir.mkdir(exist_ok=True)
(zim_dir / 'wikipedia_en_all_maxi_2020-02.zim').write_bytes(zim_path_factory().read_bytes())
await await_switches()
deleted_count = await lib.remove_outdated_zim_files(zim_dir)
assert deleted_count == 0
switches = dict(api_app.shared_ctx.switches) if api_app.shared_ctx.switches else {}
assert 'restart_kiwix' not in switches