diff --git a/nz/ingest_official_budget_scores.py b/nz/ingest_official_budget_scores.py index cec8d6f66..6b0251528 100644 --- a/nz/ingest_official_budget_scores.py +++ b/nz/ingest_official_budget_scores.py @@ -484,10 +484,14 @@ def ingest(db_path: Path) -> dict: source census; unchanged parents are updated in place and attachments are pruned only for claims that disappeared. Existing diagnosing/published/ regressed lane states are never rolled back by a source refresh, while an - early-stage lane advances to computed when surviving results exist. - The committed JSON lane mirror is deliberately post-transaction, matching - the repository-wide convention. A mirror failure is recoverable by safely - rerunning this idempotent ingest. + early-stage lane advances to computed when a surviving claim's latest + result, ordered as the feed orders them (computed_at, then id), carries a + PolicyEngine value: the rule the populations feed and the app use for + "with a value". A valueless pe_gap or mismatch that is a claim's latest + row does not count that claim as computed. The committed JSON lane mirror + is deliberately post-transaction, matching the repository-wide + convention. A mirror failure is recoverable by safely rerunning this + idempotent ingest. """ scores = stage_scores() score_rows = [ScorecardDB.score_row(score) for score in scores] @@ -523,9 +527,9 @@ def ingest(db_path: Path) -> dict: result_state = db.conn.execute( "SELECT COUNT(r.id) AS latest_results, " - "COALESCE(SUM(CASE WHEN r.status != 'not_computed' " + "COALESCE(SUM(CASE WHEN r.computed_value IS NOT NULL " "THEN 1 ELSE 0 END), 0) AS computed_claims, " - "MAX(CASE WHEN r.status != 'not_computed' " + "MAX(CASE WHEN r.computed_value IS NOT NULL " "THEN substr(r.computed_at, 1, 10) END) AS latest_result " "FROM external_scores s " "LEFT JOIN pe_results r ON r.id = (" @@ -557,7 +561,10 @@ def ingest(db_path: Path) -> dict: ) elif current_lane is not None and current_lane["stage"] == "computed": lane_stage = "regressed" - detail = f"0 of {len(scores)} claims retain results — {base_detail}" + detail = ( + f"0 of {len(scores)} claims retain a PolicyEngine value — " + f"{base_detail}" + ) db.conn.execute( LANE_SQL, (LANE_ID, lane_stage, detail, UPDATED), diff --git a/scorecard_db/ingest_harvest.py b/scorecard_db/ingest_harvest.py index 48e0a7034..225893cf1 100644 --- a/scorecard_db/ingest_harvest.py +++ b/scorecard_db/ingest_harvest.py @@ -174,6 +174,7 @@ def sync_lane_feed( } _COMPUTED_PREFIX = re.compile(r"^\d+ of \d+ claims computed — ") +_HARVEST_SOURCES_SQL = "('jct','tpc','cpsp','pwbm','tax_foundation','budget_lab','cbo')" def _harvest_lane(source: str, reform_json: str) -> str: @@ -184,15 +185,19 @@ def _harvest_lane(source: str, reform_json: str) -> str: def advance_computed_lanes(db_path: Path, feed_path: Path | None = None) -> dict: - """Advance harvest lanes ingested -> computed once PE results exist + """Advance harvest lanes ingested -> computed once PE values exist for their claims. The adapters run early in the build chain and only know staging; results attach later (reform_validation, campaign_us), so this runs - after campaign_us and derives each lane's stage from the DB itself: - any lane whose claims carry pe_results moves to computed, its note - gains a "N of M claims computed" prefix, and updated_at becomes the - latest computed_at date so the feed shows when compute actually + after campaign_us and derives each lane's stage from the DB itself. + A claim counts as computed when its latest result, ordered as the feed + orders them (computed_at, then id), carries a PolicyEngine value: the + rule the populations feed and the app use for "with a value". A + valueless pe_gap or mismatch that is a claim's latest row does not + count. Any lane with a counted claim moves to computed, its note gains + a "N of M claims computed" prefix, and updated_at becomes the latest + counted computed_at date so the feed shows when compute actually landed. Lanes already past computed are never regressed. Deterministic and idempotent (the prefix is replaced, not stacked).""" db = ScorecardDB(db_path) @@ -200,8 +205,7 @@ def advance_computed_lanes(db_path: Path, feed_path: Path | None = None) -> dict claim_totals: Counter = Counter() for row in db.conn.execute( "SELECT claim_id, source, reform_json FROM external_scores" - " WHERE source IN ('jct','tpc','cpsp','pwbm','tax_foundation'," - "'budget_lab','cbo')" + f" WHERE source IN {_HARVEST_SOURCES_SQL}" ): lane = _harvest_lane(row["source"], row["reform_json"]) lane_of[row["claim_id"]] = lane @@ -210,12 +214,16 @@ def advance_computed_lanes(db_path: Path, feed_path: Path | None = None) -> dict computed: Counter = Counter() latest: dict[str, str] = {} for row in db.conn.execute( - "SELECT claim_id, MAX(substr(computed_at, 1, 10)) AS d" - " FROM pe_results GROUP BY claim_id" + "SELECT s.claim_id, substr(r.computed_at, 1, 10) AS d" + " FROM external_scores s JOIN pe_results r ON r.id = (" + "SELECT id FROM pe_results WHERE claim_id = s.claim_id" + " ORDER BY computed_at DESC, id DESC LIMIT 1)" + f" WHERE s.source IN {_HARVEST_SOURCES_SQL}" + " AND r.computed_value IS NOT NULL" ): lane = lane_of.get(row["claim_id"]) if lane is None: - continue + continue # a claim added after the first read computed[lane] += 1 latest[lane] = max(latest.get(lane, ""), row["d"] or "") diff --git a/scorecard_db/ingest_uk_ab2025.py b/scorecard_db/ingest_uk_ab2025.py index 3919afb9a..b11210855 100644 --- a/scorecard_db/ingest_uk_ab2025.py +++ b/scorecard_db/ingest_uk_ab2025.py @@ -1033,18 +1033,12 @@ def stage() -> tuple[list[ExternalScore], dict]: precision=lambda s: len(s.conditions.get("value_verbatim", "")), tolerance=lambda s: max(abs(s.value) * 0.005, 1e-9), ) - twins = len(mine) - len(kept) - if twins: - fam_of = {s.claim_id(): s.publication["family"] for s in mine} - kept_ids = {s.claim_id() for s in kept} - for s in mine: - if s.claim_id() in kept_ids and s is not next( - k for k in kept if k.claim_id() == s.claim_id() - ): - fam = acct["by_family"][fam_of[s.claim_id()]] - _drop(acct, fam, "republished_twin_merged") - acct["ingested"] -= 1 - fam["ingested"] -= 1 + if len(kept) != len(mine): + for family in _merged_twins(mine, kept): + fam = acct["by_family"][family] + _drop(acct, fam, "republished_twin_merged") + acct["ingested"] -= 1 + fam["ingested"] -= 1 merged.extend(kept) acct["dropped"] = acct["read"] - acct["ingested"] if acct["ingested"] + acct["dropped"] != acct["read"]: # pragma: no cover @@ -1052,6 +1046,27 @@ def stage() -> tuple[list[ExternalScore], dict]: return finish(merged, REGISTRY_MARK), acct +def _merged_twins(mine: list[ExternalScore], kept: list[ExternalScore]) -> list[str]: + """The family each merged twin is tallied against, in row order. + + A row is a merged twin when another row with its claim id is the one + merge_republications kept. The tally goes to the family of the last row + with that id, as it always has (#264 asks whether it should be the + twin's own). Each score is hashed once and kept rows are looked up by + id, so the work grows linearly with the rows: a scan of `kept` per row + once dominated a full build.""" + ids = [s.claim_id() for s in mine] + fam_of = {cid: s.publication["family"] for s, cid in zip(mine, ids)} + kept_by_id: dict[str, ExternalScore] = {} + for k in kept: + kept_by_id.setdefault(k.claim_id(), k) + return [ + fam_of[cid] + for s, cid in zip(mine, ids) + if cid in kept_by_id and s is not kept_by_id[cid] + ] + + def _drop(acct: dict, fam: dict, reason_key: str) -> None: entry = acct["drops"].setdefault( reason_key, {"rows": 0, "reason": DROPS[reason_key]} diff --git a/scorecard_db/ingest_uk_childcare_100k.py b/scorecard_db/ingest_uk_childcare_100k.py index d7ff257d5..d4fd8512c 100644 --- a/scorecard_db/ingest_uk_childcare_100k.py +++ b/scorecard_db/ingest_uk_childcare_100k.py @@ -1362,6 +1362,12 @@ def accounting(scores, pe, diag, drops, artifacts) -> dict: def ingest(db_path: Path) -> dict: + """Stage and check the accounting, then replace this registry in one + transaction and mirror the lane. + + The write lock is taken before the registry is read, so two overlapping + ingests run one after the other instead of both reading an empty + registry and each writing every row.""" notes = load_notes() scores, drops, artifacts = stage(notes) art = artifacts[-1][0] @@ -1371,51 +1377,54 @@ def ingest(db_path: Path) -> dict: want = expected(scores, artifacts, notes) if counts != want: raise ValueError(f"claim accounting drifted: {counts} != {want}") - db = ScorecardDB(db_path) from .baselines import register_baselines_txn from .ingest_harvest import sync_lane_feed - with db.conn: - old = [ - r[0] - for r in db.conn.execute( - "SELECT claim_id FROM external_scores " - "WHERE json_extract(publication, '$.registry') = ?", - (REGISTRY_MARK,), + db = ScorecardDB(db_path) + try: + with db.conn: + db.conn.execute("BEGIN IMMEDIATE") + old = [ + r[0] + for r in db.conn.execute( + "SELECT claim_id FROM external_scores " + "WHERE json_extract(publication, '$.registry') = ?", + (REGISTRY_MARK,), + ) + ] + for table in ("diagnoses", "pe_results", "external_scores"): + db.conn.executemany( + f"DELETE FROM {table} WHERE claim_id = ?", [(c,) for c in old] + ) + db.conn.executemany(SCORES_SQL, [ScorecardDB.score_row(s) for s in scores]) + db.conn.executemany(RESULTS_SQL, [ScorecardDB.result_row(r) for r in pe]) + db.conn.executemany(DIAGNOSES_SQL, diag) + register_baselines_txn(db) + runs = {a["run_id"] for a, _ in artifacts} + computed = {r.claim_id for r in pe if r.run_id in runs} + pairs = ( + "the certified pair" + if len(artifacts) == 1 + else f"{len(artifacts)} certified pairs, the newest" ) - ] - for table in ("diagnoses", "pe_results", "external_scores"): - db.conn.executemany( - f"DELETE FROM {table} WHERE claim_id = ?", [(c,) for c in old] + detail = ( + f"{len(computed)} of {len(scores)} claims computed on {pairs} " + f"({art['data_bundle']}, policyengine-uk {art['engine_version']}) — " + "CenTax Table 4.2 (24 cells: static cost comparable, net cost concept_mismatch) and CBP's " + "technical appendix (12 abolition cells, concept_mismatch); PolicyEngine's published " + "dashboard figure kept as history" + + ("; pe_gap on the central static rows" if diag else "") ) - db.conn.executemany(SCORES_SQL, [ScorecardDB.score_row(s) for s in scores]) - db.conn.executemany(RESULTS_SQL, [ScorecardDB.result_row(r) for r in pe]) - db.conn.executemany(DIAGNOSES_SQL, diag) - register_baselines_txn(db) - runs = {a["run_id"] for a, _ in artifacts} - computed = {r.claim_id for r in pe if r.run_id in runs} - pairs = ( - "the certified pair" - if len(artifacts) == 1 - else f"{len(artifacts)} certified pairs, the newest" + db.conn.execute(LANE_SQL, (LANE_ID, "computed", detail, LANE_UPDATED)) + sync_lane_feed( + db, + REPO / "data" / "lanes.json", + FEED_UPDATED, + lanes={LANE_ID: LANE_FEED_META}, ) - detail = ( - f"{len(computed)} of {len(scores)} claims computed on {pairs} " - f"({art['data_bundle']}, policyengine-uk {art['engine_version']}) — " - "CenTax Table 4.2 (24 cells: static cost comparable, net cost concept_mismatch) and CBP's " - "technical appendix (12 abolition cells, concept_mismatch); PolicyEngine's published " - "dashboard figure kept as history" - + ("; pe_gap on the central static rows" if diag else "") - ) - db.conn.execute(LANE_SQL, (LANE_ID, "computed", detail, LANE_UPDATED)) - sync_lane_feed( - db, - REPO / "data" / "lanes.json", - FEED_UPDATED, - lanes={LANE_ID: LANE_FEED_META}, - ) - db.close() + finally: + db.close() return counts diff --git a/tests/test_harvest_ingest.py b/tests/test_harvest_ingest.py index eff0c94d8..075591f7d 100644 --- a/tests/test_harvest_ingest.py +++ b/tests/test_harvest_ingest.py @@ -777,6 +777,135 @@ def test_idempotent_prefix_and_no_regression(self, prepared): db.close() assert (row["stage"], row["detail"]) == ("diagnosing", "batch open") + @pytest.mark.parametrize( + "rows, updated", + [ + pytest.param([("pe_gap", None, "2026-08-09")], None, id="gap-only"), + pytest.param( + [("constructed", 1.0, "2026-08-08"), ("pe_gap", None, "2026-08-09")], + None, + id="newer-gap-supersedes-a-value", + ), + pytest.param( + [("constructed", 1.0, "2026-08-09"), ("pe_gap", None, "2026-08-09")], + None, + id="tie-goes-to-the-later-id", + ), + pytest.param( + [ + ("concept_mismatch", None, "2026-08-08"), + ("comparable", 2.0, "2026-08-09"), + ], + "2026-08-09", + id="newer-value-supersedes-a-gap", + ), + pytest.param( + [("pe_gap", None, "2026-08-09"), ("constructed", 1.0, "2026-08-08")], + None, + id="date-not-insert-order-picks-the-gap", + ), + pytest.param( + [("constructed", 1.0, "2026-08-09"), ("pe_gap", None, "2026-08-08")], + "2026-08-09", + id="date-not-insert-order-picks-the-value", + ), + ], + ) + def test_counts_a_claim_only_when_its_latest_result_has_a_value( + self, prepared, rows, updated + ): + """A claim counts as computed only when its latest result, ordered + as the feed orders them (computed_at, then id), carries a + PolicyEngine value; a valueless pe_gap or mismatch as the latest + row leaves its lane where the adapter put it.""" + from scorecard_db import PEResult + from scorecard_db.ingest_harvest import advance_computed_lanes + + db_path, feed = prepared + policy = ReformRef(framework="policy_ref", reform={"policy": "x"}) + claim_id = self._claim("cbo", reform=policy).claim_id() + db = ScorecardDB(db_path) + for status, value, when in rows: + db.add_results( + [ + PEResult( + claim_id=claim_id, + computed_value=value, + status=status, + engine_version="1", + data_bundle="b", + computed_at=f"{when}T00:00:00Z", + ) + ] + ) + db.close() + stats = advance_computed_lanes(db_path, feed_path=feed) + assert ("cbo-cost-estimates" in stats["lanes_advanced"]) is bool(updated) + assert set(stats["lanes_advanced"]) - {"cbo-cost-estimates"} == { + "jct-reform-scores", + "cbo-baseline", + } + db = ScorecardDB(db_path) + lane = db.conn.execute( + "SELECT stage, detail, updated_at FROM lanes" + " WHERE lane = 'cbo-cost-estimates'" + ).fetchone() + db.close() + if updated: + assert tuple(lane) == ( + "computed", + "1 of 1 claims computed — adapter note", + updated, + ) + else: + assert tuple(lane) == ("ingested", "adapter note", "2026-08-02") + + def test_a_mixed_lane_counts_and_dates_only_its_valued_claims(self, prepared): + """In a lane holding a claim with a value and a claim whose latest + row is a newer valueless gap, N counts only the valued claim and + updated_at is that claim's date, not the gap's.""" + from scorecard_db import PEResult + from scorecard_db.ingest_harvest import advance_computed_lanes + + db_path, feed = prepared + valued = self._claim( + "cbo", reform=ReformRef(framework="policy_ref", reform={"policy": "x"}) + ) + gap = self._claim( + "cbo", reform=ReformRef(framework="policy_ref", reform={"policy": "y"}) + ) + db = ScorecardDB(db_path) + db.upsert_scores([gap]) + db.add_results( + [ + PEResult( + claim_id=claim.claim_id(), + computed_value=value, + status=status, + engine_version="1", + data_bundle="b", + computed_at=f"{when}T00:00:00Z", + ) + for claim, status, value, when in ( + (valued, "constructed", 1.0, "2026-08-08"), + (gap, "pe_gap", None, "2026-08-10"), + ) + ] + ) + db.close() + advance_computed_lanes(db_path, feed_path=feed) + db = ScorecardDB(db_path) + lane = db.conn.execute( + "SELECT stage, detail, updated_at FROM lanes" + " WHERE lane = 'cbo-cost-estimates'" + ).fetchone() + db.close() + assert tuple(lane) == ( + "computed", + "1 of 2 claims computed — adapter note", + "2026-08-08", + ) + def test_every_committed_lane_carries_a_country(): """The app's countryOf() defaults a missing key to US, so a committed diff --git a/tests/test_nz_official_budget_scores.py b/tests/test_nz_official_budget_scores.py index 3151a2fae..229c93157 100644 --- a/tests/test_nz_official_budget_scores.py +++ b/tests/test_nz_official_budget_scores.py @@ -351,10 +351,159 @@ def test_refresh_uses_latest_result_and_marks_a_computed_lane_regressed( "SELECT stage, detail FROM lanes WHERE lane = ?", (mod.LANE_ID,) ).fetchone() assert lane["stage"] == "regressed" - assert "0 of 12 claims retain results" in lane["detail"] + assert "0 of 12 claims retain a PolicyEngine value" in lane["detail"] db.close() +def _result(score, *, status, value, run_id="test-run", when="2026-08-29"): + return PEResult( + claim_id=score.claim_id(), + computed_value=value, + status=status, + engine_version="test-engine", + data_bundle="test-bundle", + run_id=run_id, + computed_at=when, + baseline_key=score.reform.baseline_key(), + ) + + +@pytest.mark.parametrize( + "status, value, counted", + [ + (ComparisonStatus.PE_GAP, None, False), + (ComparisonStatus.CONCEPT_MISMATCH, None, False), + (ComparisonStatus.CONCEPT_MISMATCH, 2.0, True), + (ComparisonStatus.CONSTRUCTED, 1.0, True), + ], +) +def test_lane_counts_only_a_latest_result_with_a_value( + tmp_path, monkeypatch, status, value, counted +): + """A claim counts as computed only when its latest result carries a + PolicyEngine value, the populations feed's and the app's "with a value" + rule; a valueless gap or mismatch does not make the lane computed, and + the lane's count matches the feed's.""" + from scorecard_db.export_populations import export + + monkeypatch.setattr(mod, "sync_lane_feed", lambda *args, **kwargs: 1) + path = tmp_path / "scorecard.db" + mod.ingest(path) + score = mod.stage_scores()[0] + db = ScorecardDB(path) + db.add_results([_result(score, status=status, value=value)]) + db.close() + + summary = mod.ingest(path) + assert summary["results"] == 1 + assert summary["computed_claims"] == int(counted) + assert summary["lane_stage"] == ("computed" if counted else "ingested") + out_path = tmp_path / "populations.json" + export(path, out_path=out_path, built="2026-08-29") + rows = json.loads(out_path.read_text())["rows"] + assert sum(row["latest"]["value"] is not None for row in rows) == int(counted) + + +def test_a_newer_valueless_gap_regresses_a_computed_lane(tmp_path, monkeypatch): + """A pe_gap row with no value that is newer than a claim's valued result + is the row the feed shows, so the claim no longer counts and the lane + that was computed regresses.""" + monkeypatch.setattr(mod, "sync_lane_feed", lambda *args, **kwargs: 1) + path = tmp_path / "scorecard.db" + mod.ingest(path) + score = mod.stage_scores()[0] + db = ScorecardDB(path) + db.add_results( + [ + _result( + score, + status=ComparisonStatus.CONSTRUCTED, + value=1.0, + run_id="older-run", + when="2026-08-28", + ) + ] + ) + db.close() + first = mod.ingest(path) + assert (first["computed_claims"], first["lane_stage"]) == (1, "computed") + + db = ScorecardDB(path) + db.add_results( + [ + _result( + score, + status=ComparisonStatus.PE_GAP, + value=None, + run_id="newer-run", + when="2026-08-29", + ) + ] + ) + db.close() + second = mod.ingest(path) + assert second["results"] == 1 + assert (second["computed_claims"], second["lane_stage"]) == (0, "regressed") + db = ScorecardDB(path) + lane = db.conn.execute( + "SELECT stage, detail FROM lanes WHERE lane = ?", (mod.LANE_ID,) + ).fetchone() + db.close() + assert lane["stage"] == "regressed" + assert "0 of 12 claims retain a PolicyEngine value" in lane["detail"] + + +def test_a_mixed_lane_counts_and_dates_only_valued_latest_rows(tmp_path, monkeypatch): + """Three claims with results: one valued; one whose latest row is a + newer valueless gap; and one whose newer-dated gap was inserted before + an older value, so date, not insert order, picks its latest row. Only + the first counts, the lane is dated by it, and the populations feed + agrees.""" + from scorecard_db.export_populations import export + + monkeypatch.setattr(mod, "sync_lane_feed", lambda *args, **kwargs: 1) + path = tmp_path / "scorecard.db" + mod.ingest(path) + valued, gap, reordered = mod.stage_scores()[:3] + db = ScorecardDB(path) + db.add_results( + [ + _result( + valued, + status=ComparisonStatus.CONSTRUCTED, + value=1.0, + when="2026-08-28", + ), + _result(gap, status=ComparisonStatus.PE_GAP, value=None, when="2026-08-30"), + _result( + reordered, status=ComparisonStatus.PE_GAP, value=None, when="2026-08-31" + ), + _result( + reordered, + status=ComparisonStatus.CONSTRUCTED, + value=2.0, + when="2026-08-29", + ), + ] + ) + db.close() + + summary = mod.ingest(path) + assert summary["results"] == 3 + assert (summary["computed_claims"], summary["lane_stage"]) == (1, "computed") + db = ScorecardDB(path) + lane = db.conn.execute( + "SELECT stage, detail, updated_at FROM lanes WHERE lane = ?", (mod.LANE_ID,) + ).fetchone() + db.close() + assert lane["detail"].startswith("1 of 12 claims computed — ") + assert lane["updated_at"] == "2026-08-28" + out_path = tmp_path / "populations.json" + export(path, out_path=out_path, built="2026-08-29") + rows = json.loads(out_path.read_text())["rows"] + assert sum(row["latest"]["value"] is not None for row in rows) == 1 + + def test_lane_mirror_failure_is_recoverable_by_idempotent_retry(tmp_path, monkeypatch): path = tmp_path / "scorecard.db" diff --git a/tests/test_uk_ab2025_ingest.py b/tests/test_uk_ab2025_ingest.py index 0aba629d1..b2ceb6661 100644 --- a/tests/test_uk_ab2025_ingest.py +++ b/tests/test_uk_ab2025_ingest.py @@ -12,6 +12,8 @@ import json import shutil import sqlite3 +import sys +from dataclasses import dataclass from pathlib import Path import pytest @@ -26,6 +28,7 @@ REGISTRY, REGISTRY_MARK, _DROP_BY_NAME, + _merged_twins, check_accounting, expected, ingest, @@ -393,3 +396,107 @@ def test_a_release_the_ledger_lacks_raises(): _source_model("cpag", {"source_model": "ifs_taxben"}) with pytest.raises(ValueError, match="no source_model"): _source_model("fraser_of_allander", {"source_model": ""}) + + +def test_stage_hashes_each_score_a_bounded_number_of_times(monkeypatch): + """Tallying merged republications once rescanned the kept claims for + every row and rehashed each: about 1.9 million claim-id hashes for 8,881 + rows, with one score hashed 1,147 times, which dominated a full build. + Through the whole of stage() each score is now hashed a few times (merge, + tally, kept, uniqueness gate). The bound leaves room for another linear + pass. The tally's growth itself is tested on _merged_twins below.""" + from collections import Counter + + from scorecard_db.models import ExternalScore + + hashes: Counter = Counter() + alive = [] # holds each score so no id is reused while counting + claim_id = ExternalScore.claim_id + + def counting(self): + hashes[id(self)] += 1 + alive.append(self) + return claim_id(self) + + monkeypatch.setattr(ExternalScore, "claim_id", counting) + _, acct = stage() + assert acct["drops"]["republished_twin_merged"]["rows"] > 0 + assert max(hashes.values()) <= 8 + assert sum(hashes.values()) <= 4 * acct["read"] + + +class _CountedId(str): + """A claim id whose comparisons run in Python, so a tracer sees them.""" + + __hash__ = str.__hash__ + + def __eq__(self, other): + return str.__eq__(self, other) + + def __ne__(self, other): + return str.__ne__(self, other) + + +@dataclass +class _Row: + """Stands in for an ExternalScore: a claim id, a family, and the + dataclass __eq__ that ExternalScore also has.""" + + cid: str + publication: dict + + def claim_id(self): + return _CountedId(self.cid) + + +def _printed_twice(n: int) -> tuple[list, list]: + """n claims, each printed in two families, as merge_republications + leaves them: the second printing kept, kept rows in first-seen order.""" + mine, kept = [], [] + for i in range(n): + first = _Row(f"c{i}", {"family": "figure"}) + second = _Row(f"c{i}", {"family": "table"}) + mine += [first, second] + kept.append(second) + return mine, kept + + +def _traced_steps(fn, *args) -> int: + """Python-level work: every call, line and return the tracer sees.""" + steps = [0] + + def tracer(frame, event, arg): + steps[0] += 1 + return tracer + + previous = sys.gettrace() + sys.settrace(tracer) + try: + fn(*args) + finally: + sys.settrace(previous) + return steps[0] + + +def test_merged_twins_charge_the_last_row_s_family(): + """A merged twin is tallied once, the kept row never; the tally goes to + the family of the last row with that claim id, as before the rewrite. + #264 asks whether it should be the twin's own family.""" + a_fig = _Row("a", {"family": "figure"}) + b = _Row("b", {"family": "figure"}) + a_tab = _Row("a", {"family": "table"}) + assert _merged_twins([a_fig, b, a_tab], [a_tab, b]) == ["table"] + assert _merged_twins([a_tab, b, a_fig], [a_tab, b]) == ["figure"] + assert _merged_twins([a_fig, b], [a_fig, b]) == [] + + +def test_the_twin_tally_grows_linearly(): + """Quadrupling the rows must roughly quadruple the tally's work, not + multiply it by sixteen. The tracer sees every Python step, including the + id comparisons and the rows' dataclass __eq__. So a scan of kept rows per + row is caught however it is written: rehashing, cached ids, identity + tests, or `in`. A scan done wholly in C over plain ints (say ids from + id()) would slip past.""" + small = _traced_steps(_merged_twins, *_printed_twice(250)) + large = _traced_steps(_merged_twins, *_printed_twice(1000)) + assert large <= 6 * small, (small, large) diff --git a/tests/test_uk_childcare_100k.py b/tests/test_uk_childcare_100k.py index f0a5cf3a9..bf6af0cd6 100644 --- a/tests/test_uk_childcare_100k.py +++ b/tests/test_uk_childcare_100k.py @@ -2834,3 +2834,122 @@ def test_exported_feed_rows_state_the_lane_signs_and_history(): assert len(unscored) == 12 assert {r["source"] for r in unscored} == {lane.CENTAX} assert all(r["conditions"].get("pe_missing") for r in unscored) + + +_REGISTRY_READ = ( + "SELECT claim_id FROM external_scores " + "WHERE json_extract(publication, '$.registry') = ?" +) + + +def _rows_per_claim(path) -> dict: + conn = sqlite3.connect(path) + try: + return { + "external_scores": Counter( + r[0] for r in conn.execute("SELECT claim_id FROM external_scores") + ), + "pe_results": Counter( + tuple(r) + for r in conn.execute("SELECT claim_id, run_id FROM pe_results") + ), + "diagnoses": Counter( + r[0] for r in conn.execute("SELECT claim_id FROM diagnoses") + ), + } + finally: + conn.close() + + +@pytest.mark.parametrize("late", [None, 0, 1]) +def test_overlapping_ingests_leave_what_one_ingest_leaves(tmp_path, monkeypatch, late): + """Two first ingests that open the database together must leave the + rows one ingest leaves: one row per claim in external_scores and + diagnoses, and each claim's result once per run. + + Each ingest holds at its registry read until the other has either read + or started BEGIN IMMEDIATE. Without the lock the two reads always meet, + however late either ingest starts, so both read an empty registry. With + the lock, the second ingest is waiting on the first's transaction, so + neither deadlocks. A wait that times out fails the test rather than + letting the reads miss each other. `late` starts one ingest half a + second after the other. The lane mirror is stubbed, so this covers the + database rows, not the shared lanes.json write (#262).""" + import threading + import time + from concurrent.futures import ThreadPoolExecutor + + from scorecard_db import ingest_harvest + + monkeypatch.setattr(ingest_harvest, "sync_lane_feed", lambda *a, **k: 1) + once = tmp_path / "once.db" + lane.ingest(once) + want = _rows_per_claim(once) + assert set(want["external_scores"].values()) == {1} + assert set(want["pe_results"].values()) == {1} + + path = tmp_path / "overlap.db" + lane.ScorecardDB(path).close() + opened = threading.Barrier(2, timeout=30) + state = threading.Condition() + read = [False, False] + locking = [False, False] + met = [] + local = threading.local() + + def mark(flags): + with state: + flags[local.i] = True + state.notify_all() + + class PausingConn: + def __init__(self, conn): + self._conn = conn + + def __getattr__(self, name): + return getattr(self._conn, name) + + def __enter__(self): + return self._conn.__enter__() + + def __exit__(self, *exc): + return self._conn.__exit__(*exc) + + def execute(self, sql, *args): + if sql == "BEGIN IMMEDIATE": + mark(locking) + cursor = self._conn.execute(sql, *args) + if sql == _REGISTRY_READ: + rows = cursor.fetchall() + mark(read) + other = 1 - local.i + with state: + met.append( + state.wait_for( + lambda: read[other] or locking[other], timeout=30 + ) + ) + return iter(rows) + return cursor + + class PausingDB(lane.ScorecardDB): + def __init__(self, p): + super().__init__(p) + self.conn = PausingConn(self.conn) + opened.wait() + if local.i == late: + time.sleep(0.5) + + monkeypatch.setattr(lane, "ScorecardDB", PausingDB) + + def run(i): + local.i = i + return lane.ingest(path) + + with ThreadPoolExecutor(max_workers=2) as pool: + futures = [pool.submit(run, i) for i in (0, 1)] + for future in futures: + future.result() + assert read == [True, True] + assert met == [True, True] + assert _rows_per_claim(path) == want