From 2164bfaab81e31cdb7db76038cdf0f7377520966 Mon Sep 17 00:00:00 2001 From: billlyzhaoyh Date: Tue, 1 Dec 2026 18:08:35 +0000 Subject: [PATCH 1/3] fix(datasets): needs from one source are kept with one fetch download_datasets() kept each need with download_need_figures(), which forgets the need figures held in memory before fetching. So a source with two needs, such as ONS's crime tables or UKHSA's vaccinations, was fetched twice in one run, and ONS rate-limits repeated requests. download_datasets() now forgets the need figures once, before it fetches, and keeps each need through what was fetched in the run. Calling download_need_figures() on its own still fetches afresh. Signed-off-by: billlyzhaoyh Github-Issue: #238 --- src/uk_open_data/analyses/_need.py | 21 +++++++++++++++++- src/uk_open_data/analyses/datasets.py | 14 +++++++++--- tests/test_vaccination_needs.py | 31 ++++++++++++++++++++++++--- 3 files changed, 59 insertions(+), 7 deletions(-) diff --git a/src/uk_open_data/analyses/_need.py b/src/uk_open_data/analyses/_need.py index 0f81331..19c93b2 100644 --- a/src/uk_open_data/analyses/_need.py +++ b/src/uk_open_data/analyses/_need.py @@ -1350,6 +1350,26 @@ def download_need_figures(need: str = "unemployed") -> Path: Run this once when a server is built, and again when new figures are published. Only public figures are fetched. + Args: + need: One of the needs the analysis has built in, such as ``unemployed``. + + Returns: + The path of the file written. + + Raises: + ValueError: If the need is not one the analysis has built in, or its + source does not return a count for each local authority. + """ + clear_need_cache() + return keep_fetched_need_figures(need) + + +def keep_fetched_need_figures(need: str) -> Path: + """Keep a need's figures, fetching them only if they are not held in memory. + + Needs from one source then share one fetch. Call :func:`clear_need_cache` + first for fresh figures. + Args: need: One of the needs the analysis has built in, such as ``unemployed``. @@ -1364,7 +1384,6 @@ def download_need_figures(need: str = "unemployed") -> Path: msg = f"No need called '{need}'. Known needs: {', '.join(MEASURES)}." raise ValueError(msg) measure = MEASURES[need] - clear_need_cache() figures = _in_nations(measure.fetch(), measure) note = f"fetched from {measure.origin} on {date.today().isoformat()}." return keep_need_figures( diff --git a/src/uk_open_data/analyses/datasets.py b/src/uk_open_data/analyses/datasets.py index a2d6bbd..65d162c 100644 --- a/src/uk_open_data/analyses/datasets.py +++ b/src/uk_open_data/analyses/datasets.py @@ -17,7 +17,11 @@ from uk_open_data._nations import NATIONS from uk_open_data.analyses._centres import _LEVELS, download_centres from uk_open_data.analyses._model import Source -from uk_open_data.analyses._need import MEASURES, download_need_figures +from uk_open_data.analyses._need import ( + MEASURES, + clear_need_cache, + keep_fetched_need_figures, +) from uk_open_data.analyses._steps import ENGLAND_AND_WALES from uk_open_data.analyses.sources import ( CENSUS_ETHNIC_GROUP, @@ -106,6 +110,8 @@ def download_datasets( The analyses then read the copies instead of the network, so a server or a demonstration works offline. Run this once when a server is built, and again when new figures are published. Only public figures are fetched. + Need figures held in memory are forgotten first, so they are fetched + afresh, and a file that several needs come from is fetched once. The copies live in the data folder (see :func:`uk_open_data.postcodes.offline.data_dir`). @@ -121,10 +127,12 @@ def download_datasets( ValueError: If no id is given in a list, or an id is not a dataset that can be kept. Nothing is fetched then. """ + to_keep = _to_keep(ids) + clear_need_cache() # Two datasets kept in one file share its download, which runs once. written: dict[Callable[[], Path], Path] = {} kept: dict[str, list[Path]] = {} - for dataset in _to_keep(ids): + for dataset in to_keep: fresh = [download for download in dataset.downloads if download not in written] if fresh: logger.info("Fetching %s.", dataset.source.id) @@ -178,7 +186,7 @@ def _kept_for_analyses(source: Source) -> tuple[Callable[[], Path], ...]: """ return ( *( - partial(download_need_figures, need) + partial(keep_fetched_need_figures, need) for need, measure in MEASURES.items() if measure.source.id == source.id ), diff --git a/tests/test_vaccination_needs.py b/tests/test_vaccination_needs.py index 5df182c..5f37beb 100644 --- a/tests/test_vaccination_needs.py +++ b/tests/test_vaccination_needs.py @@ -6,12 +6,14 @@ """ from typing import Any +from unittest.mock import MagicMock import pytest from need_fakes import COUNCIL_COUNTS, RUNS, area, keep_places, serve_gov_uk from spreadsheets import ods from uk_open_data.analyses import AnalysisInputError, AnalysisResult, run_analysis +from uk_open_data.analyses.datasets import download_datasets from uk_open_data.vaccinations import api RELEASE_PATH = "/government/statistics/cover-programme-april-2025-to-march-2026" @@ -91,8 +93,12 @@ def _table(age: str, vaccines: list[str], figures: list[list[float]]) -> list[An return [[f"Children aged {age}"], header, *rows] -def _serve(monkeypatch: pytest.MonkeyPatch, at_24_months: str = "MMR1") -> None: - """Serve UKHSA's statistics, naming the vaccine at 24 months as given.""" +def _serve(monkeypatch: pytest.MonkeyPatch, at_24_months: str = "MMR1") -> MagicMock: + """Serve UKHSA's statistics, naming the vaccine at 24 months as given. + + Returns: + The stand-in for the web request, to see what was asked. + """ workbook = ods( { "T4b_UTLA12m": _table("12 months", ["MenB"], AT_24_MONTHS), @@ -100,7 +106,7 @@ def _serve(monkeypatch: pytest.MonkeyPatch, at_24_months: str = "MMR1") -> None: "T6b_UTLA5y": _table("5 years", ["MMR1", "MMR2"], AT_5_YEARS), } ) - serve_gov_uk(monkeypatch, PAGES, {RELEASE_FILE: workbook}) + return serve_gov_uk(monkeypatch, PAGES, {RELEASE_FILE: workbook}) @pytest.fixture(autouse=True) @@ -193,6 +199,25 @@ def test_a_result_counts_children_without_both_mmr_doses() -> None: assert "ons-local-authority-lookups" in cited +def test_keeping_both_needs_fetches_ukhsa_once( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Both needs come from one file, so keeping them fetches it once (#238).""" + asked = _serve(monkeypatch) + + kept = download_datasets("ukhsa-childhood-vaccinations") + + assert [path.name for path in kept["ukhsa-childhood-vaccinations"]] == [ + "children_without_mmr1_by_2.json", + "children_without_mmr2_by_5.json", + ] + assert [call.args[0] for call in asked.call_args_list] == [ + api.CONTENT_API_URL, + RELEASE, + RELEASE_FILE, + ] + + def test_a_renamed_vaccine_says_ukhsa_changed(monkeypatch: pytest.MonkeyPatch) -> None: _serve(monkeypatch, at_24_months="MMR 1") From 5089fdb3a51ff8d863cbf5807e4fee67ba3f24c0 Mon Sep 17 00:00:00 2001 From: billlyzhaoyh Date: Fri, 4 Dec 2026 18:18:02 +0000 Subject: [PATCH 2/3] fix(datasets): a need's download fetches afresh when run on its own The Codex review of #239 found three ways the fix changed what main did: - download_datasets() forgot the need figures held in memory even when no need was kept, such as when keeping the postcode table alone. It now forgets them only when a need is among the datasets kept. - A need's download in Dataset.downloads, run on its own, kept whatever was in memory and noted it as fetched today. It fetches afresh again, as on main. Only a run of download_datasets() shares what was fetched. - download_need_figures() forgot the figures before it refused an unknown need. It checks the need first, as on main. Each has a test that failed before the change. Github-Issue: #238 --- src/uk_open_data/analyses/_need.py | 19 +++++++------ src/uk_open_data/analyses/datasets.py | 39 +++++++++++++++++++++++---- tests/test_analysis_need_reach.py | 8 ++++++ tests/test_datasets.py | 18 +++++++++++++ tests/test_vaccination_needs.py | 19 ++++++++++++- 5 files changed, 89 insertions(+), 14 deletions(-) diff --git a/src/uk_open_data/analyses/_need.py b/src/uk_open_data/analyses/_need.py index 19c93b2..66a9c1f 100644 --- a/src/uk_open_data/analyses/_need.py +++ b/src/uk_open_data/analyses/_need.py @@ -1323,10 +1323,7 @@ def keep_need_figures( Raises: ValueError: If the need is not one the analysis has built in. """ - if need not in MEASURES: - msg = f"No need called '{need}'. Known needs: {', '.join(MEASURES)}." - raise ValueError(msg) - measure = MEASURES[need] + measure = _built_in(need) content = { "need": need, "label": measure.label, @@ -1360,6 +1357,7 @@ def download_need_figures(need: str = "unemployed") -> Path: ValueError: If the need is not one the analysis has built in, or its source does not return a count for each local authority. """ + _built_in(need) clear_need_cache() return keep_fetched_need_figures(need) @@ -1380,10 +1378,7 @@ def keep_fetched_need_figures(need: str) -> Path: ValueError: If the need is not one the analysis has built in, or its source does not return a count for each local authority. """ - if need not in MEASURES: - msg = f"No need called '{need}'. Known needs: {', '.join(MEASURES)}." - raise ValueError(msg) - measure = MEASURES[need] + measure = _built_in(need) figures = _in_nations(measure.fetch(), measure) note = f"fetched from {measure.origin} on {date.today().isoformat()}." return keep_need_figures( @@ -1407,6 +1402,14 @@ def clear_need_cache() -> None: crime.clear_cache() +def _built_in(need: str) -> Measure: + """Return a built-in need by its name, or say which ones there are.""" + if need not in MEASURES: + msg = f"No need called '{need}'. Known needs: {', '.join(MEASURES)}." + raise ValueError(msg) + return MEASURES[need] + + # --- the area compared ----------------------------------------------------- diff --git a/src/uk_open_data/analyses/datasets.py b/src/uk_open_data/analyses/datasets.py index 65d162c..c711a16 100644 --- a/src/uk_open_data/analyses/datasets.py +++ b/src/uk_open_data/analyses/datasets.py @@ -20,6 +20,7 @@ from uk_open_data.analyses._need import ( MEASURES, clear_need_cache, + download_need_figures, keep_fetched_need_figures, ) from uk_open_data.analyses._steps import ENGLAND_AND_WALES @@ -110,8 +111,9 @@ def download_datasets( The analyses then read the copies instead of the network, so a server or a demonstration works offline. Run this once when a server is built, and again when new figures are published. Only public figures are fetched. - Need figures held in memory are forgotten first, so they are fetched - afresh, and a file that several needs come from is fetched once. + When a need is kept, the need figures held in memory are forgotten first, + so they are fetched afresh, and a file that several needs come from is + fetched once. The copies live in the data folder (see :func:`uk_open_data.postcodes.offline.data_dir`). @@ -128,7 +130,9 @@ def download_datasets( can be kept. Nothing is fetched then. """ to_keep = _to_keep(ids) - clear_need_cache() + downloads = [download for dataset in to_keep for download in dataset.downloads] + if any(isinstance(download, _NeedDownload) for download in downloads): + clear_need_cache() # Two datasets kept in one file share its download, which runs once. written: dict[Callable[[], Path], Path] = {} kept: dict[str, list[Path]] = {} @@ -137,7 +141,7 @@ def download_datasets( if fresh: logger.info("Fetching %s.", dataset.source.id) for download in fresh: - written[download] = download() + written[download] = _run_with_others(download) kept[dataset.source.id] = [written[download] for download in dataset.downloads] return kept @@ -166,6 +170,17 @@ def _to_keep(ids: str | Iterable[str] | None) -> list[Dataset]: return [keepable[id_] for id_ in dict.fromkeys(wanted)] +def _run_with_others(download: Callable[[], Path]) -> Path: + """Run a download as one of several, where needs share what is fetched. + + The need figures held in memory were forgotten when the run began, so a + need keeps what a need before it fetched, and does not fetch it again. + """ + if isinstance(download, _NeedDownload): + return keep_fetched_need_figures(download.need) + return download() + + def _keep_postcode_table() -> Path: """Keep the postcode table this version publishes, unless it is installed. @@ -186,7 +201,7 @@ def _kept_for_analyses(source: Source) -> tuple[Callable[[], Path], ...]: """ return ( *( - partial(keep_fetched_need_figures, need) + _NeedDownload(need) for need, measure in MEASURES.items() if measure.source.id == source.id ), @@ -203,6 +218,20 @@ def _kept_for_analyses(source: Source) -> tuple[Callable[[], Path], ...]: ) +@dataclass(frozen=True) +class _NeedDownload: + """Fetches a need's figures afresh and keeps them, when run on its own. + + In a run of :func:`download_datasets` the need is kept from what the run + has fetched, so needs from one file share its fetch. + """ + + need: str + + def __call__(self) -> Path: + return download_need_figures(self.need) + + _NEED = ("need-reach", "provision-gap", "access-distance") # The analyses that place people in neighbourhoods and read their residents # from the indices of deprivation. diff --git a/tests/test_analysis_need_reach.py b/tests/test_analysis_need_reach.py index 1ec9b15..405c9b0 100644 --- a/tests/test_analysis_need_reach.py +++ b/tests/test_analysis_need_reach.py @@ -447,6 +447,14 @@ def test_only_built_in_needs_can_be_kept(): assert need_figures_path("poverty") is None +def test_an_unknown_need_is_refused_before_figures_are_forgotten(nomis): + _run(_counts(Lewisham=60)) + with pytest.raises(ValueError, match="No need called 'poverty'"): + download_need_figures("poverty") + _run(_counts(Lewisham=60)) + assert len(nomis.asked) == 2 # the need, and the residents for the map + + def test_a_kept_file_that_cannot_be_read_is_an_input_error(nomis): path = keep_need_figures("unemployed", INVENTED, "invented.") path.write_text('{"format": "something else"}', encoding="utf-8") diff --git a/tests/test_datasets.py b/tests/test_datasets.py index ca71086..43c4fd0 100644 --- a/tests/test_datasets.py +++ b/tests/test_datasets.py @@ -229,6 +229,24 @@ def test_clearing_caches_fetches_the_figures_again(nomis) -> None: assert _tables_asked(nomis).count("NM_2124_1") == 2 +def test_keeping_a_dataset_with_no_need_forgets_no_need_figures( + nomis, tmp_path, empty_data_dir +) -> None: + """Need figures held in memory outlast a run that keeps no need.""" + source = tmp_path / "lookup.csv" + source.write_text(fakes.POSTCODE_LOOKUP_CSV, encoding="utf-8") + table = tmp_path / "postcodes.ktpc.gz" + build_postcode_table(source, table, PUBLISHED_TABLE["edition"]) + install_postcode_table(table) + options = {"need": "unemployed"} + run_analysis("need-reach", COUNCIL_COUNTS, options=options) + + download_datasets(["ons-postcode-lookup"]) + + run_analysis("need-reach", COUNCIL_COUNTS, options=options) + assert _tables_asked(nomis).count("NM_2124_1") == 1 + + def test_an_empty_list_of_datasets_is_refused(nomis, empty_data_dir) -> None: with pytest.raises(ValueError, match="No dataset was named"): download_datasets([]) diff --git a/tests/test_vaccination_needs.py b/tests/test_vaccination_needs.py index 5f37beb..93a2e0a 100644 --- a/tests/test_vaccination_needs.py +++ b/tests/test_vaccination_needs.py @@ -13,7 +13,7 @@ from spreadsheets import ods from uk_open_data.analyses import AnalysisInputError, AnalysisResult, run_analysis -from uk_open_data.analyses.datasets import download_datasets +from uk_open_data.analyses.datasets import download_datasets, list_datasets from uk_open_data.vaccinations import api RELEASE_PATH = "/government/statistics/cover-programme-april-2025-to-march-2026" @@ -218,6 +218,23 @@ def test_keeping_both_needs_fetches_ukhsa_once( ] +def test_a_download_run_on_its_own_fetches_afresh( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Outside a run that keeps several, each download asks UKHSA again.""" + asked = _serve(monkeypatch) + dataset = next( + dataset + for dataset in list_datasets() + if dataset.source.id == "ukhsa-childhood-vaccinations" + ) + + for download in dataset.downloads: + download() + + assert [call.args[0] for call in asked.call_args_list].count(RELEASE_FILE) == 2 + + def test_a_renamed_vaccine_says_ukhsa_changed(monkeypatch: pytest.MonkeyPatch) -> None: _serve(monkeypatch, at_24_months="MMR 1") From 0f3432d4b451ec7a4ca18a4c76136dc4c6b27c4d Mon Sep 17 00:00:00 2001 From: billlyzhaoyh Date: Fri, 4 Dec 2026 18:23:46 +0000 Subject: [PATCH 3/3] refactor(datasets): the vaccination tests share one fake request From the /simplify review of #239: - The two new vaccination tests served UKHSA a second time to see what was asked. The gov_uk fixture now hands out the fake request it already makes, as the homelessness and fuel poverty tests do. - _NeedDownload's docstring repeated how a run shares a fetch, which _run_with_others already says. No behaviour changes. Github-Issue: #238 --- src/uk_open_data/analyses/datasets.py | 6 +----- tests/test_vaccination_needs.py | 20 +++++++------------- 2 files changed, 8 insertions(+), 18 deletions(-) diff --git a/src/uk_open_data/analyses/datasets.py b/src/uk_open_data/analyses/datasets.py index c711a16..78afb1a 100644 --- a/src/uk_open_data/analyses/datasets.py +++ b/src/uk_open_data/analyses/datasets.py @@ -220,11 +220,7 @@ def _kept_for_analyses(source: Source) -> tuple[Callable[[], Path], ...]: @dataclass(frozen=True) class _NeedDownload: - """Fetches a need's figures afresh and keeps them, when run on its own. - - In a run of :func:`download_datasets` the need is kept from what the run - has fetched, so needs from one file share its fetch. - """ + """Fetches a need's figures afresh and keeps them, when run on its own.""" need: str diff --git a/tests/test_vaccination_needs.py b/tests/test_vaccination_needs.py index 93a2e0a..0aed9a3 100644 --- a/tests/test_vaccination_needs.py +++ b/tests/test_vaccination_needs.py @@ -110,13 +110,14 @@ def _serve(monkeypatch: pytest.MonkeyPatch, at_24_months: str = "MMR1") -> Magic @pytest.fixture(autouse=True) -def gov_uk(monkeypatch: pytest.MonkeyPatch) -> None: +def gov_uk(monkeypatch: pytest.MonkeyPatch) -> MagicMock: """Serve UKHSA's statistics, and keep the residents and centres runs need.""" - _serve(monkeypatch) + answer = _serve(monkeypatch) keep_places( tuple((code, code, 100000) for code in MORE_COUNCILS), tuple((code, 52.6 + i / 100, -1.1) for i, code in enumerate(MORE_COUNCILS)), ) + return answer def _compared(result: AnalysisResult) -> dict[str, int]: @@ -199,30 +200,23 @@ def test_a_result_counts_children_without_both_mmr_doses() -> None: assert "ons-local-authority-lookups" in cited -def test_keeping_both_needs_fetches_ukhsa_once( - monkeypatch: pytest.MonkeyPatch, -) -> None: +def test_keeping_both_needs_fetches_ukhsa_once(gov_uk: MagicMock) -> None: """Both needs come from one file, so keeping them fetches it once (#238).""" - asked = _serve(monkeypatch) - kept = download_datasets("ukhsa-childhood-vaccinations") assert [path.name for path in kept["ukhsa-childhood-vaccinations"]] == [ "children_without_mmr1_by_2.json", "children_without_mmr2_by_5.json", ] - assert [call.args[0] for call in asked.call_args_list] == [ + assert [call.args[0] for call in gov_uk.call_args_list] == [ api.CONTENT_API_URL, RELEASE, RELEASE_FILE, ] -def test_a_download_run_on_its_own_fetches_afresh( - monkeypatch: pytest.MonkeyPatch, -) -> None: +def test_a_download_run_on_its_own_fetches_afresh(gov_uk: MagicMock) -> None: """Outside a run that keeps several, each download asks UKHSA again.""" - asked = _serve(monkeypatch) dataset = next( dataset for dataset in list_datasets() @@ -232,7 +226,7 @@ def test_a_download_run_on_its_own_fetches_afresh( for download in dataset.downloads: download() - assert [call.args[0] for call in asked.call_args_list].count(RELEASE_FILE) == 2 + assert [call.args[0] for call in gov_uk.call_args_list].count(RELEASE_FILE) == 2 def test_a_renamed_vaccine_says_ukhsa_changed(monkeypatch: pytest.MonkeyPatch) -> None: