Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions nz/ingest_official_budget_scores.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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 = ("
Expand Down Expand Up @@ -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),
Expand Down
28 changes: 18 additions & 10 deletions scorecard_db/ingest_harvest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -184,24 +185,27 @@ 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)
lane_of: dict[str, str] = {}
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
Expand All @@ -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 "")

Expand Down
39 changes: 27 additions & 12 deletions scorecard_db/ingest_uk_ab2025.py
Original file line number Diff line number Diff line change
Expand Up @@ -1033,25 +1033,40 @@ 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
raise ValueError("accounting does not close")
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]}
Expand Down
85 changes: 47 additions & 38 deletions scorecard_db/ingest_uk_childcare_100k.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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


Expand Down
Loading
Loading