"""State data study: filing histories of a state's retirement plans, 2009-2025 (first run: Ohio, 2026-11-03). Version 4 (2026-11-04), after the second prepublication audit (v3 after the first); 4.1 runs many states in one pass (PRD 5.133), rules unchanged: Ohio's files are byte-identical. Every published figure comes from this file's outputs. v4 changes: final status read from the latest report; a transfer counts as moving the plan only if it carried at least half the plan's assets; a receiving plan named with an employer-ID typo is corrected when the sender's own employer files the matching incoming transfer; a later record under the same employer ID and plan number that files recently counts as the plan continuing; new numbers are read from the year before the last report to two years after it. Unit: a plan record as the index resolves it (one identity per employer ID + plan number, split where effective date and name show a different plan; src/build_index.py). Not a count of distinct legal plans across successors. Cohort: records with a Form 5500 or 5500-SF report for a plan year 2009-2025 (window enforced here), at least 100 participants (total_partcp) in some report in that window, pension codes present, a two-letter sponsor state. State = plans.state, the sponsor's mailing state on the record's latest filing. Latest status (the last report in the window): recent last report 2023-2025 and it is not a final report final the last report is a final report no_recent last report 2022 or earlier and not a final report Events (any year unless said): pbgc matched to PBGC's trusteed-plan list terminal transfer a Schedule H line 5b / SF transfer naming a receiving plan, in the last report's plan year or the year before, whose amounts add up to at least half the start-of-year net assets of that year's report Category, first match wins (status and events are also cross-tabbed in summary.json): pbgc PBGC trusteed moved terminal transfer, and the last report shows net assets observed and <= $100,000 at year end recent latest status recent (includes plans that transferred part of their assets earlier) same_number_later a later record under the same employer ID and plan number has a report for 2023-2025 (a rename or an index split: the plan is active under its original number) new_number a renumbered_or_new_sponsor edge from the last report's year minus one to plus two moved_unverified terminal transfer, but year-end net assets missing or above $100,000, or no amount reported (a transfer carrying under half the assets is not a move: the plan falls to the next category) final the last report is a final report no_recent none of the above Not active under the original number = every category except recent and same_number_later. People: line 6c of the full Form 5500 (retired or separated participants entitled to future benefits). The 5500-SF has no such line, so a record with only short-form reports has no count (missing, never zero). For moved plans the count comes from the latest full-form report before the transfer year; for others, the latest full-form report. Each count keeps its plan year. Sums are of plan-level counts and can include one person in several plans. Receiving plans: the sending plan's filing names them (edges.note keeps that text). edges.amount_in is the receiving plan's TOTAL incoming transfers that year or the next or previous (src/plantrace/resolve.py pick_receiver): context, not confirmation that a particular sender's money arrived. Typo correction: when the named receiver reports no incoming transfer and another plan under the sender's own employer ID reports one within 1% of the amount sent, in the transfer year or the next, that plan is the receiver (ledger columns dst_plan_as_filed, receiver_corrected). Outputs in OUT_DIR: summary.json totals, coverage, cross-tab, reconciliation, sector table (state and national), all numbers transfers_ledger.csv every terminal transfer of the state's moved / moved_unverified records, all destinations, with filing acknowledgement IDs categories_by_state.csv Usage: python -I tools/state_study.py DB OUT_DIR [STATE ...|ALL] (one state: files in OUT_DIR; several: OUT_DIR//) """ import csv import json import os import sqlite3 import sys db, out = sys.argv[1], sys.argv[2] STATES = [s.upper() for s in sys.argv[3:]] or ["OH"] PY0, PY1, RECENT, EMPTY = 2009, 2025, 2023, 100_000 c = sqlite3.connect(f"file:{db}?mode=ro", uri=True) c.executescript(f""" create temp table w as select plan_id, min(py) as first_py, max(py) as last_py, max(coalesce(total_partcp, 0)) as peak, max(case when final in ('1', 1, 'Y', 'y', 'true') then 1 else 0 end) as any_final from plan_years where py between {PY0} and {PY1} group by plan_id; create temp table u as select p.plan_id, p.ein, p.pn, p.state, p.biz_code, p.plan_name, p.sponsor, w.first_py, w.last_py, w.any_final from plans p join w using (plan_id) where w.peak >= 100 and p.pension_codes is not null and length(p.state) = 2 and p.state glob '[A-Z][A-Z]'; create index tu on u(plan_id); create temp table lastobs as select y.plan_id, y.net_assets_eoy as eoy, y.ack_id, (y.final = '1') as last_final from plan_years y join u on u.plan_id = y.plan_id and y.py = u.last_py where y.rowid = (select max(rowid) from plan_years z where z.plan_id = y.plan_id and z.py = y.py); create index tlo on lastobs(plan_id); create temp table tt0 as select e.src_plan as plan_id, min(e.py) as t_py, sum(coalesce(e.amount_out, 0)) as out_sum from edges e join u on u.plan_id = e.src_plan where e.kind = 'transfer' and e.py between u.last_py - 1 and u.last_py group by e.src_plan; create temp table tt as select tt0.*, (select y.net_assets_boy from plan_years y where y.plan_id = tt0.plan_id and y.py = tt0.t_py order by y.rowid desc limit 1) as boy_t from tt0; -- big: the amounts reported carry at least half the start-of-year assets; noamt: a receiver named with no amount create temp table ttc as select plan_id, t_py, (out_sum > 0 and out_sum >= 0.5 * coalesce(boy_t, 0)) as big, (out_sum = 0) as noamt from tt; create temp table rn as select distinct e.src_plan as plan_id from edges e join u on u.plan_id = e.src_plan where e.kind = 'renumbered_or_new_sponsor' and e.py between u.last_py - 1 and u.last_py + 2; create temp table sn as select distinct u.plan_id from u join plans p2 on p2.ein = u.ein and p2.pn = u.pn and p2.plan_id != u.plan_id where p2.first_py > u.first_py and exists (select 1 from plan_years y where y.plan_id = p2.plan_id and y.py between {RECENT} and {PY1}); create index tsn on sn(plan_id); create temp table pb as select distinct plan_id from pbgc_match; create index ttt on ttc(plan_id); create index trn on rn(plan_id); create index tpb on pb(plan_id); create temp table f as select u.*, tt.t_py, lo.eoy, tt.big, tt.noamt, case when lo.last_final = 1 then 'final' when u.last_py >= {RECENT} then 'recent' else 'no_recent' end as status, case when pb.plan_id is not null then 'pbgc' when tt.big = 1 and lo.eoy is not null and lo.eoy <= {EMPTY} then 'moved' when u.last_py >= {RECENT} and coalesce(lo.last_final, 0) = 0 then 'recent' when sn.plan_id is not null then 'same_number_later' when rn.plan_id is not null then 'new_number' when tt.big = 1 or tt.noamt = 1 then 'moved_unverified' when lo.last_final = 1 then 'final' else 'no_recent' end as cat from u left join lastobs lo using (plan_id) left join ttc tt using (plan_id) left join rn using (plan_id) left join pb using (plan_id) left join sn using (plan_id); create index tf on f(plan_id); create temp table ppl as select f.plan_id, (select y.sep_fut from plan_years y where y.plan_id = f.plan_id and y.form = '5500' and y.sep_fut is not null and y.py between {PY0} and (case when f.cat in ('moved', 'moved_unverified') then f.t_py - 1 else f.last_py end) order by y.py desc, y.rowid desc limit 1) as n, (select y.py from plan_years y where y.plan_id = f.plan_id and y.form = '5500' and y.sep_fut is not null and y.py between {PY0} and (case when f.cat in ('moved', 'moved_unverified') then f.t_py - 1 else f.last_py end) order by y.py desc, y.rowid desc limit 1) as n_py from f; create index tp on ppl(plan_id); """) def rows(sql, *a): cur = c.execute(sql, a) cols = [d[0] for d in cur.description] return [dict(zip(cols, r)) for r in cur.fetchall()] def emit(ST, out): """One state's three files in OUT. The national tables above are built once for every state.""" os.makedirs(out, exist_ok=True) S = {"state": ST, "window": [PY0, PY1], "empty_threshold": EMPTY, "unit": "plan record (index identity)"} S["categories"] = rows("""select cat, count(*) as plans, sum(ppl.n is not null) as with_count, sum(coalesce(ppl.n, 0)) as people_observed from f join ppl using (plan_id) where f.state = ? group by cat order by plans desc""", ST) S["total_plans"] = sum(r["plans"] for r in S["categories"]) ACTIVE = ("recent", "same_number_later") S["not_active_original_number"] = S["total_plans"] - sum(r["plans"] for r in S["categories"] if r["cat"] in ACTIVE) S["status_by_category"] = rows("select cat, status, count(*) as plans from f where state = ? group by 1, 2", ST) S["no_recent_split"] = rows(f"""select case when exists (select 1 from plan_years y join plans p2 on p2.plan_id = y.plan_id where p2.ein = f.ein and y.py > f.last_py and y.py <= {PY1}) then 'later_report_same_ein' else 'no_later_report_same_ein' end as split, count(*) as plans, sum(ppl.n is not null) as with_count, sum(coalesce(ppl.n, 0)) as people_observed from f join ppl using (plan_id) where f.state = ? and f.cat = 'no_recent' group by 1""", ST) led = rows("""select f.plan_id, f.ein, f.pn, f.sponsor, f.plan_name, f.cat, f.last_py, f.eoy, ppl.n as people, ppl.n_py as people_py, e.py as transfer_py, e.dst_plan, d.ein as to_ein, d.pn as to_pn, d.sponsor as to_sponsor, d.plan_name as to_plan_name, d.state as to_state, e.amount_out, e.amount_in as receiver_total_in, e.note, (select y.ack_id from plan_years y where y.plan_id = f.plan_id and y.py = e.py order by y.rowid desc limit 1) as src_ack, (select y.ack_id from plan_years y where y.plan_id = e.dst_plan and y.py in (e.py, e.py + 1) order by coalesce(y.transfers_to, 0) > 0 desc, y.py, y.rowid desc limit 1) as dst_ack from f join ppl using (plan_id) join edges e on e.src_plan = f.plan_id and e.kind = 'transfer' and e.py between f.last_py - 1 and f.last_py left join plans d on d.plan_id = e.dst_plan where f.state = ? and f.cat in ('moved', 'moved_unverified') order by f.plan_id, e.py""", ST) # employer-ID typos on the receiver line: the sender's own employer files the matching incoming transfer for r in led: r["dst_plan_as_filed"], r["receiver_corrected"] = r["dst_plan"], 0 if r["amount_out"] and not (r["receiver_total_in"] or 0) > 0: hit = c.execute("""select p.plan_id, p.ein, p.pn, p.sponsor, p.plan_name, p.state, (select y2.ack_id from plan_years y2 where y2.plan_id = p.plan_id and y2.py = y.py order by y2.rowid desc limit 1), y.transfers_to from plans p join plan_years y on y.plan_id = p.plan_id where p.ein = ? and p.plan_id != ? and y.py in (?, ?) and y.transfers_to > 0 and abs(y.transfers_to - ?) <= 0.01 * ? order by abs(y.transfers_to - ?) limit 1""", (r["ein"], r["plan_id"], r["transfer_py"], r["transfer_py"] + 1, r["amount_out"], r["amount_out"], r["amount_out"])).fetchone() if hit: (r["dst_plan"], r["to_ein"], r["to_pn"], r["to_sponsor"], r["to_plan_name"], r["to_state"], r["dst_ack"], r["receiver_total_in"]) = hit r["receiver_corrected"] = 1 S["receivers_corrected"] = sum(r["receiver_corrected"] for r in led) with open(os.path.join(out, "transfers_ledger.csv"), "w", newline="") as fh: w = csv.DictWriter(fh, fieldnames=list(led[0].keys()) if led else ["plan_id"]) w.writeheader() w.writerows(led) moved = {} for r in led: if r["cat"] != "moved": continue m = moved.setdefault(r["plan_id"], {"dests": 0, "named": 0, "other_ein": 0, "out_of_state": 0, "rcv_in": 0, "people": r["people"]}) m["dests"] += 1 m["named"] += r["dst_plan"] is not None m["other_ein"] += bool(r["to_ein"] and r["to_ein"] != r["ein"]) m["out_of_state"] += bool(r["to_state"] and r["to_state"] != ST) m["rcv_in"] += bool(r["receiver_total_in"] and r["receiver_total_in"] > 0) mv = list(moved.values()) S["moved_reconciliation"] = { "unit": "distinct sending plan records in category moved", "moved": len(mv), "with_a_named_receiving_record": sum(1 for m in mv if m["named"]), "with_more_than_one_destination": sum(1 for m in mv if m["dests"] > 1), "any_destination_other_ein": sum(1 for m in mv if m["other_ein"]), "any_destination_other_ein_out_of_state": sum(1 for m in mv if m["other_ein"] and m["out_of_state"]), "any_destination_reported_incoming_transfers": sum(1 for m in mv if m["rcv_in"]), "people_observed_pre_transfer_other_ein": sum(m["people"] or 0 for m in mv if m["other_ein"]), "other_ein_with_count": sum(1 for m in mv if m["other_ein"] and m["people"] is not None), } NAICS = {"62": "Health care and social assistance", "31": "Manufacturing", "32": "Manufacturing", "33": "Manufacturing"} def sector_table(where, *a): out_rows = {} for r in rows(f"select substr(biz_code, 1, 2) as n2, cat, count(*) as plans from f where {where} group by 1, 2", *a): k = NAICS.get(r["n2"] or "", r["n2"] or "missing") t = out_rows.setdefault(k, {"sector": k, "plans": 0, "not_recent": 0, "moved": 0}) t["plans"] += r["plans"] t["not_recent"] += r["plans"] if r["cat"] not in ACTIVE else 0 t["moved"] += r["plans"] if r["cat"] == "moved" else 0 return sorted(out_rows.values(), key=lambda t: -t["plans"]) S["sectors_state"] = sector_table("state = ?", ST) S["sectors_all_states"] = sector_table("1") with open(os.path.join(out, "categories_by_state.csv"), "w", newline="") as fh: w = csv.writer(fh) w.writerow(["state", "category", "plans", "with_count", "people_observed"]) w.writerows(c.execute("""select f.state, f.cat, count(*), sum(ppl.n is not null), sum(coalesce(ppl.n, 0)) from f join ppl using (plan_id) group by 1, 2""").fetchall()) json.dump(S, open(os.path.join(out, "summary.json"), "w"), indent=1, default=str) print(json.dumps({k: S[k] for k in ("total_plans", "not_active_original_number", "receivers_corrected", "categories", "moved_reconciliation")}, indent=1, default=str)) return S if STATES == ["ALL"]: STATES = [r[0] for r in c.execute("select distinct state from f order by 1")] for st in STATES: emit(st, out if len(STATES) == 1 else os.path.join(out, st))