From de72882f645b984f4519542792a8bae5975b0bdc Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 18 Nov 2026 08:00:20 -0500 Subject: [PATCH 1/9] Add policybench_calculator: the tool pilot's calculator as an importable package policybench_calculator/core.py is a verbatim copy of the calculator inside scripts/tool_pilot_argon.py (schema and descriptions per feature set, the validator, the engine call, explanations, the board's pinned engine and reform, the worker pool): the dependency closure of 19 entry points, 102 module-level definitions, written by scripts/sync_calculator_core.py. It is a copy, not a move, because the confirmatory runner refuses to start unless scripts/tool_pilot_argon.py and policybench/ are its treatment commit's (confirmatory_run.py, TREATMENT_PATHS). Nothing under those paths changes here. tests/test_calculator_core.py holds the two copies together without the engine: core.py is the sync script's output for the harness as it stands; every definition has the harness's syntax tree; both build the same tool schema for all 96 feature sets on two stated engines, and the schemas hash to what the development runs recorded; both read 3,000 generated calls alike (malformed ones, and written ones the validator accepts, notes or refuses), run a request alike on a fake engine, and frame pool messages alike. Co-Authored-By: Claude Fable 5.2 --- policybench_calculator/__init__.py | 6 + policybench_calculator/core.py | 2013 ++++++++++++++++++++++++++++ scripts/sync_calculator_core.py | 284 ++++ tests/test_calculator_core.py | 658 +++++++++ 4 files changed, 2961 insertions(+) create mode 100644 policybench_calculator/__init__.py create mode 100644 policybench_calculator/core.py create mode 100644 scripts/sync_calculator_core.py create mode 100644 tests/test_calculator_core.py diff --git a/policybench_calculator/__init__.py b/policybench_calculator/__init__.py new file mode 100644 index 00000000..43fae0d7 --- /dev/null +++ b/policybench_calculator/__init__.py @@ -0,0 +1,6 @@ +"""The PolicyBench household calculator, apart from the harness that tests models. + +``core`` is the calculator the tool pilot gives a model: a verbatim copy of +the one in ``scripts/tool_pilot_argon.py``, kept exact by +``scripts/sync_calculator_core.py`` and ``tests/test_calculator_core.py``. +""" diff --git a/policybench_calculator/core.py b/policybench_calculator/core.py new file mode 100644 index 00000000..ae51428a --- /dev/null +++ b/policybench_calculator/core.py @@ -0,0 +1,2013 @@ +"""The household calculator the PolicyBench tool pilot gives a model. + +Written by ``scripts/sync_calculator_core.py``; do not edit it by hand. + +This module is a verbatim copy of the calculator inside +``scripts/tool_pilot_argon.py``: the tool's schema and descriptions for each +feature set, the validator (names, labels, placement, overrides, the flat +household), the engine call, the explanations, the board's pinned engine and +convention reform, and the worker pool that runs each call in its own process +under a timeout. Nothing here calls a model. + +Why a copy. The v2 confirmatory runner refuses to start unless +``scripts/tool_pilot_argon.py`` and the ``policybench`` package are its +treatment commit's (``scripts/confirmatory_run.py``, ``TREATMENT_PATHS``), so +the harness cannot import this module until that run is over. Until then both +hold the same code. ``tests/test_calculator_core.py`` fails if this file is +not the sync script's output for the harness as it stands, if any definition +here differs from the harness's (compared by AST), or if the two build +different tool schemas or read a call differently. To change the calculator, +change the harness and run the sync script; once the treatment pin is lifted, +the harness imports this module and its own copy goes. + +Everything below the imports is the harness's text, in the harness's order. +""" + +from __future__ import annotations + +import contextlib +import copy +import difflib +import functools +import hashlib +import importlib.metadata +import importlib.util +import json +import math +import multiprocessing as mp +import os +import queue +import re +import sys +import threading +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Callable, Mapping + +ROOT = Path(__file__).resolve().parents[1] +SNAPSHOT = ( + ROOT + / "paper/snapshot/20260501/runs/us_full_run_20260612_policyengine_4_16_1_populace" +) +FIX_MODULE = ROOT / "reference_audit/2026-09-28/fixes/latest_final.py" +# The bytes the 2.41.0 references were built with: the sidecar's 2026-10-13 +# engine_upgrade revision pins latest_final.py to this sha256, and +# verify_fix_pins checks it and every module it composes against that revision. +FIX_MODULE_SHA256 = "dbbdd228b99933c6f336af97970821c25c863a18606285e8d6d9ffb3bc9af78e" + +YEAR = 2026 +REFERENCE_ENGINE = "2.41.0" + +TOOL_NAME = "calculate_household" + +TOOL_TIMEOUT_SECONDS = 60 +WORKER_START_TIMEOUT_SECONDS = 900 + +POOL_UNAVAILABLE = "pool_unavailable" + +MAX_PEOPLE = 16 +MAX_UNITS_PER_GROUP = 16 +MAX_VARIABLES = 40 +MAX_SITUATION_CHARS = 200_000 +MAX_PROBLEMS = 20 +MAX_MESSAGE_CHARS = 2_000 +PERIOD_RE = re.compile(r"^(?:20[0-4]\d)(?:-(?:0[1-9]|1[0-2]))?$") + +GROUPS = { + "tax_units": "tax_unit", + "spm_units": "spm_unit", + "families": "family", + "marital_units": "marital_unit", + "households": "household", +} +ENTITY_GROUP = {"person": "people", **{v: k for k, v in GROUPS.items()}} + +# The calculator's features, each on or off, so a study can change one at a +# time (Max, 2026-10-23: "measuring this as an experiment could be +# publishable"; "do all these tests with a cheap model"): +# - names: a name written with spaces, or a benchmark output key, is read as +# its engine variable; +# - labels: a fact written under the label the prompt gives it (a prompt +# labels some facts in words, e.g. employment_income as "gross wages and +# salaries"; policybench.prompts.INPUT_LABEL_OVERRIDES) is read as its +# variable, and a fact the reference also sets under another name +# (policybench.scenarios.PE_INPUT_ALIASES: usual weekly hours) is set there +# too; +# - placement: an input set on another entity moves to the one unit holding +# its people; +# - overrides: a realized contribution is read as its _desired input, and an +# input that replaces a formula is flagged; +# - explain: `explain` traces up to three variables; +# - concise: an explanation is brief unless `detail` is "full"; +# - flat: the household is described as people with roles and facts +# (`household`), and the tool builds its units as the benchmark does. +# "pe2" is tool version 2 (names, placement, overrides and explain); "pe3" is +# all seven. Any other set +# runs as an arm named "pe:" plus its features joined by "+", e.g. +# "pe:names+flat". +NAMES, LABELS, PLACEMENT, OVERRIDES, EXPLAIN, CONCISE, FLAT = ( + "names", + "labels", + "placement", + "overrides", + "explain", + "concise", + "flat", +) +TOOL_FEATURES = (NAMES, LABELS, PLACEMENT, OVERRIDES, EXPLAIN, CONCISE, FLAT) +V2_FEATURES = frozenset({NAMES, PLACEMENT, OVERRIDES, EXPLAIN}) +FEATURES_BY_ARM = { + "pe": frozenset(), + "web+pe": frozenset(), + "pe2": V2_FEATURES, + "pe3": frozenset(TOOL_FEATURES), + "web+pe3": frozenset(TOOL_FEATURES), +} +_FEATURE_ARM = re.compile(r"^pe:([a-z]+(?:\+[a-z]+)*)$") + + +def arm_features(arm: str) -> frozenset | None: + """The calculator features an arm offers, or None for an arm without the + calculator. Refuses an unknown feature, or concise without explain.""" + if arm in FEATURES_BY_ARM: + return FEATURES_BY_ARM[arm] + match = _FEATURE_ARM.match(arm or "") + if match is None: + return None + features = frozenset(match.group(1).split("+")) + unknown = sorted(features - set(TOOL_FEATURES)) + if unknown: + raise SystemExit( + f"unknown tool features {unknown}; the features are {TOOL_FEATURES}" + ) + if CONCISE in features and EXPLAIN not in features: + raise SystemExit("the concise feature needs explain") + return features + + +# The engine version the notices and the tool description state: the board's +# (set by command_run), so a household set on a newer engine says so. The +# frozen board's 2.41.0 leaves every text byte for byte as before. +_STATED_ENGINE = {"version": REFERENCE_ENGINE} + + +def set_stated_engine(version: str) -> None: + _STATED_ENGINE["version"] = version + + +@contextlib.contextmanager +def stating_engine(version: str): + """The texts as a run on `version` sent them, for a check that rebuilds a + notice; the stated engine is restored afterwards.""" + before = _STATED_ENGINE["version"] + set_stated_engine(version) + try: + yield + finally: + set_stated_engine(before) + + +def engine_text(text: str) -> str: + return text.replace( + f"policyengine-us {REFERENCE_ENGINE}", + f"policyengine-us {_STATED_ENGINE['version']}", + ) + + +V2_PILOT_DEFINITIONS = ( + ( + re.compile( + r"whether (.+?) is eligible for Medicaid under PolicyEngine rules, " + r"not whether they are currently enrolled \(1 if yes, 0 if no\)" + ), + "whether {who} is eligible for Medicaid in 2026 under federal and state " + "Medicaid rules, not whether they are currently enrolled; the Medicare " + "Savings Programs (QMB, SLMB and QI), which help only with Medicare costs, " + "do not count (1 if yes, 0 if no)", + ), + ( + re.compile( + r"whether (.+?) is eligible for CHIP under PolicyEngine rules, " + r"not whether they are currently enrolled \(1 if yes, 0 if no\)" + ), + "whether {who} is eligible for CHIP (the Children's Health Insurance " + "Program, including any CHIP coverage the state gives pregnant women) in " + "2026 under federal and state rules, not whether they are currently " + "enrolled; someone eligible for Medicaid is not CHIP-eligible (1 if yes, " + "0 if no)", + ), + ( + re.compile( + r"whether PolicyEngine returns positive annual free school meal support " + r"for the household \(1 if yes, 0 if no; reduced-price meals do not " + r"count as 1\)" + ), + "whether the household's children get free school meals in 2026: treat " + "everyone aged 5 to 17 as attending a public K-12 school that takes part " + "in the National School Lunch and School Breakfast Programs, and count " + "meals at no charge to the family, whether through federal free-meal " + "eligibility or a state program that makes both breakfast and lunch free " + "for all students or pays the reduced-price charge for both breakfast and " + "lunch (1 if yes, 0 if no; 0 if no one is aged 5 to 17; reduced-price " + "meals do not count as 1)", + ), + ( + re.compile( + r"whether PolicyEngine returns positive annual reduced-price school meal " + r"support for the household \(1 if yes, 0 if no; free meals do not " + r"count as 1\)" + ), + "whether the household's children get reduced-price school meals in 2026: " + "treat everyone aged 5 to 17 as attending a public K-12 school that takes " + "part in the National School Lunch and School Breakfast Programs, and " + "count meals at the federal reduced price that no state program makes " + "free (1 if yes, 0 if no; 0 if no one is aged 5 to 17; free meals do not " + "count as 1)", + ), +) +# d1029 (Max, 2026-11-01): the US income tax outputs cover the head and spouse's +# return only. The reference has no second tax unit, so a dependent's own return +# is in no reference, and household sets drop households where a dependent has +# income or a loss (policybench.scenarios._households_with_dependent_return_income). +HEAD_SPOUSE_RETURN = ( + "Cover only the return of the head and spouse, not any return a dependent files" +) +# d1971 (Max, 2026-11-01): the EITC comes from 26 USC 32's formula, as d1263 kept +# the rate schedule over the Tax Table. 32(f) prescribes the IRS table, which +# differs by a few dollars ($3,183 against $3,179.76 for one pilot household). +STATE_USES_EITC_FORMULA = ( + "Where a state amount depends on the federal EITC, use the EITC from the " + "formula in 26 U.S.C. 32" +) + +# d1263 (Max, 2026-10-13): keep the section 1 rate schedule for federal income +# tax, and state that convention in the v2 prompt. A web arm finds the IRS Tax +# Table: in the 2026-10-21 trial GPT-6 Sol answered scenario_000 from it, $1.45 +# off the schedule reference. +V2_PILOT_CONVENTIONS = ( + ( + re.compile( + r"(federal individual income tax after nonrefundable credits and before " + r"refundable credits\. This subtracts nonrefundable credits actually " + r"used, including CDCC and the nonrefundable portion of CTC or other " + r"credits when applicable; it does not subtract EITC or refundable " + r"portions of credits such as refundable CTC)" + ), + "{who}. Compute regular income tax from the section 1 tax rate schedules, " + "to the cent, even where the Form 1040 instructions would use the Tax " + f"Table. {HEAD_SPOUSE_RETURN}", + ), + ( + # The refundable CTC depends on the tax liability, so the schedule + # choice can move this output too. + re.compile( + r"(total refundable federal income tax credits, including EITC and " + r"refundable portions of credits such as refundable CTC when " + r"applicable; exclude the ACA Premium Tax Credit)" + ), + "{who}. Where a credit depends on income tax liability, compute that " + "liability from the section 1 tax rate schedules, not the Tax Table. " + "Compute the EITC from the formula in 26 U.S.C. 32, to the cent, not from " + f"the IRS EIC table. {HEAD_SPOUSE_RETURN}", + ), + ( + # policyengine-us 2.41.0's state_income_tax_before_refundable_credits + # list adds id_pbf for Idaho ("Form 40 permanent building fund tax, + # added before refundable credits"); no other state adds such a tax. + # GPT-6 Sol's tool answers for scenario_007 were $10 short without it. + re.compile( + r"(state individual income tax after nonrefundable credits and before " + r"refundable credits, excluding local income and payroll taxes)" + ), + "{who}; include Idaho's $10 permanent building fund tax where it applies. " + f"{STATE_USES_EITC_FORMULA}. {HEAD_SPOUSE_RETURN}", + ), + ( + re.compile(r"(total refundable state individual income tax credits)"), + f"{{who}}. {STATE_USES_EITC_FORMULA}. {HEAD_SPOUSE_RETURN}", + ), + ( + # The reference rule (reference sidecar, quoted in each + # reference_audit/2026-09-28/fixes/latest_c_* module): "a scored + # reference follows from the stated facts and from law published before + # the 2026-07-03 reference freeze". Where no 2026 amount was published by + # then, the reference holds the last one published before it: California's + # 2025 indexed amounts, Idaho's zero-rate thresholds, the IRS 2025 + # optional sales tax tables, and some Maryland, Michigan and Minnesota + # amounts. SNAP holds the FY2026 schedule (allotments, deductions, + # utility allowances, asset limits) for October to December; "Not held: + # the poverty guideline", so income limits move to the 2026 guideline in + # October. Web arms had applied SNAP's FY2027 schedule, published in + # August 2026 (GPT-6 Sol, scenarios 008 and 012). + # + # d1972(4) (Max, 2026-11-01): Louisiana is the one amount stated outright. + # policyengine-us 2.60.4 carries RIB 26-019's $12,838 and $25,676, from + # 2026-09-28; before the freeze LDR published only the provisional + # $12,875 and $25,750 (reference_audit/2026-10-05-louisiana). The fallback + # would send a careful reader to those, as d994 foresaw; the 20-household + # pilot's models answered from $25,750 (mt_004). + # + # Session call (judge triage Pattern B): engine defaults make rental, + # farm rent, partnership and S corporation income qualified business + # income, and the `_would_be_qualified` flags are never prompted, so the + # convention is stated. Setting the flags false instead would part the + # references from what a calculator call returns on the same facts. + re.compile( + r"(Do not infer unlisted income, expenses, assets, benefit receipt, " + r"rent, or health coverage\.)" + ), + "{who} Apply the law and program parameters published before July 3, " + "2026. Where a 2026 amount had not been published by then, use the latest " + "amount published before that date (for example, a state's 2025 " + "inflation-adjusted amounts, or the IRS's 2025 optional sales tax " + "tables). For SNAP, keep the fiscal year 2026 allotments, deductions, " + "utility allowances and asset limits through December 2026; the income " + "limits use the 2026 HHS poverty guidelines from October 2026. Louisiana's " + "2026 standard deduction is $12,838 for single and separate filers and " + "$25,676 for all other filers, not the provisional $12,875 and $25,750 in " + "its withholding tables and estimated-tax worksheet; an amount an agency " + "labels provisional or estimated is not a published return amount. Treat " + "rental, farm rent, partnership and S corporation income as qualified " + "business income under section 199A.", + ), + ( + # d1970 (Max, 2026-11-01): policyengine-us defaults immigration_status + # and ssn_card_type to CITIZEN, and the prompt's rule makes unlisted + # statuses false. The references keep the default and set it explicitly + # (household_set.situation_for). 5 of the 14 disputed verdicts in the + # 20-household pilot turned on this. + re.compile(r"(fact, boolean, or status input as false\.)"), + "{who} Everyone listed is a U.S. citizen with a valid Social Security " + "number issued before the return's due date, unless stated otherwise.", + ), + ( + # d1972(2) (Max, 2026-11-01): a period for every amount. Read as monthly, + # mt_017's $1,920 rent moved DC SNAP from $1,284 to $3,576. + re.compile( + r"Gross wage and salary amounts are annual totals, including any " + r"overtime pay;" + ), + "Every dollar amount is an annual total, including rent and other " + "expenses, except asset and vehicle values, loan balances and the basis of " + "business property; gross wages and salaries include any overtime pay;", + ), + ( + # d1972(3) (Max, 2026-11-01): each income's tax character. Partnership + # income: the ruled label read "(Schedule E; no self-employment + # earnings)". partnership_self_employment_net_earnings "is not an + # additional gross income source separate from partnership_income" + # (policyengine-us 2.60.4), and two pilot people carry that line, so the + # label yields to it and the second label says the amount is a part. + re.compile(r"(?m)^- partnership income: "), + "- partnership income (Schedule E; no self-employment earnings unless a " + "separate line states them): ", + ), + ( + re.compile(r"(?m)^- partnership self employment net earnings: "), + "- partnership net earnings from self-employment (part of partnership " + "income, not added to it): ", + ), + ( + # educational_assistance feeds no gross-income source in policyengine-us + # 2.60.4, so the reference treats all of it as tax-free. Read as taxable, + # mt_019's $10,000 moved federal tax by $1,200. + re.compile(r"(?m)^- educational assistance: "), + "- educational assistance (tax-free scholarships and grants): ", + ), + ( + # "Memo component of long_term_capital_gains -- already included there" + # (policyengine-us 2.60.4). The judge and the consensus added it twice. + re.compile(r"(?m)^- schedule d capital gain distributions: "), + "- capital gain distributions (already included in long-term capital gains): ", + ), + ( + # policyengine-us documents employer_sponsored_insurance_premiums as + # "Annual employer-paid health insurance premiums". Three web arms read + # the bare label as premiums the household paid (scenario_000). + re.compile(r"employer sponsored insurance premiums: "), + "employer-paid health insurance premiums (paid by the employer, not by " + "the household): ", + ), + ( + # spm_unit_energy_subsidy, the SPM's energy subsidy (home energy + # assistance). No scored output reads it. policyengine-us never reads the + # amount for SNAP: it deems a utility allowance from the state's + # always-SUA flag, and in 2026 only for elderly or disabled households + # (heat_and_eat_requires_elderly_disabled, P.L. 119-21 section 10103). + # The engine label hid what the amount is. + re.compile(r"spm unit energy subsidy: "), + "home energy assistance received: ", + ), +) + + +def v2_pilot_text(text: str) -> str: + """The text with the four PolicyEngine-naming definitions made neutral and + the conventions Max has ruled the v2 prompt states (V2_PILOT_CONVENTIONS).""" + for pattern, replacement in (*V2_PILOT_DEFINITIONS, *V2_PILOT_CONVENTIONS): + text = pattern.sub( + lambda m, r=replacement: r.format(who=m.group(1)) if m.re.groups else r, + text, + ) + return text + + +CALCULATE_DESCRIPTION = ( + "Run PolicyEngine US (policyengine-us 2.41.0) on one household and return " + "the requested variables. `situation` is a PolicyEngine household JSON " + "object with the entity groups people, tax_units, spm_units, families, " + "marital_units and households. Name each person and each unit; every unit " + "lists its `members` by person name, and a group left out puts everyone in " + "one unit. Set each input under its policyengine-us variable name as " + '{period: value}, for example "age": {"2026": 40}; a period is a year ' + '("2026") or a month ("2026-01"), and a bare value is read as the call\'s ' + "`period`. Inputs you do not set take the engine's defaults. `variables` " + 'lists policyengine-us variables to compute for `period` (default "2026"). ' + "Each result gives the variable's entity, label and value for each member of " + "that entity; a monthly variable computed for a year is summed over its " + "months. An unknown name, a variable set on the wrong entity, or a malformed " + "situation returns an error with suggestions instead of results." +) + + +CALCULATE_DESCRIPTION_V2 = CALCULATE_DESCRIPTION.replace( + "An unknown name, a variable set on the wrong entity, or a malformed " + "situation returns an error with suggestions instead of results.", + "A name may also be written with spaces (as the facts are labeled) or be one " + "of the output keys you are asked for; the result's `notes` say how each was " + "read. An input set on the wrong entity is moved to the one unit it belongs " + "to, and the notes say so; where there is no single such unit, or a name is " + "unknown, or the situation is malformed, it returns an error with " + "suggestions instead of results. Setting a variable the engine computes " + "replaces its formula, and the notes say so; a contribution set as the " + "amount contributed is read as the amount asked for before limits " + "(`..._desired`). `explain` lists up to 3 variables to trace: each comes " + "back with the steps that produced it and the parameters, with their " + "values and sources, that it used.", +) +MAX_EXPLAIN = 3 + + +FLAT_DESCRIPTION = ( + "Run PolicyEngine US (policyengine-us 2.41.0) on one household and return " + "the requested variables. `household` is a JSON object: `state` (the " + "two-letter state code), `people` (a list, each with `role` -- head, " + 'spouse or dependent --, `facts`, for example {"age": 40, ' + '"employment_income": 30000}, and optionally `name`, by default the role, ' + "numbered for dependents), and `household_facts` (facts about the " + "household as a whole: its tax unit, family, SPM unit or home). The head " + "and spouse are one couple and everyone else is on their own; everyone " + "shares one tax unit, family, SPM unit and household. A fact is a value " + 'for `period`, or {period: value} with a period such as "2026" or ' + '"2026-01". Facts you do not give take the engine\'s defaults. `variables` ' + 'lists the variables to compute for `period` (default "2026"). Each ' + "result gives the variable's entity, label and value for each member of " + "that entity; a monthly variable computed for a year is summed over its " + "months. An unknown name or a malformed household returns an error with " + "suggestions instead of results." +) +# The version 1 description's last sentence, which placement amends. +_ENTITY_ERROR_SENTENCE = ( + "An unknown name, a variable set on the wrong entity, or a malformed " + "situation returns an error with suggestions instead of results." +) + + +def calculate_tool_schema(version: int = 1, features: frozenset | None = None) -> dict: + if features is None: + features = V2_FEATURES if version == 2 else frozenset() + if features: + schema = calculate_tool_schema(1) + function = schema["function"] + properties = function["parameters"]["properties"] + if features == V2_FEATURES: + function["description"] = engine_text(CALCULATE_DESCRIPTION_V2) + else: + description = ( + FLAT_DESCRIPTION if FLAT in features else CALCULATE_DESCRIPTION + ) + if PLACEMENT in features and FLAT not in features: + description = description.replace( + _ENTITY_ERROR_SENTENCE, + "An unknown name or a malformed situation returns an error " + "with suggestions instead of results.", + ) + notes = [] + if LABELS in features: + notes.append( + "A fact may be written under the label it has in the facts " + "you were given." + ) + if NAMES in features: + notes.append( + "A name may also be written with spaces or be one of the " + "output keys you are asked for." + ) + if PLACEMENT in features and FLAT not in features: + notes.append( + "An input set on the wrong entity is moved to the one unit " + "holding its people; where no single unit holds them, it " + "returns an error." + ) + if OVERRIDES in features: + notes.append( + "Setting a variable the engine computes replaces its formula; a " + "contribution set as the amount contributed is read as the " + "amount asked for before limits (`..._desired`)." + ) + if notes: + notes.append("The result's `notes` say what it did.") + function["description"] = engine_text(" ".join([description, *notes])) + if FLAT in features: + del properties["situation"] + properties["household"] = { + "type": "string", + "description": ( + "The household as a JSON object (state, people with role and " + "facts, household_facts), written as a JSON string." + ), + } + function["parameters"]["required"] = ["household", "variables"] + if EXPLAIN in features: + properties["explain"] = { + "type": "array", + "items": {"type": "string"}, + "description": ( + f"Up to {MAX_EXPLAIN} variables to explain: how the engine " + "computed them." + ), + } + if CONCISE in features: + properties["detail"] = { + "type": "string", + "enum": ["brief", "full"], + "description": ( + 'How much an explanation shows: "brief" (the default: the ' + 'value, what it came from, and the main parameters) or "full" ' + f"(the trace, up to {EXPLAIN_MAX_LINES} steps and " + f"{EXPLAIN_MAX_PARAMETERS} parameters)." + ), + } + return schema + return { + "type": "function", + "function": { + "name": TOOL_NAME, + "description": engine_text(CALCULATE_DESCRIPTION), + "parameters": { + "type": "object", + "properties": { + "situation": { + "type": "string", + "description": ( + "The household situation as a JSON object, written " + "as a JSON string." + ), + }, + "variables": { + "type": "array", + "items": {"type": "string"}, + "description": ( + "policyengine-us variable names to compute (at most " + f"{MAX_VARIABLES})." + ), + }, + "period": { + "type": "string", + "description": 'Year or month to compute, default "2026".', + }, + }, + "required": ["situation", "variables"], + }, + }, + } + + +@dataclass(frozen=True) +class VariableInfo: + entity: str + value_type: str + label: str | None = None + definition_period: str | None = None + possible_values: tuple[str, ...] | None = None + # Whether the engine computes the variable (a formula or a sum of other + # variables) and no household fact the benchmark states sets it: setting + # it replaces what the engine would compute. + computed: bool = False + + +# Inputs the benchmark's reference situations set besides its promptable +# facts (policybench.scenarios.Scenario.to_pe_household), and the convention +# switches (take-up, filing) any household may set. +BASE_STATED_INPUTS = frozenset( + { + "age", + "employment_income", + "self_employment_income", + "long_term_capital_gains", + "partnership_s_corp_income", + "is_tax_unit_head", + "is_tax_unit_spouse", + "state_code", + "weekly_hours_worked_before_lsr", + } +) +CONVENTION_PREFIXES = ("takes_up_", "would_") + + +def stated_inputs() -> frozenset[str]: + """Every variable a household fact the benchmark states can set.""" + from policybench.scenarios import PE_INPUT_ALIASES, PE_INPUT_RENAMES + + names = {spec.source_name for spec in _promptable_specs()} + names |= BASE_STATED_INPUTS + names |= set(PE_INPUT_ALIASES.values()) | set(PE_INPUT_RENAMES.values()) + return frozenset(names) + + +def build_registry( + system, stated: frozenset[str] | None = None +) -> dict[str, VariableInfo]: + """The engine's variables. ``stated`` (default :func:`stated_inputs`) marks + which ones a stated fact sets; the rest that the engine computes are + ``computed``.""" + if stated is None: + stated = stated_inputs() + registry = {} + for name, variable in system.variables.items(): + value_type = getattr(variable.value_type, "__name__", str(variable.value_type)) + possible = None + if value_type == "Enum" and variable.possible_values is not None: + possible = tuple(member.name for member in variable.possible_values) + registry[name] = VariableInfo( + entity=variable.entity.key, + value_type=value_type, + label=variable.label, + definition_period=str(variable.definition_period), + possible_values=possible, + computed=bool( + getattr(variable, "formulas", None) + or getattr(variable, "adds", None) + or getattr(variable, "subtracts", None) + ) + and name not in stated + and not name.startswith(CONVENTION_PREFIXES), + ) + return registry + + +def _suggest(name: str, registry: Mapping[str, VariableInfo], entity=None) -> str: + names = [ + n for n, info in registry.items() if entity is None or info.entity == entity + ] + close = difflib.get_close_matches(name, names, n=5, cutoff=0.6) + return f" Close matches: {', '.join(close)}." if close else "" + + +def _scalar_problem(value) -> str | None: + if isinstance(value, bool) or isinstance(value, str): + return None + if isinstance(value, (int, float)): + if not math.isfinite(float(value)): + return "is not a finite number" + return None + return "must be a number, true/false or a string" + + +def _type_problem(value, info: VariableInfo) -> str | None: + if info.value_type in {"float", "int"}: + if isinstance(value, bool) or not isinstance(value, (int, float)): + return f"takes a number ({info.value_type})" + elif info.value_type == "bool": + if not (isinstance(value, bool) or value in (0, 1)): + return "takes true or false" + elif info.value_type == "Enum": + if not isinstance(value, str): + return "takes one of its named values as a string" + if info.possible_values and value not in info.possible_values: + shown = ", ".join(info.possible_values[:30]) + return f"takes one of: {shown}" + elif info.value_type == "str": + if not isinstance(value, str): + return "takes a string" + return None + + +def _normalize_value( + where: str, + name: str, + value, + info: VariableInfo, + period: str, + problems: list[str], +) -> dict | None: + """One input's {period: value}, or None after recording why not.""" + if isinstance(value, dict): + if not value: + problems.append( + f"{where}: {name} has no values; set it as {{period: value}}." + ) + return None + periods = value + else: + periods = {period: value} + normalized = {} + for key, item in periods.items(): + if not isinstance(key, str) or not PERIOD_RE.match(key): + problems.append( + f"{where}: {name} has period {key!r}; use a year such as " + '"2026" or a month such as "2026-01".' + ) + continue + scalar = _scalar_problem(item) + if scalar is not None: + problems.append(f"{where}: {name} for {key} {scalar}.") + continue + typed = _type_problem(item, info) + if typed is not None: + problems.append(f"{where}: {name} {typed}.") + continue + normalized[key] = item + return normalized + + +def _normalize_inputs( + where: str, + entity: str, + data: dict, + registry: Mapping[str, VariableInfo], + period: str, + problems: list[str], + allow_members: bool, + v2: dict | None = None, +) -> dict: + """Each input under its engine name. ``v2`` (tool version 2) collects the + names it read, the inputs it redirected or flagged, and the inputs set on + another entity, which normalize_request then places.""" + out: dict[str, Any] = {} + for name, value in data.items(): + if allow_members and name == "members": + continue + if v2 is not None and isinstance(name, str) and name not in registry: + resolved, note = read_fact_name(name, registry, v2["features"]) + if resolved is not None: + v2["notes"].append(f"{where}: {note}") + name = resolved + elif (field := dropped_fact(name, registry, v2["features"])) is not None: + v2["notes"].append(_dropped_note(where, name, field)) + continue + if not isinstance(name, str) or name not in registry: + problems.append( + f"{where}: unknown variable {name!r}." + + (_suggest(name, registry) if isinstance(name, str) else "") + ) + continue + info = registry[name] + if v2 is not None and OVERRIDES in v2["features"]: + desired = f"{name}{DESIRED_SUFFIX}" + if ( + info.computed + and desired in registry + and registry[desired].entity == info.entity + ): + v2["notes"].append( + f"{where}: set {desired} (the amount asked for, before " + f"limits) for {name}, which the engine computes from it" + ) + name, info = desired, registry[desired] + elif info.computed: + v2["notes"].append( + f"{where}: {name} is computed by the engine; the value set " + "replaces its formula" + ) + if info.entity != entity: + if v2 is not None and PLACEMENT in v2["features"]: + v2["misplaced"].append((where, entity, name, value)) + continue + problems.append( + f"{where}: {name} is a {info.entity} variable; set it under " + f"{ENTITY_GROUP.get(info.entity, info.entity)}." + ) + continue + normalized = _normalize_value(where, name, value, info, period, problems) + if normalized is None: + continue + if v2 is not None and name in out and out[name] != normalized: + problems.append(f"{where}: {name} is set twice with different values") + continue + out[name] = normalized + return out + + +def normalize_request( + args, + registry: Mapping[str, VariableInfo], + version: int = 1, + features: frozenset | None = None, +) -> tuple[dict | None, dict | None]: + """Check a calculate_household call; return (request, None) or (None, error). + + Accepts only plain JSON data. Every input and output name must be a + variable of the engine, on its own entity; nothing else in the situation + (axes, reforms, parameters) is accepted. Tool version 2 also reads a name + written with spaces or a benchmark output key, redirects a contribution to + its ``_desired`` input, flags an input that replaces a formula, places an + input set on another entity where exactly one unit holds it, and takes + ``explain``; the request's ``notes`` say what it did. + """ + problems: list[str] = [] + if features is None: + features = V2_FEATURES if version == 2 else frozenset() + v2 = {"notes": [], "misplaced": [], "features": features} if features else None + + def fail() -> tuple[None, dict]: + return None, { + "error": "validation", + "problems": problems[:MAX_PROBLEMS], + "problem_count": len(problems), + } + + if isinstance(args, str): + if len(args) > 2 * MAX_SITUATION_CHARS: + problems.append("arguments are too large") + return fail() + try: + args = json.loads(args) + except (ValueError, RecursionError) as error: + problems.append( + f"arguments are not valid JSON: {error}"[:MAX_MESSAGE_CHARS] + ) + return fail() + if not isinstance(args, dict): + problems.append("arguments must be an object") + return fail() + allowed = {"variables", "period"} + allowed |= {"household"} if FLAT in features else {"situation"} + allowed |= {"explain"} if EXPLAIN in features else set() + allowed |= {"detail"} if CONCISE in features else set() + unknown = sorted(set(args) - allowed) + if unknown: + problems.append(f"unknown arguments: {', '.join(map(str, unknown))}") + + period = args.get("period", str(YEAR)) + if period in (None, ""): + period = str(YEAR) + if isinstance(period, int) and not isinstance(period, bool): + period = str(period) + if not isinstance(period, str) or not PERIOD_RE.match(period): + problems.append( + f'period {period!r} must be a year ("2026") or a month ("2026-01")' + ) + period = str(YEAR) + + if FLAT in features: + args = dict(args) + args["situation"] = flat_situation( + args.get("household"), registry, problems, v2, period + ) + if args["situation"] is None: + return fail() + situation = args.get("situation") + if isinstance(situation, str): + if len(situation) > MAX_SITUATION_CHARS: + problems.append("situation is too large") + return fail() + try: + situation = json.loads(situation) + except (ValueError, RecursionError) as error: + problems.append(f"situation is not valid JSON: {error}"[:MAX_MESSAGE_CHARS]) + return fail() + if not isinstance(situation, dict): + problems.append("situation must be a JSON object") + return fail() + try: + too_large = len(json.dumps(situation, default=str)) > MAX_SITUATION_CHARS + except (ValueError, RecursionError): + too_large = True + if too_large: + problems.append("situation is too large") + return fail() + extra = sorted(set(situation) - {"people", *GROUPS}) + if extra: + problems.append( + "situation accepts only people, " + + ", ".join(GROUPS) + + f"; remove {', '.join(map(str, extra))}" + ) + + people = situation.get("people") + normalized: dict[str, Any] = {} + if not isinstance(people, dict) or not people: + problems.append("situation.people must be a non-empty object of named people") + people = {} + elif len(people) > MAX_PEOPLE: + problems.append(f"at most {MAX_PEOPLE} people") + normalized_people = {} + for name, data in people.items(): + if not isinstance(name, str) or not name or len(name) > 64: + problems.append(f"person name {name!r} must be a short string") + continue + if not isinstance(data, dict): + problems.append(f"people.{name} must be an object of inputs") + continue + normalized_people[name] = _normalize_inputs( + f"people.{name}", "person", data, registry, period, problems, False, v2 + ) + normalized["people"] = normalized_people + + for group, entity in GROUPS.items(): + if group not in situation: + continue + units = situation[group] + if not isinstance(units, dict) or not units: + problems.append(f"{group} must be a non-empty object of named units") + continue + if len(units) > MAX_UNITS_PER_GROUP: + problems.append(f"at most {MAX_UNITS_PER_GROUP} {group}") + seen: dict[str, str] = {} + normalized_units = {} + for unit_name, unit in units.items(): + where = f"{group}.{unit_name}" + if not isinstance(unit_name, str) or not unit_name or len(unit_name) > 64: + problems.append( + f"{group} unit name {unit_name!r} must be a short string" + ) + continue + if not isinstance(unit, dict): + problems.append(f"{where} must be an object with members") + continue + members = unit.get("members") + if ( + not isinstance(members, list) + or not members + or not all(isinstance(m, str) for m in members) + ): + problems.append(f"{where}.members must list person names") + members = [] + for member in members: + if member not in people: + problems.append(f"{where}: member {member!r} is not in people") + elif member in seen: + problems.append( + f"{where}: {member} is already in {group}.{seen[member]}" + ) + else: + seen[member] = unit_name + normalized_unit = {"members": list(members)} + normalized_unit.update( + _normalize_inputs( + where, entity, unit, registry, period, problems, True, v2 + ) + ) + normalized_units[unit_name] = normalized_unit + normalized[group] = normalized_units + + variables = args.get("variables") + if isinstance(variables, str): + variables = [variables] + if ( + not isinstance(variables, list) + or not variables + or not all(isinstance(v, str) for v in variables) + ): + problems.append("variables must be a non-empty list of variable names") + variables = [] + elif len(variables) > MAX_VARIABLES: + problems.append(f"at most {MAX_VARIABLES} variables per call") + if v2 is not None and PLACEMENT in features: + _place_misplaced(v2, normalized, situation, registry, period, problems) + if v2 is not None and LABELS in features: + _set_aliases(v2, normalized["people"], registry) + requested = [] + for name in variables: + if ( + v2 is not None + and NAMES in features + and isinstance(name, str) + and name not in registry + ): + resolved, note = resolve_name(name, registry, output_names=True) + if resolved is not None: + v2["notes"].append(f"variables: {note}") + name = resolved + if name not in registry: + problems.append( + f"variables: unknown variable {name!r}." + _suggest(name, registry) + ) + elif name not in requested: + requested.append(name) + explain = [] + if EXPLAIN in features and args.get("explain") is not None: + names = args["explain"] + if isinstance(names, str): + names = [names] + if not isinstance(names, list) or not all(isinstance(n, str) for n in names): + problems.append("explain must be a list of variable names") + names = [] + elif len(names) > MAX_EXPLAIN: + problems.append(f"explain at most {MAX_EXPLAIN} variables per call") + for name in names: + if NAMES in features and name not in registry: + resolved, note = resolve_name(name, registry, output_names=True) + if resolved is not None: + v2["notes"].append(f"explain: {note}") + name = resolved + if name not in registry: + problems.append( + f"explain: unknown variable {name!r}." + _suggest(name, registry) + ) + elif name not in explain: + explain.append(name) + + detail = None + if CONCISE in features: + detail = args.get("detail") or "brief" + if detail not in ("brief", "full"): + problems.append('detail must be "brief" or "full"') + + if problems: + return fail() + request = {"situation": normalized, "variables": requested, "period": period} + if v2 is not None: + request["explain"] = explain + request["notes"] = v2["notes"] + if detail is not None: + request["detail"] = detail + return request, None + + +FLAT_ROLES = ("head", "spouse", "dependent") +FLAT_PERSON_KEYS = ("name", "role", "facts") +# The relationship inputs a role sets (as Scenario.to_pe_household's people +# carry them). +FLAT_RELATIONS = {"is_tax_unit_head": "head", "is_tax_unit_spouse": "spouse"} + + +def flat_names(people) -> list: + """The name each listed person goes by: the one given, or, for a person + given none, the role (head, spouse, dependent_1, ...: dependents are + numbered by their place among the dependents listed).""" + names, dependents = [], 0 + for person in people if isinstance(people, list) else []: + if not isinstance(person, dict): + names.append(None) + continue + role = person.get("role") + if role == "dependent": + dependents += 1 + name = person.get("name") + if name is None and role in FLAT_ROLES: + name = role if role != "dependent" else f"dependent_{dependents}" + names.append(name) + return names + + +def _same_value( + registry, + name: str, + a, + b, + period: str, + problems: list[str] | None = None, + where: str = "", +) -> bool | None: + """Whether two values of an input are the same once normalized, or None + when either is malformed. ``a`` stays in the situation, so normalization + reports it later; a caller that drops ``b`` passes ``problems`` so a + malformed ``b`` is reported, not lost.""" + info = registry[name] + first_problems: list[str] = [] + second_problems: list[str] = [] + first = _normalize_value(where, name, a, info, period, first_problems) + second = _normalize_value(where, name, b, info, period, second_problems) + if problems is not None: + problems.extend(second_problems) + if first_problems or second_problems: + return None + return first == second + + +def flat_situation( + household, + registry, + problems: list[str], + v2: dict | None, + period: str = str(YEAR), +): + """The flat feature's household -- state, people with role and facts, and + household facts -- as a situation, with the units the benchmark's own + reference situations have (policybench.scenarios.Scenario.to_pe_household): + the head and spouse one marital unit and everyone else alone, and one tax + unit, SPM unit, family and household holding everyone. Roles set the + relationship inputs; a stated one that contradicts its role is refused. + A household fact goes to the unit of its variable's entity, under the + name it was written with, so normalization reads and compares it as any + other input. A person given no name is named by role (flat_names). + Returns None after recording problems.""" + features = v2["features"] if v2 is not None else frozenset() + + def engine_name(name): + if isinstance(name, str) and name in registry: + return name + if isinstance(name, str): + return read_fact_name(name, registry, features)[0] + return None + + if isinstance(household, str): + if len(household) > MAX_SITUATION_CHARS: + problems.append("household is too large") + return None + try: + household = json.loads(household) + except (ValueError, RecursionError) as error: + problems.append(f"household is not valid JSON: {error}"[:MAX_MESSAGE_CHARS]) + return None + if not isinstance(household, dict): + problems.append( + "household must be a JSON object with state, people and household_facts" + ) + return None + extra = sorted(set(household) - {"state", "people", "household_facts"}) + if extra: + problems.append( + "household accepts state, people and household_facts; remove " + + ", ".join(map(str, extra)) + ) + people = household.get("people") + if not isinstance(people, list) or not people: + problems.append("household.people must be a non-empty list of people") + return None + if len(people) > MAX_PEOPLE: + problems.append(f"at most {MAX_PEOPLE} people") + return None + situation: dict[str, Any] = {"people": {}} + roles: dict[str, str] = {} + for index, (person, name) in enumerate(zip(people, flat_names(people))): + if not isinstance(person, dict): + problems.append( + f"people[{index}] must be an object with name, role and facts" + ) + continue + stray = sorted(map(str, set(person) - set(FLAT_PERSON_KEYS))) + if stray: + problems.append( + f"people[{index}] takes only name, role and facts; give " + f"{', '.join(stray)} under facts" + ) + continue + role, facts = person.get("role"), person.get("facts", {}) + if role not in FLAT_ROLES: + problems.append( + f"people[{index}].role must be one of {', '.join(FLAT_ROLES)}" + ) + continue + if person.get("name") is None and v2 is not None: + v2["notes"].append(f"people[{index}]: named {name}") + if not isinstance(name, str) or not name or len(name) > 64: + problems.append(f"people[{index}].name must be a short string") + continue + if name in roles: + problems.append(f"people[{index}]: {name!r} is listed twice") + continue + if not isinstance(facts, dict): + problems.append(f"people[{index}].facts must be an object") + continue + roles[name] = role + situation["people"][name] = dict(facts) + heads = [n for n, r in roles.items() if r == "head"] + spouses = [n for n, r in roles.items() if r == "spouse"] + if len(heads) != 1: + problems.append("the household needs exactly one head") + if len(spouses) > 1: + problems.append("the household has at most one spouse") + if problems: + return None + for name, role in roles.items(): + facts = situation["people"][name] + for relation, relation_role in FLAT_RELATIONS.items(): + if relation not in registry: + continue + implied = role == relation_role + stated = [k for k in facts if engine_name(k) == relation] + if not stated: + facts[relation] = implied + elif any( + _same_value(registry, relation, facts[k], implied, period) is False + for k in stated + ): + problems.append( + f"people.{name}: {relation} contradicts the role {role}; the " + "role sets it" + ) + everyone = list(situation["people"]) + couple = heads + spouses + groups = [couple] + [[n] for n in everyone if n not in couple] + situation["marital_units"] = { + f"marital_unit_{i}": {"members": members} + for i, members in enumerate(groups, start=1) + } + situation["tax_units"] = {"tax_unit": {"members": list(everyone)}} + situation["spm_units"] = {"spm_unit": {"members": list(everyone)}} + situation["families"] = {"family": {"members": list(everyone)}} + situation["households"] = {"household": {"members": list(everyone)}} + state = household.get("state") + if state is not None: + situation["households"]["household"]["state_code"] = state + unit_of = { + "tax_unit": situation["tax_units"]["tax_unit"], + "spm_unit": situation["spm_units"]["spm_unit"], + "family": situation["families"]["family"], + "household": situation["households"]["household"], + "marital_unit": situation["marital_units"]["marital_unit_1"], + } + facts = household.get("household_facts") or {} + if not isinstance(facts, dict): + problems.append("household_facts must be an object") + return None + for name, value in facts.items(): + resolved = engine_name(name) + if resolved is None: + field = ( + dropped_fact(name, registry, features) + if isinstance(name, str) + else None + ) + if field is not None: + v2["notes"].append(_dropped_note("household_facts", name, field)) + continue + problems.append( + f"household_facts: unknown variable {name!r}." + + (_suggest(name, registry) if isinstance(name, str) else "") + ) + continue + entity = registry[resolved].entity + if entity == "person": + # As placement moves a person variable off a one-person unit: only + # a household of one says whose fact it is. + if v2 is None or PLACEMENT not in features or len(everyone) != 1: + problems.append( + f"household_facts: {resolved} is a person's fact; give it " + "under the person whose facts list it" + ) + continue + target = situation["people"][everyone[0]] + v2["notes"].append( + f"household_facts: moved {resolved}, a person's fact, to {everyone[0]}" + ) + else: + target = unit_of[entity] + if name in target: + # The repeat is dropped, so only one validated as equal is kept quiet. + same = _same_value( + registry, + resolved, + target[name], + value, + period, + problems, + "household_facts", + ) + if same is False: + problems.append( + f"household_facts: {resolved} is set twice with different values" + ) + continue + target[name] = value + return None if problems else situation + + +DESIRED_SUFFIX = "_desired" +_LABEL_SEPARATORS = re.compile(r"[\s\-]+") + + +def output_reading(name: str) -> tuple[str, str] | None: + """A benchmark output key's engine variable and how the output reads it, + or None when the name is not an output key.""" + from policybench.ground_truth import ( + _aggregation_for_output, + _pe_variable_for_output, + ) + from policybench.spec import find_output_spec, parse_person_output + + person = parse_person_output(name) + if person is None and find_output_spec(name, country="us") is None: + return None + engine = _pe_variable_for_output(name, "us") + if engine == name: + return None + aggregation = _aggregation_for_output(name, "us") + if person is not None: + how = f"{engine} for the person the key names ({person[0]})" + elif aggregation == "any_positive": + how = f"1 when {engine} is above 0, else 0" + else: + how = f"{engine}, summed over the household's units" + return engine, how + + +def _label_key(text: str) -> str: + """A label as compared: lower case, letters and digits only, so "Roth + 401(k) contributions" and "roth 401k contributions" read alike.""" + return re.sub(r"[^0-9a-z]", "", text.casefold()) + + +# The prompt's household block gives the state as "state: CT". +PROMPT_EXTRA_LABELS = {"state": "state_code"} + + +@functools.lru_cache(maxsize=1) +def _promptable_specs(): + from policybench.scenarios import get_promptable_input_specs + + return get_promptable_input_specs() + + +def _sample_value(value_type: str): + if value_type == "bool": + return True + if value_type in ("str", "Enum"): + return "x" + return 1.0 + + +def rendered_labels(field: str, value_type: str = "float") -> tuple[str, ...]: + """The labels a fact is shown under: in the board's prompt + (policybench.prompts._format_input_line, special renderers included) and + in the v2-pilot prompt (v2_pilot_text applied to that line).""" + from policybench.prompts import _format_input_line, _humanize_input_label + + line = _format_input_line(field, _sample_value(value_type)) + label = _humanize_input_label(field) + if not (line == f"- {label}" or line.startswith(f"- {label}: ")): + label = line[2:].split(": ", 1)[0] + labels = [label] + suffix = line[2 + len(label) :] + rewritten = v2_pilot_text(line) + if rewritten != line and rewritten.startswith("- ") and rewritten.endswith(suffix): + labels.append(rewritten[2 : len(rewritten) - len(suffix)]) + return tuple(labels) + + +@functools.lru_cache(maxsize=1) +def prompt_labels() -> dict[str, frozenset[tuple[str, bool]]]: + """Every label the prompts show a fact under, keyed by _label_key, each + with the facts it may name as (engine name, dropped): the promptable + inputs, every labeled input (policybench.prompts.INPUT_LABEL_OVERRIDES), + the inputs the reference sets besides them (BASE_STATED_INPUTS), inputs + the engine has renamed and inputs the reference leaves out + (policybench.scenarios.PE_INPUT_RENAMES, PE_DROPPED_INPUTS), each in the + board's and the v2-pilot prompt's wording. Dropped facts are shown but are + not engine inputs. A label may name facts of another country; a lookup + reads only the one its engine has.""" + from policybench.prompts import INPUT_LABEL_OVERRIDES + from policybench.scenarios import PE_DROPPED_INPUTS, PE_INPUT_RENAMES + + fields = {spec.output_name: spec.value_type for spec in _promptable_specs()} + dropped = {f for names in PE_DROPPED_INPUTS.values() for f in names} + for source in ( + "age", + *BASE_STATED_INPUTS, + *INPUT_LABEL_OVERRIDES, + *PE_INPUT_RENAMES, + *dropped, + ): + fields.setdefault(source, "int" if source == "age" else "float") + labels: dict[str, set[tuple[str, bool]]] = {} + for source, value_type in fields.items(): + target = (PE_INPUT_RENAMES.get(source, source), source in dropped) + keys = {_label_key(label) for label in rendered_labels(source, value_type)} + if source in PE_INPUT_RENAMES or source in dropped: + keys.add(_label_key(source)) + for key in keys: + labels.setdefault(key, set()).add(target) + for label, name in PROMPT_EXTRA_LABELS.items(): + labels.setdefault(_label_key(label), set()).add((name, False)) + return {key: frozenset(targets) for key, targets in labels.items()} + + +def read_fact_name( + name: str, registry: Mapping[str, VariableInfo], features: frozenset +) -> tuple[str | None, str | None]: + """A fact's engine variable under the labels feature (any label the + prompt shows it under, when exactly one fact it may name is the engine's) + and then the names feature (spaces for underscores). Returns (engine + name, note) or (None, None).""" + if LABELS in features: + found = [ + engine + for engine, dropped in prompt_labels().get(_label_key(name), ()) + if not dropped and engine in registry + ] + if len(found) == 1: + return found[0], f"read {name!r} as {found[0]}" + if NAMES in features: + return resolve_name(name, registry, output_names=False) + return None, None + + +def dropped_fact( + name: str, registry: Mapping[str, VariableInfo], features: frozenset +) -> str | None: + """Under the labels feature, the input a fact names when the prompt shows + it but the reference leaves it out (policybench.scenarios.PE_DROPPED_INPUTS: + no longer an engine input); otherwise None.""" + if LABELS not in features: + return None + found = [ + engine + for engine, dropped in prompt_labels().get(_label_key(name), ()) + if dropped + ] + return found[0] if len(found) == 1 else None + + +def _dropped_note(where: str, name: str, field: str) -> str: + return ( + f"{where}: {name!r} ({field}) is not an input of this engine; the " + "benchmark's reference leaves it out too, so it was ignored" + ) + + +def _set_aliases(v2: dict, people: dict, registry: Mapping[str, VariableInfo]): + """Set each fact the reference also sets under another name there too + (policybench.scenarios.PE_INPUT_ALIASES: the SNAP work rules read stated + usual weekly hours as weekly_hours_worked_before_lsr), unless it is set.""" + from policybench.scenarios import PE_INPUT_ALIASES + + for person, inputs in people.items(): + for source, target in PE_INPUT_ALIASES.items(): + if source in inputs and target in registry and target not in inputs: + inputs[target] = dict(inputs[source]) + v2["notes"].append( + f"people.{person}: also set {target} from {source}, as the " + "benchmark's reference does" + ) + + +def resolve_name( + name: str, registry: Mapping[str, VariableInfo], output_names: bool +) -> tuple[str | None, str | None]: + """Tool version 2's reading of a name the engine does not know: the name + with spaces or hyphens as underscores, or (for outputs) a benchmark output + key. Returns (engine name, note) or (None, None).""" + if name in registry: + return name, None + written = _LABEL_SEPARATORS.sub("_", name.strip().lower()) + if written in registry: + return written, f"read {name!r} as {written}" + if output_names: + reading = output_reading(name) + if reading is not None and reading[0] in registry: + return reading[0], f"{name} is {reading[1]}; computed {reading[0]}" + return None, None + + +def _place_misplaced( + v2: dict, + normalized: dict, + situation: dict, + registry: Mapping[str, VariableInfo], + period: str, + problems: list[str], +) -> None: + """Move each input set on another entity to the one unit that holds the + people it was set for: a group variable set on a person goes to that + person's unit (a group left out of the situation becomes one unit of + everyone, as the engine reads it), a person variable set on a one-person + unit goes to that person, and a group variable set on another group goes + to the unit holding all of its members. Anything else stays an error.""" + for where, source_entity, name, value in v2["misplaced"]: + info = registry[name] + if source_entity == "person": + persons = [where.split(".", 1)[1]] + else: + group, unit = where.split(".", 1) + persons = list(normalized.get(group, {}).get(unit, {}).get("members", [])) + target_group = ENTITY_GROUP.get(info.entity, info.entity) + if info.entity == "person": + if len(persons) != 1: + problems.append( + f"{where}: {name} is a person variable; set it on one person " + "under people." + ) + continue + destination = normalized["people"].get(persons[0]) + to = f"people.{persons[0]}" + else: + if target_group not in situation and target_group not in normalized: + normalized[target_group] = { + "all": {"members": list(normalized["people"])} + } + units = normalized.get(target_group, {}) + holding = [ + unit + for unit, data in units.items() + if set(persons) <= set(data.get("members", [])) + ] + if len(holding) != 1: + problems.append( + f"{where}: {name} is a {info.entity} variable; set it under " + f"{target_group} (no single unit there holds " + f"{', '.join(persons) or 'its members'})." + ) + continue + destination = units[holding[0]] + to = f"{target_group}.{holding[0]}" + if destination is None: + problems.append(f"{where}: {name} has no place to go") + continue + normalized_value = _normalize_value(to, name, value, info, period, problems) + if normalized_value is None: + continue + if name in destination and destination[name] != normalized_value: + problems.append(f"{to}: {name} is set twice with different values") + continue + destination[name] = normalized_value + v2["notes"].append(f"moved {name} from {where} to {to}") + + +def _jsonable(value): + if hasattr(value, "item"): + value = value.item() + if isinstance(value, bytes): + value = value.decode() + if isinstance(value, bool): + return value + if isinstance(value, (int, float)): + value = float(value) + if not math.isfinite(value): + return None + return round(value, 2) + return str(value) + + +def execute_request(system, registry, request: dict, simulation_cls=None) -> dict: + if simulation_cls is None: + from policyengine_us import Simulation as simulation_cls + try: + simulation = simulation_cls( + tax_benefit_system=system, situation=copy.deepcopy(request["situation"]) + ) + except Exception as error: # the engine's own message is the useful one + return { + "error": "engine", + "message": f"{type(error).__name__}: {error}"[:MAX_MESSAGE_CHARS], + } + results = {} + for name in request["variables"]: + info = registry[name] + try: + array = simulation.calculate(name, request["period"]) + except Exception as error: + results[name] = { + "error": f"{type(error).__name__}: {error}"[:MAX_MESSAGE_CHARS] + } + continue + if hasattr(array, "decode_to_str"): + array = array.decode_to_str() + ids = [str(i) for i in simulation.populations[info.entity].ids] + results[name] = { + "entity": info.entity, + "label": info.label, + "period": request["period"], + "values": {i: _jsonable(v) for i, v in zip(ids, list(array))}, + } + out = {"results": results} + if "notes" in request: + out["notes"] = list(request["notes"]) + if request.get("explain"): + out["explanations"] = { + name: ( + brief_explanation( + explain_variable(system, request, name, simulation_cls) + ) + if request.get("detail") == "brief" + else explain_variable(system, request, name, simulation_cls) + ) + for name in request["explain"] + } + return out + + +BRIEF_INPUTS = 8 +BRIEF_PARAMETERS = 5 + + +def brief_explanation(full: dict) -> dict: + """The concise feature's explanation: the value, the variables it came + from directly (one level down, the first BRIEF_INPUTS), and the first + parameters it read with their sources.""" + if "error" in full: + return full + steps = full["steps"] + direct = [ + s.strip() for s in steps[1:] if s.startswith(" ") and not s.startswith(" ") + ] + return { + "value": steps[0].strip() if steps else "", + "from": direct[:BRIEF_INPUTS], + "parameters": full["parameters"][:BRIEF_PARAMETERS], + "more": 'set detail to "full" for the trace', + } + + +EXPLAIN_MAX_LINES = 60 +EXPLAIN_MAX_DEPTH = 6 +EXPLAIN_MAX_PARAMETERS = 15 +# Switches every variable has; never part of a reason. +_QUIET_PARAMETERS = ("gov.abolitions.",) + + +def _trace_value(value) -> Any: + if hasattr(value, "decode_to_str"): + value = value.decode_to_str() + try: + items = list(value) + except TypeError: + return _jsonable(value) + items = [_jsonable(v) for v in items] + return items[0] if len(items) == 1 else items + + +def _all_zero(value) -> bool: + try: + return all((not v) if not isinstance(v, str) else False for v in list(value)) + except TypeError: + return not value + + +def parameter_sources(system, name: str, limit: int = 2) -> list[dict]: + """A parameter's cited sources: its own ``reference`` metadata, or the + nearest ancestor's.""" + node = system.parameters + chain = [node] + for part in name.split("."): + children = getattr(node, "children", None) + if not isinstance(children, dict) or part not in children: + break + node = children[part] + chain.append(node) + for node in reversed(chain): + refs = (getattr(node, "metadata", None) or {}).get("reference") + if refs: + refs = refs if isinstance(refs, list) else [refs] + out = [] + for ref in refs[:limit]: + if isinstance(ref, dict): + out.append({k: ref[k] for k in ("title", "href") if ref.get(k)}) + else: + out.append({"href": str(ref)}) + return out + return [] + + +def explain_variable(system, request: dict, name: str, simulation_cls=None) -> dict: + """How the engine computed ``name`` for the request's household: the + computation steps (each variable, its period and value, with its inputs + indented beneath it; zero-valued branches below the first level left out), + then the parameters it read, each with its value and cited sources.""" + if simulation_cls is None: + from policyengine_us import Simulation as simulation_cls + try: + simulation = simulation_cls( + tax_benefit_system=system, situation=copy.deepcopy(request["situation"]) + ) + simulation.trace = True + simulation.calculate(name, request["period"]) + except Exception as error: + return {"error": f"{type(error).__name__}: {error}"[:MAX_MESSAGE_CHARS]} + + def find(nodes): + for node in nodes: + if node.name == name: + return node + hit = find(node.children) + if hit is not None: + return hit + return None + + root = find(simulation.tracer.trees) + if root is None: + return {"error": f"no trace for {name}"} + steps: list[str] = [] + parameters: dict[str, Any] = {} + + def walk(node, depth): + if len(steps) >= EXPLAIN_MAX_LINES or depth > EXPLAIN_MAX_DEPTH: + return + if depth > 1 and _all_zero(node.value): + return + steps.append( + " " * depth + f"{node.name} ({node.period}) = {_trace_value(node.value)}" + ) + for parameter in node.parameters: + if parameter.name.startswith(_QUIET_PARAMETERS): + continue + parameters.setdefault(parameter.name, _trace_value(parameter.value)) + for child in node.children: + walk(child, depth + 1) + + walk(root, 0) + return { + "steps": steps, + "parameters": [ + {"name": key, "value": value, "sources": parameter_sources(system, key)} + for key, value in list(parameters.items())[:EXPLAIN_MAX_PARAMETERS] + ], + } + + +def _board_upgrade(snapshot: Path) -> dict: + """A board's last engine_upgrade revision: the engine its references are + on and the fix modules it pins. The frozen board's is 2.41.0's; a household + set (scripts/household_set.py) records one.""" + meta = json.loads((snapshot / "reference_outputs.csv.meta.json").read_text()) + revisions = [r for r in meta["revisions"] if r.get("kind") == "engine_upgrade"] + if not revisions: + raise SystemExit(f"{snapshot} records no engine_upgrade revision") + return revisions[-1] + + +def board_engine(snapshot: Path = SNAPSHOT) -> str: + """The policyengine-us version a board's references were computed on.""" + return _board_upgrade(snapshot)["engine_version"].removeprefix("policyengine-us ") + + +def is_household_set(snapshot: Path) -> bool: + meta = json.loads((snapshot / "reference_outputs.csv.meta.json").read_text()) + return meta.get("board_kind") == "household_set" + + +def pinned_fix_modules(snapshot: Path = SNAPSHOT) -> list[dict]: + """The fix modules a board's references were built with, as its sidecar's + engine_upgrade revision pins them (path and sha256).""" + return _board_upgrade(snapshot)["fix_modules"] + + +def board_fix_module_sha256(snapshot: Path = SNAPSHOT) -> str: + """The pinned latest_final.py: the constant for the frozen board, the + sidecar's record for a household set.""" + if not is_household_set(snapshot): + return FIX_MODULE_SHA256 + return _board_upgrade(snapshot)["fix_module"]["sha256"] + + +def verify_fix_pins( + fixes_dir: Path = FIX_MODULE.parent, snapshot: Path = SNAPSHOT +) -> None: + """Every module latest_final.py composes must be the pinned bytes. + + Each pin is checked at its recorded path; a module the reform reads from + its own directory (the sales tax tables) is also checked there. + """ + problems = [] + for pin in pinned_fix_modules(snapshot): + candidates = {ROOT / pin["path"], fixes_dir / pin["module"]} + for path in sorted(candidates): + if path.exists() and _sha256(path) != pin["sha256"]: + problems.append(f"{path} does not match the pinned {pin['sha256']}") + if not any(path.exists() for path in candidates): + problems.append(f"{pin['module']} is missing") + pinned = board_fix_module_sha256(snapshot) + if _sha256(FIX_MODULE) != pinned: + problems.append(f"{FIX_MODULE} does not match {pinned}") + if problems: + raise SystemExit("; ".join(problems)) + + +def load_fix_reform(path: Path = FIX_MODULE, snapshot: Path = SNAPSHOT): + if path == FIX_MODULE: + verify_fix_pins(snapshot=snapshot) + spec = importlib.util.spec_from_file_location("tool_pilot_latest_final", path) + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module.reform + + +def build_tool_system( + reform: bool = True, path: Path = FIX_MODULE, snapshot: Path = SNAPSHOT +): + from policyengine_us import CountryTaxBenefitSystem + + if not reform: + return CountryTaxBenefitSystem() + return CountryTaxBenefitSystem(reform=load_fix_reform(path, snapshot)) + + +# How a pool tells its worker the calculator's features: a tuple, which a +# model's JSON arguments can never be, so a model cannot turn on a feature its +# arm does not offer. A pool without features sends the arguments as they are. +CALL_FRAME = "calculate" + + +def tool_call_frame(features: frozenset, arguments) -> tuple: + return (CALL_FRAME, tuple(sorted(features)), arguments) + + +def frame_features(names) -> frozenset: + """A frame's features, refused (ValueError) unless they are a tuple of + known feature names with concise only beside explain.""" + if not isinstance(names, tuple) or not all(isinstance(n, str) for n in names): + raise ValueError("the features must be a tuple of names") + features = frozenset(names) + if features - set(TOOL_FEATURES): + raise ValueError( + f"unknown tool features {sorted(features - set(TOOL_FEATURES))}" + ) + if CONCISE in features and EXPLAIN not in features: + raise ValueError("the concise feature needs explain") + return features + + +def worker_request(message, registry) -> tuple[dict | None, dict | None]: + """A worker's reading of one pool message: a call frame's arguments under + its features, or anything else as a model's arguments with no features + (keys such as "__tool_features__" or "__tool_version__" in them are the + model's, and refused as unknown arguments).""" + features = frozenset() + if isinstance(message, tuple) and len(message) == 3 and message[0] == CALL_FRAME: + try: + features = frame_features(message[1]) + except ValueError as error: + return None, {"error": "configuration", "message": str(error)} + message = message[2] + return normalize_request(message, registry, features=features) + + +def _worker_main(conn, fix_path: str, reform: bool, board: str | None = None) -> None: + for name in ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS"): + os.environ[name] = "1" + snapshot = Path(board) if board else SNAPSHOT + system = build_tool_system(reform=reform, path=Path(fix_path), snapshot=snapshot) + registry = build_registry(system) + conn.send(("ready", None)) + while True: + try: + args = conn.recv() + except EOFError: + return + if args is None: + return + request, error = worker_request(args, registry) + if error is not None: + conn.send(("ok", error)) + continue + conn.send(("ok", execute_request(system, registry, request))) + + +class ToolPool: + """Worker processes that hold the tool system, each call under a timeout.""" + + def __init__( + self, + size: int, + fix_path: Path = FIX_MODULE, + timeout: float = TOOL_TIMEOUT_SECONDS, + reform: bool = True, + worker_target: Callable | None = None, + acquire_timeout: float | None = None, + board: Path | None = None, + tool_version: int = 1, + tool_features: frozenset | None = None, + ): + self._ctx = mp.get_context("spawn") + self._tool_version = tool_version + self._tool_features = ( + tool_features + if tool_features is not None + else (V2_FEATURES if tool_version == 2 else frozenset()) + ) + self._fix_path = str(fix_path) + # A worker gets the board only when it is not the frozen one, so a + # three-argument worker target still starts on the default. + self._board = None if board is None or board == SNAPSHOT else str(board) + self._reform = reform + self._target = worker_target or _worker_main + self.timeout = timeout + self.acquire_timeout = ( + WORKER_START_TIMEOUT_SECONDS + timeout + if acquire_timeout is None + else acquire_timeout + ) + self._idle: queue.Queue = queue.Queue() + self._lock = threading.Lock() + self.timeouts = 0 + self.crashes = 0 + self.lost = 0 + starting = [self._start() for _ in range(size)] + for worker in starting: + self._idle.put(self._await_ready(worker)) + + def _start(self): + parent, child = self._ctx.Pipe() + args = (child, self._fix_path, self._reform) + if self._board is not None: + args += (self._board,) + process = self._ctx.Process(target=self._target, args=args, daemon=True) + process.start() + return process, parent + + def _await_ready(self, worker): + """The worker once it reports ready; RuntimeError (worker killed) if it + does not start, however it fails.""" + process, conn = worker + try: + if not conn.poll(WORKER_START_TIMEOUT_SECONDS): + raise RuntimeError("tool worker did not start") + status, _ = conn.recv() + if status != "ready": + raise RuntimeError(f"tool worker failed to start: {status}") + except (RuntimeError, EOFError, OSError, ValueError) as error: + process.kill() + process.join(timeout=10) + raise RuntimeError(f"tool worker failed to start: {error}") from error + return worker + + def counters(self) -> dict: + with self._lock: + return { + "timeouts": self.timeouts, + "crashes": self.crashes, + "lost": self.lost, + } + + def call(self, args) -> tuple[dict, float]: + started = time.perf_counter() + try: + worker = self._idle.get(timeout=self.acquire_timeout) + except queue.Empty: + # Infrastructure, not the model: run_household stops the household + # with a rerunnable status rather than show the model this result. + return ( + {"error": POOL_UNAVAILABLE, "message": "no tool worker is available"}, + time.perf_counter() - started, + ) + process, conn = worker + if self._tool_features: + args = tool_call_frame(self._tool_features, args) + try: + conn.send(args) + if conn.poll(self.timeout): + _, result = conn.recv() + self._idle.put(worker) + return result, time.perf_counter() - started + with self._lock: + self.timeouts += 1 + result = { + "error": "timeout", + "message": f"the calculation exceeded {self.timeout:.0f} seconds", + } + except (EOFError, BrokenPipeError, OSError, ValueError) as error: + with self._lock: + self.crashes += 1 + result = {"error": "engine", "message": f"tool worker failed: {error}"} + elapsed = time.perf_counter() - started + process.kill() + process.join(timeout=10) + try: + self._idle.put(self._await_ready(self._start())) + except RuntimeError: + with self._lock: + self.lost += 1 + return result, elapsed + + def close(self) -> None: + while not self._idle.empty(): + process, conn = self._idle.get() + try: + conn.send(None) + except (BrokenPipeError, OSError): + pass + process.join(timeout=5) + if process.is_alive(): + process.kill() + + +def _sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _versions() -> dict: + out = {} + for name in ("policyengine-us", "policyengine-core", "litellm"): + try: + out[name] = importlib.metadata.version(name) + except importlib.metadata.PackageNotFoundError: + out[name] = None + return out + + +def _require_engine(board: Path = SNAPSHOT) -> None: + version = _versions()["policyengine-us"] + pinned = board_engine(board) + if version != pinned: + where = ( + f"the reference engine of household set {board}" + if is_household_set(board) + else "the reference engine of release dashboard-data-20261014" + ) + raise SystemExit( + f"policyengine-us {version} is installed; the pilot pins {pinned}, {where}." + ) diff --git a/scripts/sync_calculator_core.py b/scripts/sync_calculator_core.py new file mode 100644 index 00000000..072b6763 --- /dev/null +++ b/scripts/sync_calculator_core.py @@ -0,0 +1,284 @@ +"""Write policybench_calculator/core.py from scripts/tool_pilot_argon.py. + + python scripts/sync_calculator_core.py rewrite core.py + python scripts/sync_calculator_core.py --check exit 1 if core.py is stale + +The tool pilot's harness holds the calculator (the tool a model is given) in +one script with the code that calls models. ``policybench_calculator.core`` is +the calculator alone, for anything else that offers it (the MCP server). The +v2 confirmatory runner pins the harness to its treatment commit +(``scripts/confirmatory_run.py``, ``TREATMENT_PATHS``), so the harness cannot +import the package yet; until it can, this script keeps the package's copy +exact. + +The copy is the dependency closure of ``ENTRY_POINTS`` among the harness's +module-level statements, in the harness's order: each statement's source +lines byte for byte, with the comment block directly above it. The closure +comes from Python's own symbol tables, so a name counts only where a scope +reads it as a global, and a local variable that shares a module-level name +pulls nothing in. + +Run it after any change to the harness that the closure reaches (the +calculator itself, or the v2-pilot wording the labels feature reads); +``tests/test_calculator_core.py`` fails until core.py is current. +""" + +from __future__ import annotations + +import ast +import builtins +import symtable +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +HARNESS = ROOT / "scripts/tool_pilot_argon.py" +CORE = ROOT / "policybench_calculator/core.py" + +# What a server or a harness needs to offer the calculator; everything else in +# core.py is there because one of these reads it. +ENTRY_POINTS = ( + "TOOL_NAME", + "TOOL_TIMEOUT_SECONDS", + "TOOL_FEATURES", + "arm_features", + "calculate_tool_schema", + "set_stated_engine", + "stating_engine", + "engine_text", + "build_registry", + "normalize_request", + "execute_request", + "build_tool_system", + "board_engine", + "_require_engine", + "tool_call_frame", + "frame_features", + "worker_request", + "_worker_main", + "ToolPool", +) +# Names every module has. +MODULE_NAMES = frozenset({"__file__", "__name__"}) + +HEADER = '''"""The household calculator the PolicyBench tool pilot gives a model. + +Written by ``scripts/sync_calculator_core.py``; do not edit it by hand. + +This module is a verbatim copy of the calculator inside +``scripts/tool_pilot_argon.py``: the tool's schema and descriptions for each +feature set, the validator (names, labels, placement, overrides, the flat +household), the engine call, the explanations, the board's pinned engine and +convention reform, and the worker pool that runs each call in its own process +under a timeout. Nothing here calls a model. + +Why a copy. The v2 confirmatory runner refuses to start unless +``scripts/tool_pilot_argon.py`` and the ``policybench`` package are its +treatment commit's (``scripts/confirmatory_run.py``, ``TREATMENT_PATHS``), so +the harness cannot import this module until that run is over. Until then both +hold the same code. ``tests/test_calculator_core.py`` fails if this file is +not the sync script's output for the harness as it stands, if any definition +here differs from the harness's (compared by AST), or if the two build +different tool schemas or read a call differently. To change the calculator, +change the harness and run the sync script; once the treatment pin is lifted, +the harness imports this module and its own copy goes. + +Everything below the imports is the harness's text, in the harness's order. +""" +''' + +IMPORTS = """from __future__ import annotations + +import contextlib +import copy +import difflib +import functools +import hashlib +import importlib.metadata +import importlib.util +import json +import math +import multiprocessing as mp +import os +import queue +import re +import sys +import threading +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Callable, Mapping +""" + +DEFINITIONS = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef) + + +def statement_names(node: ast.stmt) -> list[str]: + """The module-level names a definition or an assignment binds.""" + if isinstance(node, DEFINITIONS): + return [node.name] + if isinstance(node, ast.Assign): + targets = node.targets + elif isinstance(node, ast.AnnAssign): + targets = [node.target] + else: + return [] + return [n.id for t in targets for n in ast.walk(t) if isinstance(n, ast.Name)] + + +def imported_names(tree: ast.Module) -> set[str]: + return { + (alias.asname or alias.name).split(".")[0] + for node in tree.body + if isinstance(node, (ast.Import, ast.ImportFrom)) + for alias in node.names + } + + +def _loads(node: ast.AST) -> set[str]: + return { + n.id + for n in ast.walk(node) + if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Load) + } + + +def _global_reads(table: symtable.SymbolTable) -> set[str]: + """Every name a scope, or a scope nested in it, reads as a global.""" + names = { + symbol.get_name() + for symbol in table.get_symbols() + if symbol.is_global() and symbol.is_referenced() + } + for child in table.get_children(): + names |= _global_reads(child) + return names + + +def statement_reads(node: ast.stmt, module_table: symtable.SymbolTable) -> set[str]: + """The module-level names a statement reads.""" + if isinstance(node, DEFINITIONS): + tables = [ + child + for child in module_table.get_children() + if child.get_name() == node.name and child.get_lineno() == node.lineno + ] + if len(tables) != 1: + raise SystemExit(f"no single symbol table for {node.name}") + reads = _global_reads(tables[0]) + # Decorators, bases and argument defaults are read in module scope. + outside = list(node.decorator_list) + if isinstance(node, ast.ClassDef): + outside += [*node.bases, *(k.value for k in node.keywords)] + else: + outside += [*node.args.defaults, *(d for d in node.args.kw_defaults if d)] + for expression in outside: + reads |= _loads(expression) + return reads + # An assignment: the names it loads, less a comprehension's or a lambda's + # own variables. + own = { + n.id + for inner in ast.walk(node) + if isinstance(inner, ast.comprehension) + for n in ast.walk(inner.target) + if isinstance(n, ast.Name) + } + own |= { + argument.arg + for inner in ast.walk(node) + if isinstance(inner, ast.Lambda) + for argument in ast.walk(inner.args) + if isinstance(argument, ast.arg) + } + return _loads(node) - own + + +def closure(source: str) -> list[ast.stmt]: + """The harness statements the entry points need, in the harness's order.""" + tree = ast.parse(source) + module_table = symtable.symtable(source, HARNESS.name, "exec") + imported = imported_names(tree) + by_name: dict[str, ast.stmt] = {} + for node in tree.body: + for name in statement_names(node): + if name in by_name: + raise SystemExit(f"{name} is defined twice at module level") + by_name[name] = node + missing = [name for name in ENTRY_POINTS if name not in by_name] + if missing: + raise SystemExit(f"entry points not in the harness: {missing}") + wanted: set[int] = set() + seen: set[str] = set() + unresolved: set[str] = set() + stack = list(ENTRY_POINTS) + while stack: + name = stack.pop() + if name in seen: + continue + seen.add(name) + node = by_name[name] + wanted.add(id(node)) + for read in statement_reads(node, module_table): + if read in by_name: + stack.append(read) + elif ( + read not in imported + and not hasattr(builtins, read) + and read not in MODULE_NAMES + ): + unresolved.add(read) + if unresolved: + raise SystemExit(f"names the closure reads but nothing defines: {unresolved}") + return [node for node in tree.body if id(node) in wanted] + + +def _span(lines: list[str], node: ast.stmt) -> tuple[int, int]: + """A statement's 1-based lines, from its first decorator, extended up over + the comment lines directly above it.""" + start = min([node.lineno, *(d.lineno for d in getattr(node, "decorator_list", []))]) + while start > 1 and lines[start - 2].lstrip().startswith("#"): + start -= 1 + return start, node.end_lineno + + +def render(source: str) -> str: + """core.py's text for a harness source.""" + lines = source.splitlines() + parts = [HEADER, "\n", IMPORTS] + previous_end, previous_was_definition = None, False + for node in closure(source): + start, end = _span(lines, node) + definition = isinstance(node, DEFINITIONS) + if previous_end is None: + gap = "\n" + else: + between = lines[previous_end : start - 1] + if all(not text.strip() for text in between): + # Neighbours in the harness keep the harness's spacing. + gap = "\n" * len(between) + else: + gap = "\n\n" if definition or previous_was_definition else "\n" + parts.append(gap + "\n".join(lines[start - 1 : end]) + "\n") + previous_end, previous_was_definition = end, definition + return "".join(parts) + + +def main(argv: list[str] | None = None) -> int: + argv = sys.argv[1:] if argv is None else argv + text = render(HARNESS.read_text()) + if "--check" in argv: + if not CORE.exists() or CORE.read_text() != text: + print( + f"{CORE.relative_to(ROOT)} is not the calculator in " + f"{HARNESS.relative_to(ROOT)}; run scripts/sync_calculator_core.py" + ) + return 1 + return 0 + CORE.write_text(text) + print(f"wrote {CORE.relative_to(ROOT)}: {len(text.splitlines())} lines") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_calculator_core.py b/tests/test_calculator_core.py new file mode 100644 index 00000000..2b34d71c --- /dev/null +++ b/tests/test_calculator_core.py @@ -0,0 +1,658 @@ +"""The calculator package against the harness it is copied from. + +``policybench_calculator.core`` must be the calculator inside +``scripts/tool_pilot_argon.py`` and nothing else: the same definitions, the +same tool schemas, the same reading of every call. The harness cannot import +the package while the confirmatory runner pins it +(``scripts/confirmatory_run.py``, ``TREATMENT_PATHS``), so these tests hold +the two copies together. None of them needs the engine. +""" + +from __future__ import annotations + +import ast +import builtins +import copy +import hashlib +import itertools +import json +import symtable +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest +from hypothesis import given, settings +from hypothesis import strategies as st + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT), str(ROOT / "scripts")] + +import sync_calculator_core as sync # noqa: E402 +import tool_pilot_argon as pilot # noqa: E402 + +from policybench_calculator import core # noqa: E402 + +# Every set of features an arm can offer: concise only beside explain. +FEATURE_SETS = [ + frozenset(chosen) + for size in range(len(pilot.TOOL_FEATURES) + 1) + for chosen in itertools.combinations(pilot.TOOL_FEATURES, size) + if not (pilot.CONCISE in chosen and pilot.EXPLAIN not in chosen) +] + + +def _statements(path: Path) -> dict[str, ast.stmt]: + return { + name: node + for node in ast.parse(path.read_text()).body + for name in sync.statement_names(node) + } + + +def test_core_is_the_sync_scripts_output_for_this_harness(): + assert sync.CORE.read_text() == sync.render(sync.HARNESS.read_text()), ( + "policybench_calculator/core.py is stale: run scripts/sync_calculator_core.py" + ) + assert sync.main(["--check"]) == 0 + + +def test_every_definition_is_the_harnesss(): + """Independent of how the sync script slices the source: each module-level + name in the copy has the harness's syntax tree, in the harness's order.""" + harness, copied = _statements(sync.HARNESS), _statements(sync.CORE) + assert set(sync.ENTRY_POINTS) <= set(copied) + assert len(copied) > 100 + for name, node in copied.items(): + assert name in harness, f"{name} is not in the harness" + assert ast.dump(node) == ast.dump(harness[name]), name + assert list(copied) == [name for name in harness if name in copied] + + +def test_the_copy_defines_every_name_it_reads(): + source = sync.CORE.read_text() + table = symtable.symtable(source, "core.py", "exec") + for node in ast.parse(source).body: + if not sync.statement_names(node): + continue + for name in sync.statement_reads(node, table): + assert ( + hasattr(core, name) + or hasattr(builtins, name) + or name in sync.MODULE_NAMES + ), name + + +def test_the_copys_values_are_the_harnesss(): + """Every constant: the limits, the descriptions, the wording tables, and + the paths (so the package sits where the harness's files are).""" + compared = 0 + for name in _statements(sync.CORE): + mine, theirs = getattr(core, name), getattr(pilot, name) + if callable(mine) or name == "_STATED_ENGINE": + # Functions and classes are compared by syntax tree above; the + # stated engine is run state, compared under stating_engine below. + continue + assert mine == theirs, name + compared += 1 + assert compared > 40 + assert core.ROOT == pilot.ROOT == ROOT + assert core.FIX_MODULE == pilot.FIX_MODULE and core.SNAPSHOT == pilot.SNAPSHOT + + +@pytest.mark.parametrize("engine", ["2.41.0", "2.60.4"]) +def test_both_build_the_same_tool_for_every_feature_set(engine): + assert len(FEATURE_SETS) == 96 + with pilot.stating_engine(engine), core.stating_engine(engine): + for features in FEATURE_SETS: + mine = core.calculate_tool_schema(features=features) + theirs = pilot.calculate_tool_schema(features=features) + # The dumps compare key order too: it is what a provider is sent. + assert json.dumps(mine) == json.dumps(theirs), sorted(features) + assert f"policyengine-us {engine}" in mine["function"]["description"] + for version in (1, 2): + assert core.calculate_tool_schema(version) == pilot.calculate_tool_schema( + version + ) + assert core.engine_text("policyengine-us 2.41.0") == pilot.engine_text( + "policyengine-us 2.41.0" + ) + + +# sha256 of each feature set's tool schema (json.dumps with sorted keys, as the +# harness's profile_treatment hashes it) in the household records of the +# October and November 2026 development runs, which ran on policyengine-us +# 2.60.4. The records themselves stay outside the repository with their +# household set; a schema's hash says nothing about a household. +RECORDED_SCHEMA_SHA256 = { + "explain": "c06768afd93c2acbe396dea6dbae9340703bbe7c2b3702cd68825e56e2cf85c9", + "flat": "bb46d278e7236d5c1c8b5ec4d9b50ed568b13bd24d278a44959e7ff21518aecd", + "labels": "7950b061b162f21ac0acdfa424e0199357017c12251eecd188718a1ef5af186b", + "names": "552d7e25b054668128b4a64c82a01f067fe29bd27fef26d82690dabf440a6f88", + "overrides": "569c424e860ffe7d66b45b76856d6a62ca44acc32415d3c588a6ef2891fef2d0", + "placement": "ef387526f076662ae0e1145e5c5dfaf49257455c966c0f1ba1620b7f7b92f36c", + "explain+concise": ( + "461caed5af5392b2563bcb7017746b8c29f637af3158725bc74815f9a2a444b8" + ), + "names+placement+overrides+explain": ( + "4776fa0d4f6421331ebd134643366e0c6dc16f4a84905cce818272c531a1c853" + ), + "names+labels+placement+overrides+flat": ( + "c21b6cd91e9cfa20a97bfdd7b83db892709d3d1e813865947e5d94b1336c0925" + ), + "names+labels+overrides+explain+concise+flat": ( + "8fff7ef8923ab8ff63539c065323bda08f341281d4fa05c672517766876b5d52" + ), + "names+labels+placement+explain+concise+flat": ( + "d658f8af57651d12d9524d5bcbd692bf7908e53b5fc2c3e4a30e9cf41358a34c" + ), + "labels+placement+overrides+explain+concise+flat": ( + "8510fe574c6948be9fcc96d4cd3e785e447a645cae7ccb3d3fc429cfea05a059" + ), + "names+placement+overrides+explain+concise+flat": ( + "5ba88703cdf1d668b7300ad52eb4c71ed3db5a9996140c60120bfa9748d6c768" + ), + "names+labels+placement+overrides+explain+concise": ( + "12420320789d05768a091bf926bf5bd37d10c37499fa419c2228763f2911d910" + ), + "names+labels+placement+overrides+explain+flat": ( + "899583b1d27c0f1277630b5bd050b48b8b8678d02d12d9885b19f5faf7532952" + ), + # Version 3 (the pe3 and web+pe3 arms): all seven features. + "names+labels+placement+overrides+explain+concise+flat": ( + "8fff7ef8923ab8ff63539c065323bda08f341281d4fa05c672517766876b5d52" + ), +} + + +def test_the_package_builds_the_schemas_the_development_runs_recorded(): + with core.stating_engine("2.60.4"): + for written, recorded in RECORDED_SCHEMA_SHA256.items(): + schema = core.calculate_tool_schema(features=frozenset(written.split("+"))) + digest = hashlib.sha256( + json.dumps(schema, sort_keys=True).encode() + ).hexdigest() + assert digest == recorded, written + assert ( + RECORDED_SCHEMA_SHA256["+".join(core.TOOL_FEATURES)] + == RECORDED_SCHEMA_SHA256["names+labels+overrides+explain+concise+flat"] + ), "placement changes no schema text beside flat" + + +@pytest.mark.parametrize( + "arm", + [ + *pilot.ARMS, + "pe:names", + "pe:flat+names", + "pe:explain+concise", + "pe:concise", + "pe:names+telepathy", + "pe:", + "PE3", + "", + None, + ], +) +def test_arms_name_the_same_features(arm): + def read(module): + try: + return module.arm_features(arm) + except SystemExit as refusal: + return ("refused", str(refusal)) + + assert read(core) == read(pilot) + + +# A registry in each copy's own VariableInfo: entity, type, label, period, +# named values, and whether the engine computes it. +VARIABLES = { + "age": ("person", "int", "age", "year"), + "employment_income": ("person", "float", "employment income", "year"), + "is_tax_unit_head": ("person", "bool", "head", "year"), + "is_tax_unit_spouse": ("person", "bool", "spouse", "year"), + "traditional_401k_contributions": ("person", "float", "401(k)", "year", None, True), + "traditional_401k_contributions_desired": ("person", "float", "asked", "year"), + "snap": ("spm_unit", "float", "SNAP", "month", None, True), + "pre_subsidy_rent": ("person", "float", "rent", "year"), + "spm_unit_energy_subsidy": ("spm_unit", "float", "energy", "year"), + "qualified_passenger_vehicle_loan_interest": ( + "household", + "float", + "car loan", + "year", + ), + "state_code": ("household", "Enum", "state", "year", ("CA", "LA")), + "tax_unit_childcare_expenses": ("tax_unit", "float", "childcare", "year"), + "marital_unit_flag": ("marital_unit", "bool", "flag", "year"), + "has_esi": ("person", "bool", "ESI", "year"), + "hours_worked_last_week": ("person", "float", "hours", "year"), + "weekly_hours_worked_before_lsr": ("person", "float", "hours", "year"), + "school_meal_tier": ("spm_unit", "Enum", "tier", "year", ("FREE", "PAID"), True), + "filing_status": ("tax_unit", "Enum", "status", "year", ("SINGLE", "JOINT"), True), + "family_note": ("family", "str", "note", "year"), +} +REGISTRIES = { + module: {name: module.VariableInfo(*fields) for name, fields in VARIABLES.items()} + for module in (pilot, core) +} + +# Names as a model writes them: the engine's, the same with spaces, hyphens +# or capitals, labels the prompts show, benchmark output keys, and nonsense. +_WRITTEN = sorted(VARIABLES) +_WRITTEN += [name.replace("_", " ") for name in _WRITTEN[::2]] +_WRITTEN += [name.replace("_", "-").title() for name in _WRITTEN[1:12:3]] +_WRITTEN += [ + "gross wages and salaries", + "Gross wages and salaries", + "usual weekly hours worked", + "has employer-sponsored insurance", + "state", + "free_school_meals_eligible", + "federal_income_tax", + "snap_benefits", + "members", + "telepathy", + "", + " age ", +] +written_names = st.sampled_from(_WRITTEN) +scalars = st.one_of( + st.integers(-3, 10**6), + st.floats(width=32), + st.booleans(), + st.sampled_from(["CA", "LA", "FREE", "JOINT", "x", "", "40"]), + st.none(), +) +periods = st.sampled_from(["2026", "2026-01", "2026-13", "1999", "year", ""]) +values = st.one_of( + scalars, + st.dictionaries(periods, scalars, max_size=3), + st.lists(scalars, max_size=2), +) +facts = st.dictionaries(written_names, values, max_size=6) +person_names = st.sampled_from(["head", "kid", "third", "", "n" * 70]) +flat_people = st.lists( + st.one_of( + st.fixed_dictionaries( + {}, + optional={ + "name": st.one_of(person_names, st.none(), st.integers(0, 2)), + "role": st.sampled_from(["head", "spouse", "dependent", "child", None]), + "facts": st.one_of(facts, st.just([])), + "age": st.integers(0, 90), + }, + ), + st.just("someone"), + ), + max_size=4, +) +households = st.one_of( + st.fixed_dictionaries( + {}, + optional={ + "state": st.sampled_from(["CA", "LA", "ZZ", None, 6]), + "people": st.one_of(flat_people, st.just({})), + "household_facts": st.one_of(facts, st.just([]), st.none()), + "notes": st.just("extra"), + }, + ), + st.sampled_from(["not json", None, 3]), +) +members = st.one_of( + st.lists(st.sampled_from(["head", "kid", "third", "ghost"]), max_size=3), + st.sampled_from(["head", None]), +) +units = st.dictionaries( + st.sampled_from(["first", "second", ""]), + st.one_of( + st.builds(lambda inputs, people: {**inputs, "members": people}, facts, members), + facts, + st.just("unit"), + ), + max_size=2, +) +situations = st.one_of( + st.fixed_dictionaries( + {}, + optional={ + "people": st.one_of( + st.dictionaries(person_names, st.one_of(facts, st.just(3)), max_size=3), + st.just([]), + ), + **{group: st.one_of(units, st.just({})) for group in pilot.GROUPS}, + "axes": st.just([]), + }, + ), + st.sampled_from(["{not json", None, []]), +) + + +def _maybe_json(strategy): + """A value, or the same value written as a JSON string, as a model writes + the `situation` and `household` arguments.""" + return st.one_of(strategy, strategy.map(json.dumps)) + + +name_lists = st.one_of( + st.lists(written_names, max_size=4), + written_names, + st.sampled_from([None, [3], {}]), +) +calls = st.fixed_dictionaries( + {}, + optional={ + "situation": _maybe_json(situations), + "household": _maybe_json(households), + "variables": name_lists, + "period": st.sampled_from(["2026", "2026-02", 2026, "", None, "soon", True]), + "explain": name_lists, + "detail": st.sampled_from(["brief", "full", "long", None]), + "__tool_features__": st.just(["names"]), + }, +) +messages = st.one_of(_maybe_json(calls), st.sampled_from(["{not json", [], None, 7])) + + +# The strategies above write mostly nonsense, which exercises every refusal. +# The ones below write a household the validator accepts and then make up to +# two slips a model makes, so both copies are also compared on requests they +# accept, with and without notes. +PERSON_INPUTS = [ + name + for name, fields in VARIABLES.items() + if fields[0] == "person" and not name.startswith("is_tax_unit_") +] +INPUTS_OF = { + entity: [name for name, fields in VARIABLES.items() if fields[0] == entity] + for entity in pilot.GROUPS.values() +} +UNIT_INPUTS = [name for names in INPUTS_OF.values() for name in names] +PROMPT_LABELS = { + "employment_income": "gross wages and salaries", + "hours_worked_last_week": "usual weekly hours worked", + "has_esi": "has employer-sponsored insurance", +} +SLIPS = ( + "spaces", + "capitals", + "label", + "unknown name", + "wrong type", + "dated", + "bad period", + "misplaced", + "stray key", + "written output", + "unknown output", + "no outputs", + "other shape", + "explain", + "detail", + "forged features", + "people", +) + + +def _typed(name: str): + """A value of the variable's own type.""" + value_type, named = VARIABLES[name][1], (*VARIABLES[name], None)[4] + if value_type == "int": + return st.integers(0, 90) + if value_type == "float": + return st.one_of(st.integers(0, 10**6), st.floats(0, 10**6, width=32)) + if value_type == "bool": + return st.booleans() + if value_type == "Enum": + return st.sampled_from(named) + return st.sampled_from(["note", ""]) + + +@st.composite +def _inputs(draw, names, max_size=3): + chosen = draw(st.lists(st.sampled_from(names), max_size=max_size, unique=True)) + return {name: draw(_typed(name)) for name in chosen} + + +@st.composite +def written_cases(draw): + """(features, message, framed): a call the validator accepts, in the shape + its features take (`household` under flat, else `situation`), with none, + one or two of SLIPS made in it.""" + features = draw(st.sampled_from(FEATURE_SETS)) + flat = pilot.FLAT in features + names = ["head", "kid", "third"][: draw(st.sampled_from([1, 2, 2, 3]))] + people = {name: draw(_inputs(PERSON_INPUTS)) for name in names} + units = { + entity: draw(_inputs(INPUTS_OF[entity], 2)) if INPUTS_OF[entity] else {} + for entity in pilot.GROUPS.values() + } + if flat: + household_facts = {k: v for inputs in units.values() for k, v in inputs.items()} + state = household_facts.pop("state_code", "CA") + payload = { + "state": state, + "people": [ + {"role": "dependent" if index else "head", "facts": facts} + for index, facts in enumerate(people.values()) + ], + "household_facts": household_facts, + } + containers = [person["facts"] for person in payload["people"]] + unit_containers = [payload["household_facts"]] + else: + payload = {"people": people} + for group, entity in pilot.GROUPS.items(): + if units[entity] or draw(st.booleans()): + payload[group] = { + f"{entity}_1": {"members": list(names), **units[entity]} + } + containers = list(people.values()) + unit_containers = [ + unit for group in pilot.GROUPS for unit in payload.get(group, {}).values() + ] + known = st.sampled_from(sorted(VARIABLES)) + arguments = {"variables": draw(st.lists(known, min_size=1, max_size=3))} + if draw(st.booleans()): + arguments["period"] = draw(st.sampled_from(["2026", "2026-02", 2026])) + if pilot.EXPLAIN in features and draw(st.booleans()): + arguments["explain"] = draw(st.lists(known, max_size=3)) + if pilot.CONCISE in features and draw(st.booleans()): + arguments["detail"] = draw(st.sampled_from(["brief", "full"])) + + def a_fact(pool): + """A container that holds a fact, and one of its names; or None.""" + holding = [facts for facts in pool if set(facts) - {"members"}] + if not holding: + return None, None + facts = draw(st.sampled_from(holding)) + return facts, draw(st.sampled_from(sorted(set(facts) - {"members"}))) + + for slip in draw(st.sampled_from([[], [], [0], [0], [0, 1]])): + del slip + kind = draw(st.sampled_from(SLIPS)) + facts, name = a_fact(containers + unit_containers) + if kind in ("spaces", "capitals", "label", "unknown name") and facts: + written = { + "spaces": name.replace("_", " "), + "capitals": name.replace("_", "-").title(), + "label": PROMPT_LABELS.get(name, name.upper()), + "unknown name": "telepathy", + }[kind] + facts[written] = facts.pop(name) + elif kind == "wrong type" and facts: + facts[name] = draw(scalars) + elif kind in ("dated", "bad period") and facts: + period = "2026-01" if kind == "dated" else draw(periods) + facts[name] = {period: facts[name]} + elif kind == "misplaced": + source, name = a_fact(draw(st.sampled_from([containers, unit_containers]))) + target = draw(st.sampled_from(containers + unit_containers)) + if source is not None and target is not source: + target[name] = source.pop(name) + elif kind == "stray key": + draw(st.sampled_from([payload, arguments, *containers]))["axes"] = [] + elif kind == "written output": + arguments["variables"] = draw(st.lists(written_names, max_size=3)) + elif kind == "unknown output": + arguments["variables"] = [*arguments["variables"], "snap_benefits"] + elif kind == "no outputs": + arguments["variables"] = draw(st.sampled_from([[], None, "age", [3]])) + elif kind == "explain": + arguments["explain"] = draw(st.lists(written_names, max_size=4)) + elif kind == "detail": + arguments["detail"] = draw(st.sampled_from(["brief", "long", None])) + elif kind == "forged features": + arguments["__tool_features__"] = ["names"] + elif kind == "people" and flat: + payload["people"].append( + draw( + st.sampled_from( + [ + {"role": "head", "facts": {}}, + {"role": "spouse", "facts": {"age": 40}}, + {"role": "child", "facts": {}}, + {"role": "dependent", "name": "head", "facts": {}}, + {"role": "dependent", "facts": {"is_tax_unit_head": True}}, + ] + ) + ) + ) + elif kind == "people" and unit_containers: + draw(st.sampled_from(unit_containers))["members"] = draw( + st.sampled_from([[], ["ghost"], [names[0], names[0]], "head"]) + ) + elif kind == "other shape": + flat = not flat + arguments["household" if flat else "situation"] = ( + json.dumps(payload) if draw(st.booleans()) else payload + ) + message = json.dumps(arguments) if draw(st.booleans()) else arguments + return features, message, draw(st.sampled_from([True] * 7 + [False])) + + +def _reading(module, features, arguments, framed) -> str: + """How a copy's worker reads one message, as text (so NaN compares equal + and key order counts).""" + message = copy.deepcopy(arguments) + if framed: + message = module.tool_call_frame(features, message) + try: + outcome = module.worker_request(message, REGISTRIES[module]) + except Exception as error: # the two must fail alike too + outcome = ("raised", type(error).__name__, str(error)) + return json.dumps(outcome) + + +@settings(max_examples=1000, deadline=None, derandomize=True, database=None) +@given(st.sampled_from(FEATURE_SETS), messages, st.booleans()) +def test_both_refuse_any_malformed_call_alike(features, arguments, framed): + assert _reading(core, features, arguments, framed) == _reading( + pilot, features, arguments, framed + ) + + +@settings(max_examples=2000, deadline=None, derandomize=True, database=None) +@given(written_cases()) +def test_both_read_any_written_call_alike(case): + assert _reading(core, *case) == _reading(pilot, *case) + + +def test_the_written_calls_are_accepted_and_refused_and_noted(): + """The differential above is worth its name only if its calls reach the + validator's every outcome: accepted, accepted with notes (a name read, an + input moved, a formula replaced) and refused.""" + tally = {"accepted": 0, "noted": 0, "refused": 0, "unframed": 0} + + @settings(max_examples=600, deadline=None, derandomize=True, database=None) + @given(written_cases()) + def count(case): + features, arguments, framed = case + message = copy.deepcopy(arguments) + if framed: + message = core.tool_call_frame(features, message) + request, error = core.worker_request(message, REGISTRIES[core]) + tally["unframed"] += not framed + tally["accepted" if request is not None else "refused"] += 1 + tally["noted"] += bool(request and request.get("notes")) + assert (request is None) != (error is None) + + count() + assert tally["accepted"] >= 150 and tally["noted"] >= 100, tally + assert tally["refused"] >= 100 and tally["unframed"] >= 15, tally + + +def test_both_read_a_forged_frame_alike(): + arguments = {"situation": {"people": {"head": {"age": 40}}}, "variables": ["age"]} + for frame in ( + ("calculate", ("telepathy",), arguments), + ("calculate", ("concise",), arguments), + ("calculate", ["names"], arguments), + ("calculate", ({},), arguments), + ("calculate", ("names",)), + ("compute", ("names",), arguments), + ): + assert core.worker_request(frame, REGISTRIES[core]) == pilot.worker_request( + frame, REGISTRIES[pilot] + ) + + +class _FakeArray(list): + pass + + +class _FakeSimulation: + def __init__(self, tax_benefit_system, situation): + if "bad" in situation["people"]: + raise ValueError("bad person") + self.populations = { + "person": SimpleNamespace(ids=list(situation["people"])), + "spm_unit": SimpleNamespace(ids=["spm"]), + } + + def calculate(self, name, period): + if name == "snap": + return _FakeArray([1234.567]) + if name == "pre_subsidy_rent": + raise KeyError("no rent") + return _FakeArray([True, float("inf")][: len(self.populations["person"].ids)]) + + +@pytest.mark.parametrize("people", [{"head": {}, "kid": {}}, {"bad": {}}]) +def test_both_execute_a_request_alike(people): + request = { + "situation": {"people": people}, + "variables": ["snap", "age", "pre_subsidy_rent"], + "period": "2026", + "notes": ["read 'Age' as age"], + } + mine = core.execute_request(None, REGISTRIES[core], request, _FakeSimulation) + theirs = pilot.execute_request(None, REGISTRIES[pilot], request, _FakeSimulation) + assert json.dumps(mine) == json.dumps(theirs) + assert ("error" in mine) == ("bad" in people) + + +def _echo_worker(conn, fix_path, reform): + conn.send(("ready", None)) + while True: + args = conn.recv() + if args is None: + return + conn.send(("ok", {"received": args})) + + +@pytest.mark.parametrize("features", [frozenset(), frozenset({"flat", "names"})]) +def test_both_pools_send_their_workers_the_same_message(features): + received = [] + for module in (core, pilot): + pool = module.ToolPool( + size=1, timeout=5.0, worker_target=_echo_worker, tool_features=features + ) + try: + result, _ = pool.call({"x": 1}) + received.append(result) + assert pool.counters() == {"timeouts": 0, "crashes": 0, "lost": 0} + finally: + pool.close() + assert received[0] == received[1] + assert (received[0]["received"] == {"x": 1}) == (not features) From 0a1bf3ad6e0971a696cbdd79af65295659b92523 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 18 Nov 2026 08:13:29 -0500 Subject: [PATCH 2/9] Add the calculator's MCP server and a client with the pilot's tool_call shape policybench_calculator/mcp_server.py serves one tool, calculate_household, with the name, description and input schema the pilot gives a model for the same arm, and answers a call with the text the pilot returns for it. It uses the SDK's low-level Server, which sends the schema as written and validates nothing itself, runs each call in the pilot's worker pool, refuses to start on an engine other than the board's, and offers the engine, board, features and schema hash as a resource. stdio, or Streamable HTTP on 127.0.0.1. policybench_calculator/mcp_client.py is a tool_call (arguments to result and seconds) over an MCP session, for the pilot's loop and for the tests. Work in progress: written against mcp 2.3.0's source and docs but not yet run against the SDK (a disk freeze on the build host holds the install), so the tests that open a session skip until mcp is in the dev extra and the lock. The 14 tests that need no session pass: the calculator offers the pilot's tool and schema hash for five arms, and its answers are the pilot's pool's for accepted, noted, explained and refused calls. Co-Authored-By: Claude Fable 5.2 --- policybench_calculator/__init__.py | 2 + policybench_calculator/mcp_client.py | 169 +++++++++++ policybench_calculator/mcp_server.py | 350 +++++++++++++++++++++ tests/calculator_mcp_fake.py | 116 +++++++ tests/test_calculator_mcp.py | 437 +++++++++++++++++++++++++++ 5 files changed, 1074 insertions(+) create mode 100644 policybench_calculator/mcp_client.py create mode 100644 policybench_calculator/mcp_server.py create mode 100644 tests/calculator_mcp_fake.py create mode 100644 tests/test_calculator_mcp.py diff --git a/policybench_calculator/__init__.py b/policybench_calculator/__init__.py index 43fae0d7..7ad13581 100644 --- a/policybench_calculator/__init__.py +++ b/policybench_calculator/__init__.py @@ -3,4 +3,6 @@ ``core`` is the calculator the tool pilot gives a model: a verbatim copy of the one in ``scripts/tool_pilot_argon.py``, kept exact by ``scripts/sync_calculator_core.py`` and ``tests/test_calculator_core.py``. +``mcp_server`` offers the same tool over the Model Context Protocol, and +``mcp_client`` calls such a server the way the pilot calls its own workers. """ diff --git a/policybench_calculator/mcp_client.py b/policybench_calculator/mcp_client.py new file mode 100644 index 00000000..f738f075 --- /dev/null +++ b/policybench_calculator/mcp_client.py @@ -0,0 +1,169 @@ +"""Call the calculator's MCP server the way the tool pilot calls its own pool. + +``McpToolCall`` is a ``tool_call`` for ``tool_pilot_argon.run_household``: a +callable from a model's arguments to ``(result, seconds)``, as +``core.ToolPool.call`` is. It keeps one MCP session open in a background +thread, so the pilot's synchronous loop can use it unchanged, and it is what +the tests use to check that the server answers a call as the pool does. + +The protocol carries arguments as a JSON object. A model's arguments that are +not one (text that is not JSON, or JSON that is not an object) cannot be sent, +so they are answered here with the validator's own refusal, which it makes +before it reads anything else. + +Needs the ``mcp`` extra (``pip install policybench[mcp]``). +""" + +from __future__ import annotations + +import asyncio +import json +import threading +import time +from typing import Any + +from policybench_calculator import core + +OPEN_TIMEOUT_SECONDS = 120.0 + + +def as_object(arguments: Any) -> dict | None: + """The arguments as the JSON object the protocol carries, or None when + they are not one.""" + if isinstance(arguments, dict): + return arguments + if not isinstance(arguments, str): + return None + if len(arguments) > 2 * core.MAX_SITUATION_CHARS: + return None + try: + parsed = json.loads(arguments) + except (ValueError, RecursionError): + return None + return parsed if isinstance(parsed, dict) else None + + +class McpToolCall: + """A session with a calculator MCP server, callable as the pilot's + ``tool_call``. + + ``server`` is what the SDK's ``Client`` takes: a Streamable HTTP URL, an + ``mcp.StdioServerParameters`` to launch, or (in tests) a server object. + ``mode`` is the ``Client``'s: "auto", or "legacy" for the handshake a + 2025-era client makes. + """ + + def __init__( + self, + server: Any, + mode: str = "auto", + call_timeout: float | None = None, + ): + self._server = server + self._mode = mode + # A call may wait for a worker to start and then for the calculation. + self._call_timeout = ( + core.WORKER_START_TIMEOUT_SECONDS + 2 * core.TOOL_TIMEOUT_SECONDS + if call_timeout is None + else call_timeout + ) + self._client = None + self._loop: asyncio.AbstractEventLoop | None = None + self._stop: asyncio.Event | None = None + self._failure: BaseException | None = None + self._opened = threading.Event() + self._thread = threading.Thread(target=self._run, daemon=True) + self._thread.start() + if not self._opened.wait(OPEN_TIMEOUT_SECONDS): + raise RuntimeError("the MCP session did not open in time") + if self._failure is not None: + raise RuntimeError( + f"the MCP session did not open: {self._failure}" + ) from self._failure + + def _run(self) -> None: + async def session() -> None: + from mcp import Client + + async with Client(self._server, mode=self._mode) as client: + self._client = client + self._loop = asyncio.get_running_loop() + self._stop = asyncio.Event() + self._opened.set() + await self._stop.wait() + + try: + asyncio.run(session()) + except BaseException as error: # reported to the opener or the next call + self._failure = error + finally: + self._opened.set() + + def _await(self, coroutine): + if self._failure is not None or self._loop is None: + coroutine.close() + raise RuntimeError(f"the MCP session is closed: {self._failure}") + future = asyncio.run_coroutine_threadsafe(coroutine, self._loop) + return future.result(self._call_timeout) + + def __enter__(self) -> "McpToolCall": + return self + + def __exit__(self, *exc) -> None: + self.close() + + def close(self) -> None: + if self._loop is not None and self._stop is not None: + self._loop.call_soon_threadsafe(self._stop.set) + self._thread.join(timeout=30) + + @property + def protocol_version(self) -> str: + return self._client.protocol_version + + def tool(self) -> dict: + """The calculator as the server lists it, in the shape of the pilot's + own schema's ``function``: name, description and parameters.""" + listed = self._await(self._client.list_tools()).tools + tools = [tool for tool in listed if tool.name == core.TOOL_NAME] + if len(tools) != 1: + raise RuntimeError( + f"the server lists {[tool.name for tool in listed]}, not one " + f"{core.TOOL_NAME}" + ) + return { + "name": tools[0].name, + "description": tools[0].description, + "parameters": tools[0].input_schema, + } + + def provenance(self) -> dict: + from policybench_calculator.mcp_server import PROVENANCE_URI + + contents = self._await(self._client.read_resource(PROVENANCE_URI)).contents + return json.loads(contents[0].text) + + def __call__(self, arguments: Any) -> tuple[dict, float]: + started = time.perf_counter() + sent = as_object(arguments) + if sent is None: + # The validator's refusal: it is made before the registry or the + # features are read, so no engine is needed to give it. + _, refusal = core.normalize_request(arguments, {}) + return refusal, time.perf_counter() - started + try: + reply = self._await(self._client.call_tool(core.TOOL_NAME, sent)) + texts = [block.text for block in reply.content if block.type == "text"] + if reply.is_error or len(texts) != 1: + raise RuntimeError(f"unexpected tool result: {reply!r}"[:500]) + result = json.loads(texts[0]) + except Exception as error: + # The server or the session failed: infrastructure, as a pool with + # no worker is, so the pilot stops the household and can rerun it. + result = { + "error": core.POOL_UNAVAILABLE, + "message": f"the calculator's MCP server failed: {error}"[ + : core.MAX_MESSAGE_CHARS + ], + } + return result, time.perf_counter() - started diff --git a/policybench_calculator/mcp_server.py b/policybench_calculator/mcp_server.py new file mode 100644 index 00000000..4834f2fe --- /dev/null +++ b/policybench_calculator/mcp_server.py @@ -0,0 +1,350 @@ +"""Offer the PolicyBench calculator over the Model Context Protocol. + + python -m policybench_calculator.mcp_server --arm pe3 [--board DIR] + [--transport stdio|http] [--port 8765] [--workers 2] + +The server has one tool, ``calculate_household``, with the name, description +and input schema the tool pilot gives a model as a function tool for the same +arm (``core.calculate_tool_schema``), and it answers a call with the text the +pilot returns for it (``json.dumps`` of the result). A call runs as the +pilot's does: validated by ``core.normalize_request`` under the arm's +features, then on the board's pinned policyengine-us and convention reform in +a worker process under a timeout (``core.ToolPool``). The server refuses to +start unless the installed policyengine-us is the board's. + +What a client reads besides the tool: + +- the tool's description states the engine, as the function tool's does; +- the server's name, version (this package's) and description (which names + the engine) in the protocol's server information; +- the resource ``policybench://calculator/provenance``: the installed engine, + the board and its pinned reform, the arm's features and the sha256 of the + tool schema, in the form the pilot's household records keep it + (``calculate_tool_sha256``). + +Two things differ from the function tool by the protocol's nature. The +arguments arrive as a JSON object, so text that is not one never reaches the +server (:mod:`policybench_calculator.mcp_client` answers it as the validator +would). And the pilot's limits on a household (8 tool turns, 4 calculations a +turn) belong to its conversation loop, not to the calculator, so the server +does not apply them. + +The http transport listens on 127.0.0.1 only and has no authentication: it is +for a client on this machine. Nothing here is meant to face the internet. + +Needs the ``mcp`` extra (``pip install policybench[mcp]``). +""" + +from __future__ import annotations + +import argparse +import hashlib +import importlib.metadata +import json +import os +import threading +from pathlib import Path +from typing import Any, Callable + +from policybench_calculator import core + +SERVER_NAME = "policybench-calculator" +SERVER_TITLE = "PolicyBench household calculator" +PROVENANCE_URI = "policybench://calculator/provenance" +DEFAULT_ARM = "pe3" +DEFAULT_PORT = 8765 +DEFAULT_WORKERS = 2 +LOOPBACK = "127.0.0.1" + + +def _quiet_worker(conn, fix_path: str, reform: bool, board: str | None = None) -> None: + """The pilot's worker with its standard output pointed at standard error. + + Under the stdio transport the server's standard output is the wire, and a + worker inherits it; anything the engine printed there would corrupt the + protocol.""" + os.dup2(2, 1) + core._worker_main(conn, fix_path, reform, board) + + +def result_text(result: dict) -> str: + """A result as the pilot returns it to a model (its ``add_tool_result``).""" + return json.dumps(result) + + +class Calculator: + """One arm's calculator: the tool as a model is shown it, and the workers + that run it. + + ``start`` builds the worker pool in the background (an engine worker takes + about a minute to start), so a client can list the tool at once; a call + waits for the pool. + """ + + def __init__( + self, + features: frozenset, + board: Path = core.SNAPSHOT, + workers: int = DEFAULT_WORKERS, + timeout: float = core.TOOL_TIMEOUT_SECONDS, + worker_target: Callable | None = None, + check_engine: bool = True, + ): + self.features = core.frame_features(tuple(sorted(features))) + self.board = Path(board) + if check_engine: + core._require_engine(self.board) + self.engine = core.board_engine(self.board) + self.workers = workers + self.timeout = timeout + self._worker_target = worker_target or _quiet_worker + # The texts state the board's engine, as the pilot's run command sets it. + with core.stating_engine(self.engine): + self.schema = core.calculate_tool_schema(features=self.features) + self._pool: core.ToolPool | None = None + self._failure: BaseException | None = None + self._ready = threading.Event() + self._starting: threading.Thread | None = None + + @property + def tool(self) -> dict: + """The tool's name, description and input schema.""" + return self.schema["function"] + + @property + def schema_sha256(self) -> str: + """The schema's hash as the pilot's household records keep it + (``profile_treatment``: sorted keys).""" + return hashlib.sha256( + json.dumps(self.schema, sort_keys=True).encode() + ).hexdigest() + + def provenance(self) -> dict: + try: + package = importlib.metadata.version("policybench") + except importlib.metadata.PackageNotFoundError: + package = None + versions = core._versions() + return { + "server": SERVER_NAME, + "policybench": package, + "policyengine-us": versions["policyengine-us"], + "policyengine-core": versions["policyengine-core"], + "board": str(self.board), + "board_engine": f"policyengine-us {self.engine}", + "fix_module": str(core.FIX_MODULE.relative_to(core.ROOT)), + "fix_module_sha256": core._sha256(core.FIX_MODULE), + "tool": self.tool["name"], + "tool_features": sorted(self.features), + "calculate_tool_sha256": self.schema_sha256, + "tool_timeout_seconds": self.timeout, + "workers": self.workers, + } + + def start(self) -> None: + """Start the workers in the background; returns at once.""" + if self._starting is not None: + return + + def build() -> None: + try: + self._pool = core.ToolPool( + size=self.workers, + timeout=self.timeout, + worker_target=self._worker_target, + board=self.board, + tool_features=self.features, + ) + except BaseException as error: # reported to every waiting call + self._failure = error + finally: + self._ready.set() + + self._starting = threading.Thread(target=build, daemon=True) + self._starting.start() + + def wait_ready(self, timeout: float | None = None) -> None: + """Block until the workers are up; raise what stopped them.""" + self.start() + if not self._ready.wait(timeout): + raise RuntimeError("the calculator's workers did not start in time") + if self._failure is not None: + raise RuntimeError( + f"the calculator's workers did not start: {self._failure}" + ) from self._failure + + def call(self, arguments: Any) -> tuple[dict, float]: + """Run one call: the result and the seconds it took, as the pilot's + ``ToolPool.call`` returns them.""" + self.wait_ready(core.WORKER_START_TIMEOUT_SECONDS) + return self._pool.call(arguments) + + def counters(self) -> dict: + return self._pool.counters() if self._pool is not None else {} + + def close(self) -> None: + if self._starting is not None: + self._ready.wait(core.WORKER_START_TIMEOUT_SECONDS) + if self._pool is not None: + self._pool.close() + self._pool = None + + +def build_server(calculator: Calculator): + """The MCP server for a calculator (the SDK's low-level ``Server``, which + sends the schema as written and applies no validation of its own).""" + import anyio + from mcp import MCPError, types + from mcp.server import Server + + tool = types.Tool( + name=calculator.tool["name"], + description=calculator.tool["description"], + input_schema=calculator.tool["parameters"], + ) + provenance = types.Resource( + uri=PROVENANCE_URI, + name="provenance", + description=( + "The engine this calculator runs, the board whose conventions it " + "follows, and the tool's features and schema hash." + ), + mime_type="application/json", + ) + + async def list_tools(ctx, params) -> types.ListToolsResult: + return types.ListToolsResult(tools=[tool]) + + async def call_tool(ctx, params) -> types.CallToolResult: + if params.name != tool.name: + raise MCPError( + code=types.INVALID_PARAMS, message=f"Unknown tool: {params.name}" + ) + arguments = {} if params.arguments is None else params.arguments + result, _ = await anyio.to_thread.run_sync(calculator.call, arguments) + if result.get("error") == core.POOL_UNAVAILABLE: + # Infrastructure, not an answer: the pilot stops the household + # rather than show a model this result, so it is a protocol error. + raise MCPError(code=types.INTERNAL_ERROR, message=result["message"]) + # Every other result, a validation or engine error included, is the + # answer a model reads, exactly as the function tool returns it. + return types.CallToolResult( + content=[types.TextContent(type="text", text=result_text(result))] + ) + + async def list_resources(ctx, params) -> types.ListResourcesResult: + return types.ListResourcesResult(resources=[provenance]) + + async def read_resource(ctx, params) -> types.ReadResourceResult: + if str(params.uri) != PROVENANCE_URI: + raise MCPError( + code=types.INVALID_PARAMS, message=f"Unknown resource: {params.uri}" + ) + return types.ReadResourceResult( + contents=[ + types.TextResourceContents( + uri=PROVENANCE_URI, + mime_type="application/json", + text=json.dumps(calculator.provenance(), indent=2), + ) + ] + ) + + return Server( + SERVER_NAME, + version=calculator.provenance()["policybench"] or "", + title=SERVER_TITLE, + description=( + f"calculate_household on policyengine-us {calculator.engine} with " + "the PolicyBench reference conventions." + ), + # The schema has no header parameters, so there is nothing for the + # HTTP transport to check a call against. + get_tool_input_schema=lambda name: None, + on_list_tools=list_tools, + on_call_tool=call_tool, + on_list_resources=list_resources, + on_read_resource=read_resource, + ) + + +async def serve_stdio(calculator: Calculator) -> None: + from mcp.server.stdio import stdio_server + + server = build_server(calculator) + calculator.start() + try: + async with stdio_server() as (read_stream, write_stream): + await server.run( + read_stream, write_stream, server.create_initialization_options() + ) + finally: + calculator.close() + + +async def serve_http(calculator: Calculator, port: int = DEFAULT_PORT) -> None: + """Streamable HTTP at http://127.0.0.1:/mcp, once the workers are up + (so an open port means a calculator that can answer).""" + import anyio + import uvicorn + + app = build_server(calculator).streamable_http_app(host=LOOPBACK) + await anyio.to_thread.run_sync(calculator.wait_ready) + try: + await uvicorn.Server( + uvicorn.Config(app, host=LOOPBACK, port=port, log_level="warning") + ).serve() + finally: + calculator.close() + + +def main(argv: list[str] | None = None) -> None: + parser = argparse.ArgumentParser( + prog="policybench-calculator-mcp", + description="Serve the PolicyBench calculator over MCP.", + ) + parser.add_argument( + "--arm", + default=DEFAULT_ARM, + help=( + "the tool pilot arm whose calculator to serve: pe, pe2, pe3, or pe: " + f"plus features joined by + ({', '.join(core.TOOL_FEATURES)})" + ), + ) + parser.add_argument( + "--board", + type=Path, + default=core.SNAPSHOT, + help="the board whose engine and conventions to run (default: the frozen one)", + ) + parser.add_argument("--transport", choices=("stdio", "http"), default="stdio") + parser.add_argument("--port", type=int, default=DEFAULT_PORT) + parser.add_argument("--workers", type=int, default=DEFAULT_WORKERS) + parser.add_argument( + "--timeout", + type=float, + default=core.TOOL_TIMEOUT_SECONDS, + help="seconds a calculation may take (the pilot's is the default)", + ) + args = parser.parse_args(argv) + features = core.arm_features(args.arm) + if features is None: + raise SystemExit(f"arm {args.arm!r} has no calculator") + try: + import anyio + import mcp # noqa: F401 + except ImportError as error: + raise SystemExit( + "the MCP server needs the mcp extra: pip install 'policybench[mcp]'" + ) from error + calculator = Calculator( + features, board=args.board, workers=args.workers, timeout=args.timeout + ) + if args.transport == "http": + anyio.run(serve_http, calculator, args.port) + else: + anyio.run(serve_stdio, calculator) + + +if __name__ == "__main__": + main() diff --git a/tests/calculator_mcp_fake.py b/tests/calculator_mcp_fake.py new file mode 100644 index 00000000..2034b066 --- /dev/null +++ b/tests/calculator_mcp_fake.py @@ -0,0 +1,116 @@ +"""A calculator MCP server on a fake engine, for the transport tests. + + python tests/calculator_mcp_fake.py stdio ARM + python tests/calculator_mcp_fake.py http ARM PORT + +The validator is the real one; only the engine is faked, so the tests need no +policyengine-us and a call's result is a fixed function of its request. +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT), str(ROOT / "tests")] + +from policybench_calculator import core # noqa: E402 +from policybench_calculator.mcp_server import ( # noqa: E402 + Calculator, + serve_http, + serve_stdio, +) + +TIMEOUT_SECONDS = 60.0 +V = core.VariableInfo +REGISTRY = { + "age": V("person", "int", "age", "year"), + "employment_income": V("person", "float", "employment income", "year"), + "is_tax_unit_head": V("person", "bool", "head", "year"), + "is_tax_unit_spouse": V("person", "bool", "spouse", "year"), + "snap": V("spm_unit", "float", "SNAP", "month", computed=True), + "state_code": V("household", "Enum", "state", "year", ("CA", "LA")), + "hours_worked_last_week": V("person", "float", "hours", "year"), + "weekly_hours_worked_before_lsr": V("person", "float", "hours", "year"), +} + + +def fake_result(request: dict) -> dict: + """A result in the engine's shape, fixed by the request alone.""" + out = { + "results": { + name: { + "entity": REGISTRY[name].entity, + "label": REGISTRY[name].label, + "period": request["period"], + "values": {"first": len(name) + 0.25, "second": None}, + } + for name in request["variables"] + } + } + if "notes" in request: + out["notes"] = list(request["notes"]) + if request.get("explain"): + out["explanations"] = { + name: {"steps": [f"{name} ({request['period']}) = 1.0"], "parameters": []} + for name in request["explain"] + } + return out + + +# The labels the prompts show three of these facts under. A worker reads them +# from this table, not from the benchmark's own (core.prompt_labels), which +# loads the engine's data to list the promptable inputs. +LABELS = { + "gross wages and salaries": "employment_income", + "usual weekly hours worked": "hours_worked_last_week", + "state": "state_code", +} + + +def _labels() -> dict: + return { + core._label_key(label): frozenset({(name, False)}) + for label, name in LABELS.items() + } + + +def worker(conn, fix_path, reform, board=None): + """The pilot's worker loop (core._worker_main) without the engine.""" + core.prompt_labels = _labels + conn.send(("ready", None)) + while True: + try: + args = conn.recv() + except EOFError: + return + if args is None: + return + request, error = core.worker_request(args, REGISTRY) + conn.send(("ok", error if error is not None else fake_result(request))) + + +def dead_worker(conn, fix_path, reform, board=None): + """A worker that never reports ready.""" + conn.close() + + +def calculator(arm: str) -> Calculator: + return Calculator( + core.arm_features(arm), + workers=1, + timeout=TIMEOUT_SECONDS, + worker_target=worker, + check_engine=False, + ) + + +if __name__ == "__main__": + import anyio + + transport, arm = sys.argv[1], sys.argv[2] + if transport == "http": + anyio.run(serve_http, calculator(arm), int(sys.argv[3])) + else: + anyio.run(serve_stdio, calculator(arm)) diff --git a/tests/test_calculator_mcp.py b/tests/test_calculator_mcp.py new file mode 100644 index 00000000..8ccc8b83 --- /dev/null +++ b/tests/test_calculator_mcp.py @@ -0,0 +1,437 @@ +"""The calculator's MCP server: the pilot's tool, and the pilot's answers. + +The server must list the tool a model is given as a function tool for the +same arm (name, description, input schema) and answer every call with the +text the pilot returns for it, over each transport and both protocol eras the +SDK serves. The engine is faked (tests/calculator_mcp_fake.py), so a result is +a fixed function of the validated request; the validator and the worker pool +are the real ones. +""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import os +import socket +import subprocess +import sys +import time +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT), str(ROOT / "scripts"), str(ROOT / "tests")] + +import calculator_mcp_fake as fake # noqa: E402 +import tool_pilot_argon as pilot # noqa: E402 + +from policybench_calculator import core, mcp_client, mcp_server # noqa: E402 + +FAKE_SERVER = ROOT / "tests/calculator_mcp_fake.py" +needs_mcp = pytest.mark.skipif( + importlib.util.find_spec("mcp") is None, reason="needs the mcp extra" +) + +FLAT_HOUSEHOLD = { + "state": "CA", + "people": [ + {"role": "head", "facts": {"age": 40, "gross wages and salaries": 30000}}, + {"role": "dependent", "facts": {"age": 8}}, + ], +} +SITUATION = { + "people": {"head": {"age": 40, "employment_income": 30000}, "kid": {"age": 8}}, + "households": {"home": {"members": ["head", "kid"], "state_code": "CA"}}, +} +# Calls as a model writes them, by the arm that takes their shape: accepted, +# accepted with notes, explained, and refused in the validator's several ways. +CALLS = { + "pe3": [ + {"household": FLAT_HOUSEHOLD, "variables": ["snap", "age"]}, + {"household": json.dumps(FLAT_HOUSEHOLD), "variables": ["snap"]}, + { + "household": FLAT_HOUSEHOLD, + "variables": ["snap"], + "explain": ["snap"], + "detail": "full", + "period": "2026-01", + }, + {"household": FLAT_HOUSEHOLD, "variables": ["telepathy"]}, + {"household": {"people": []}, "variables": ["snap"]}, + {"situation": SITUATION, "variables": ["snap"]}, + {"household": "{not json", "variables": ["snap"]}, + {}, + ], + "pe": [ + {"situation": SITUATION, "variables": ["snap", "age"]}, + {"situation": json.dumps(SITUATION), "variables": ["snap"], "period": "2026"}, + {"situation": SITUATION, "variables": ["snap"], "explain": ["snap"]}, + {"situation": {"people": {"head": {"Age": 40}}}, "variables": ["age"]}, + {"household": FLAT_HOUSEHOLD, "variables": ["snap"]}, + {}, + ], +} +# Arguments the protocol cannot carry: not a JSON object. +UNSENDABLE = ["{not json", "[1, 2]", "", ["snap"], "x" * 400_001] + + +_ANSWERS: dict[tuple, str] = {} + + +def _pilot_answers(arm: str, calls) -> list[str]: + """What the pilot returns a model for each call: its own pool's result, + as its add_tool_result writes it. Each answer is computed once.""" + keys = [(arm, json.dumps(arguments)) for arguments in calls] + if any(key not in _ANSWERS for key in keys): + pool = pilot.ToolPool( + size=1, + timeout=fake.TIMEOUT_SECONDS, + worker_target=fake.worker, + tool_features=pilot.arm_features(arm), + ) + try: + for key, arguments in zip(keys, calls): + if key not in _ANSWERS: + _ANSWERS[key] = json.dumps(pool.call(arguments)[0]) + finally: + pool.close() + return [_ANSWERS[key] for key in keys] + + +def _pilot_tool(arm: str, engine: str) -> dict: + with pilot.stating_engine(engine): + return pilot.calculate_tool_schema(features=pilot.arm_features(arm))["function"] + + +@pytest.mark.parametrize("arm", ["pe", "pe2", "pe3", "web+pe3", "pe:flat+names"]) +def test_the_calculator_offers_the_pilots_tool(arm): + calculator = fake.calculator(arm) + assert calculator.engine == pilot.board_engine() + assert calculator.tool == _pilot_tool(arm, calculator.engine) + assert f"policyengine-us {calculator.engine}" in calculator.tool["description"] + # The hash a household record of the pilot keeps for this arm's tool. + profile = pilot.ModelProfile("m", "gpt-x", "chat", "tool", arm=arm) + with pilot.stating_engine(calculator.engine): + recorded = pilot.profile_treatment(profile) + assert calculator.schema_sha256 == recorded["calculate_tool_sha256"] + assert sorted(calculator.features) == recorded["tool_features"] + + +def test_a_calculator_states_its_boards_engine_whatever_else_is_stated(): + with core.stating_engine("9.9.9"): + calculator = fake.calculator("pe3") + assert "9.9.9" in core.calculate_tool_schema(1)["function"]["description"] + assert "9.9.9" not in calculator.tool["description"] + assert f"policyengine-us {pilot.board_engine()}" in calculator.tool["description"] + assert core._STATED_ENGINE == {"version": core.REFERENCE_ENGINE} + + +@pytest.mark.parametrize("arm", sorted(CALLS)) +def test_a_calculators_answer_is_the_pilots(arm): + calculator = fake.calculator(arm) + calculator.start() + try: + answers = [ + mcp_server.result_text(calculator.call(arguments)[0]) + for arguments in CALLS[arm] + ] + assert calculator.counters() == {"timeouts": 0, "crashes": 0, "lost": 0} + finally: + calculator.close() + assert answers == _pilot_answers(arm, CALLS[arm]) + accepted = [text for text in answers if '"results"' in text] + assert 2 <= len(accepted) < len(answers), "both outcomes are covered" + + +def test_the_calculator_refuses_an_engine_other_than_the_boards(monkeypatch): + monkeypatch.setattr( + core, + "_versions", + lambda: {"policyengine-us": "0.0.1", "policyengine-core": "0"}, + ) + with pytest.raises(SystemExit, match="policyengine-us 0.0.1 is installed"): + mcp_server.Calculator(core.arm_features("pe3"), worker_target=fake.worker) + + +def test_a_calculator_whose_workers_do_not_start_says_so(): + calculator = mcp_server.Calculator( + core.arm_features("pe"), + workers=1, + worker_target=fake.dead_worker, + check_engine=False, + ) + with pytest.raises(RuntimeError, match="workers did not start"): + calculator.call({}) + calculator.close() + + +def test_the_provenance_names_the_engine_the_board_and_the_tool(): + calculator = fake.calculator("pe3") + provenance = calculator.provenance() + assert provenance["board_engine"] == f"policyengine-us {pilot.board_engine()}" + assert provenance["policyengine-us"] == pilot._versions()["policyengine-us"] + assert provenance["fix_module_sha256"] == pilot.FIX_MODULE_SHA256 + assert provenance["tool"] == pilot.TOOL_NAME + assert provenance["tool_features"] == sorted(pilot.TOOL_FEATURES) + assert provenance["calculate_tool_sha256"] == calculator.schema_sha256 + assert json.loads(json.dumps(provenance)) == provenance + + +def test_the_command_refuses_an_arm_without_a_calculator(): + for arm, message in ( + ("web", "has no calculator"), + ("none", "has no calculator"), + ("pe:telepathy", "unknown tool features"), + ("pe:concise", "concise feature needs explain"), + ): + with pytest.raises(SystemExit, match=message): + mcp_server.main(["--arm", arm]) + + +def test_arguments_that_are_not_an_object_get_the_validators_refusal(): + """The protocol cannot carry them, so the client answers as the pilot's + worker would have: the same refusal, whatever the arm's features.""" + assert [mcp_client.as_object(arguments) for arguments in UNSENDABLE] == [None] * 5 + assert mcp_client.as_object(None) is None + assert mcp_client.as_object('{"variables": []}') == {"variables": []} + assert mcp_client.as_object({"a": 1}) == {"a": 1} + refusals = [ + json.dumps(core.normalize_request(arguments, {})[1]) for arguments in UNSENDABLE + ] + for arm in ("pe", "pe3"): + assert refusals == _pilot_answers(arm, UNSENDABLE) + # No arguments at all (None) get the same refusal from a pool that frames + # its messages, as every arm with a feature does. The pilot's version 1 + # pool sends arguments bare, and a bare None is its worker's stop signal, + # so there the pilot reports a failed worker instead; the client does not + # copy that. + nothing = json.dumps(core.normalize_request(None, {})[1]) + assert [nothing] == _pilot_answers("pe3", [None]) + assert "tool worker failed" in _pilot_answers("pe", [None])[0] + + +# --------------------------------------------------------------------------- +# Over the protocol. +# --------------------------------------------------------------------------- + + +def _text(result) -> str: + assert result.is_error is False + assert result.structured_content is None + (block,) = result.content + assert block.type == "text" + return block.text + + +def _listed(tools) -> dict: + (tool,) = tools + assert tool.output_schema is None + return { + "name": tool.name, + "description": tool.description, + "parameters": tool.input_schema, + } + + +@needs_mcp +@pytest.mark.parametrize("arm", sorted(CALLS)) +def test_the_server_lists_the_pilots_tool_and_gives_the_pilots_answers(arm): + import anyio + from mcp import Client, MCPError + + calculator = fake.calculator(arm) + server = mcp_server.build_server(calculator) + seen = {} + + async def session(): + async with Client(server, raise_exceptions=True) as client: + seen["tool"] = _listed((await client.list_tools()).tools) + seen["answers"] = [ + _text(await client.call_tool(pilot.TOOL_NAME, arguments)) + for arguments in CALLS[arm] + ] + seen["no arguments"] = _text(await client.call_tool(pilot.TOOL_NAME)) + with pytest.raises(MCPError, match="Unknown tool"): + await client.call_tool("submit_outputs", {}) + (resource,) = (await client.list_resources()).resources + assert resource.uri == mcp_server.PROVENANCE_URI + (contents,) = (await client.read_resource(resource.uri)).contents + seen["provenance"] = json.loads(contents.text) + seen["server"] = client.server_info + + calculator.start() + try: + anyio.run(session) + finally: + calculator.close() + assert seen["tool"] == _pilot_tool(arm, calculator.engine) + assert seen["answers"] == _pilot_answers(arm, CALLS[arm]) + assert seen["no arguments"] == _pilot_answers(arm, [{}])[0] + assert seen["provenance"] == calculator.provenance() + assert seen["server"].name == mcp_server.SERVER_NAME + assert calculator.engine in seen["server"].description + + +@needs_mcp +def test_a_pool_with_no_worker_is_a_protocol_error_not_an_answer(monkeypatch): + import anyio + from mcp import Client, MCPError + + calculator = fake.calculator("pe") + unavailable = { + "error": core.POOL_UNAVAILABLE, + "message": "no tool worker is available", + } + monkeypatch.setattr(calculator, "call", lambda arguments: (unavailable, 0.0)) + + async def session(): + async with Client(mcp_server.build_server(calculator)) as client: + with pytest.raises(MCPError, match="no tool worker is available"): + await client.call_tool(pilot.TOOL_NAME, CALLS["pe"][0]) + + anyio.run(session) + with mcp_client.McpToolCall(mcp_server.build_server(calculator)) as tool_call: + result, _ = tool_call(CALLS["pe"][0]) + assert result["error"] == pilot.POOL_UNAVAILABLE + + +def _launch(arm: str): + from mcp import StdioServerParameters + + return StdioServerParameters( + command=sys.executable, + args=[str(FAKE_SERVER), "stdio", arm], + env=dict(os.environ), + ) + + +@needs_mcp +def test_over_stdio_the_handshake_era_reads_the_same_tool_and_answers(): + """A 2025-era client (initialize, then tools/list and tools/call) over the + stdio transport, with the server in its own process.""" + import anyio + from mcp import ClientSession + from mcp.client.stdio import stdio_client + + arm, seen = "pe3", {} + + async def session(): + async with stdio_client(_launch(arm)) as (read_stream, write_stream): + async with ClientSession(read_stream, write_stream) as client: + seen["version"] = (await client.initialize()).protocol_version + seen["tool"] = _listed((await client.list_tools()).tools) + seen["answers"] = [ + _text(await client.call_tool(pilot.TOOL_NAME, arguments)) + for arguments in CALLS[arm] + ] + + anyio.run(session) + assert seen["version"] == "2025-11-25" + assert seen["tool"] == _pilot_tool(arm, pilot.board_engine()) + assert seen["answers"] == _pilot_answers(arm, CALLS[arm]) + + +@pytest.fixture +def http_server(): + """The fake-engine server over Streamable HTTP on a free local port.""" + with socket.socket() as probe: + probe.bind((mcp_server.LOOPBACK, 0)) + port = probe.getsockname()[1] + process = subprocess.Popen( + [sys.executable, str(FAKE_SERVER), "http", "pe3", str(port)], + env=dict(os.environ), + ) + try: + deadline = time.monotonic() + 120 + while True: + if process.poll() is not None: + raise RuntimeError(f"the server exited with {process.returncode}") + try: + socket.create_connection((mcp_server.LOOPBACK, port), 0.5).close() + break + except OSError: + if time.monotonic() > deadline: + raise RuntimeError("the server did not open its port") from None + time.sleep(0.2) + yield f"http://{mcp_server.LOOPBACK}:{port}/mcp" + finally: + process.terminate() + try: + process.wait(timeout=20) + except subprocess.TimeoutExpired: + process.kill() + + +@needs_mcp +def test_over_http_both_protocol_eras_read_the_same_tool_and_answers(http_server): + import anyio + from mcp import Client, ClientSession + from mcp.client.streamable_http import streamable_http_client + + arm, seen = "pe3", {} + + async def modern(): + async with Client(http_server) as client: + seen["modern version"] = client.protocol_version + seen["modern tool"] = _listed((await client.list_tools()).tools) + seen["modern answers"] = [ + _text(await client.call_tool(pilot.TOOL_NAME, arguments)) + for arguments in CALLS[arm] + ] + + async def handshake(): + async with streamable_http_client(http_server) as (read_stream, write_stream): + async with ClientSession(read_stream, write_stream) as client: + seen["handshake version"] = (await client.initialize()).protocol_version + seen["handshake tool"] = _listed((await client.list_tools()).tools) + seen["handshake answers"] = [ + _text(await client.call_tool(pilot.TOOL_NAME, arguments)) + for arguments in CALLS[arm] + ] + + anyio.run(modern) + anyio.run(handshake) + assert seen["modern version"] == "2026-07-28" + assert seen["handshake version"] == "2025-11-25" + tool, answers = ( + _pilot_tool(arm, pilot.board_engine()), + _pilot_answers(arm, CALLS[arm]), + ) + assert seen["modern tool"] == seen["handshake tool"] == tool + assert seen["modern answers"] == seen["handshake answers"] == answers + + +@needs_mcp +@pytest.mark.parametrize("mode", ["auto", "legacy"]) +def test_the_client_is_a_tool_call_for_the_pilots_loop(mode): + """McpToolCall has ToolPool.call's shape, and gives its results: for + arguments written as an object, as JSON text, and as text the protocol + cannot carry.""" + arm = "pe3" + calls = [ + *CALLS[arm], + *[json.dumps(arguments) for arguments in CALLS[arm]], + *UNSENDABLE, + None, + ] + with mcp_client.McpToolCall(_launch(arm), mode=mode) as tool_call: + assert tool_call.tool() == _pilot_tool(arm, pilot.board_engine()) + assert tool_call.provenance()["tool_features"] == sorted(pilot.TOOL_FEATURES) + results = [tool_call(arguments) for arguments in calls] + version = tool_call.protocol_version + assert version == ("2025-11-25" if mode == "legacy" else "2026-07-28") + assert all(isinstance(seconds, float) and seconds >= 0 for _, seconds in results) + assert [json.dumps(result) for result, _ in results] == _pilot_answers(arm, calls) + + +def test_the_schema_hash_is_the_sorted_dumps_sha256(): + calculator = fake.calculator("pe") + assert ( + calculator.schema_sha256 + == hashlib.sha256( + json.dumps(calculator.schema, sort_keys=True).encode() + ).hexdigest() + ) From e023ad6305ae3b8f54b28726ea833f83abff842c Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 18 Nov 2026 08:17:37 -0500 Subject: [PATCH 3/9] Add a replay of recorded calls through the harness's calculator and the package's scripts/replay_calculator_calls.py reads the tool pilot's household records and, for every distinct calculate_household call, compares the two copies' readings (worker_request, framed as the pool frames it) and their results on one shared engine, compares the result with the one the run recorded (counting recorded timeouts and lost workers apart), and reads the arguments again as the JSON object an MCP client sends. With --mcp it also sends each call through the package's MCP server. Any difference between the copies exits 1. It appends one line per call, so a rerun resumes. The development households are not public, so tests/ test_calculator_recorded_calls.py runs the real replay only when POLICYBENCH_RECORDED_RUNS and POLICYBENCH_RECORDED_BOARD name the folders; its other six tests check the script on records written in the test, with a fake engine: the counts, the resume, the gate, and the exit code. Co-Authored-By: Claude Fable 5.2 --- scripts/replay_calculator_calls.py | 322 ++++++++++++++++++++++++ tests/test_calculator_recorded_calls.py | 247 ++++++++++++++++++ 2 files changed, 569 insertions(+) create mode 100644 scripts/replay_calculator_calls.py create mode 100644 tests/test_calculator_recorded_calls.py diff --git a/scripts/replay_calculator_calls.py b/scripts/replay_calculator_calls.py new file mode 100644 index 00000000..9c76d183 --- /dev/null +++ b/scripts/replay_calculator_calls.py @@ -0,0 +1,322 @@ +"""Replay recorded calculate_household calls through the harness's calculator +and the package's, and check that they answer alike. + + python scripts/replay_calculator_calls.py --runs DIR --board DIR --out DIR + [--glob '*/*/mctest/households/*.json'] [--limit N] [--mcp] + +``--runs`` holds the tool pilot's run folders; each household record under it +(``--glob``) keeps every call a model made: its arguments as written and the +result it was given. ``--board`` is the household set those runs used, whose +engine must be the installed one. For each distinct call (an arm's features +and the arguments' text) the script: + +1. reads it with the harness's validator and the package's + (``worker_request``, framed with the features as the pool frames it), and + compares the two readings; +2. runs an accepted request on one shared engine through the harness's + ``execute_request`` and the package's, and compares the two results; +3. compares the package's result with the result the run recorded. A recorded + timeout, a call past the per-turn limit or a lost worker is infrastructure + and is counted apart; +4. reads the arguments again as the JSON object an MCP client sends, and + compares that reading with the first (``--mcp`` also sends every such call + through the package's MCP server over stdio and compares the answer's + text). + +Steps 1, 2 and 4 are the gate: any difference exits 1. Step 3 is reported per +run folder, because the records come from several commits of the harness. + +The development households are not public, so neither the records nor this +script's per-call output belong in the repository: ``--out`` gets +``progress.jsonl`` (one line per distinct call, appended as it finishes, so a +rerun resumes) and ``summary.json`` (counts only). +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import sys +import time +from collections import Counter +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT), str(ROOT / "scripts")] + +import tool_pilot_argon as pilot # noqa: E402 + +from policybench_calculator import core # noqa: E402 +from policybench_calculator.mcp_client import as_object # noqa: E402 + +DEFAULT_GLOB = "*/*/mctest/households/*.json" +# Results a run recorded for a call the engine never answered. +INFRASTRUCTURE_ERRORS = ("timeout", "not_run", pilot.POOL_UNAVAILABLE) + + +def call_key(features: frozenset, arguments) -> str: + text = json.dumps([sorted(features), arguments], sort_keys=True, default=str) + return hashlib.sha256(text.encode()).hexdigest() + + +def is_infrastructure(result) -> bool: + if not isinstance(result, dict): + return True + if result.get("error") in INFRASTRUCTURE_ERRORS: + return True + return result.get("error") == "engine" and str( + result.get("message", "") + ).startswith("tool worker failed") + + +def recorded_calls(runs: Path, pattern: str = DEFAULT_GLOB) -> dict[str, dict]: + """Every distinct calculator call under a runs folder: its features and + arguments, the distinct results recorded for it, and where it was made.""" + calls: dict[str, dict] = {} + for path in sorted(runs.glob(pattern)): + record = json.loads(path.read_text()) + features = pilot.arm_features(record.get("arm")) + if features is None: + continue + kept = record.get("tool_features") + if kept is not None and sorted(features) != kept: + raise SystemExit(f"{path}: arm {record['arm']} ran with features {kept}") + folder = str(path.parent.parent.relative_to(runs)) + for turn in record.get("turns", []): + for call in turn.get("calls", []): + if call.get("name") != pilot.TOOL_NAME: + continue + key = call_key(features, call.get("arguments")) + entry = calls.setdefault( + key, + { + "features": features, + "arguments": call.get("arguments"), + "results": [], + "folders": Counter(), + }, + ) + entry["folders"][folder] += 1 + text = json.dumps(call.get("result")) + if text not in entry["results"]: + entry["results"].append(text) + return calls + + +def _framed(module, features: frozenset, arguments): + """The message a pool sends its worker (ToolPool.call).""" + return module.tool_call_frame(features, arguments) if features else arguments + + +def replay_one(system, registries: dict, entry: dict, simulation_cls=None) -> dict: + """One distinct call through both copies; see the module docstring.""" + features, arguments = entry["features"], entry["arguments"] + started = time.perf_counter() + answers, readings, accepted = {}, {}, {} + for module in (pilot, core): + request, error = module.worker_request( + _framed(module, features, arguments), registries[module] + ) + readings[module] = json.dumps([request, error]) + accepted[module] = request is not None + answers[module] = json.dumps( + module.execute_request(system, registries[module], request, simulation_cls) + if request is not None + else error + ) + line = { + "accepted": accepted[core], + "same_reading": readings[pilot] == readings[core], + "same_result": answers[pilot] == answers[core], + } + recorded = entry["results"] + answered = [text for text in recorded if not is_infrastructure(json.loads(text))] + if answers[core] in recorded: + line["recorded"] = "match" + elif not answered: + line["recorded"] = "infrastructure" + else: + line["recorded"] = "differs" + sent = as_object(arguments) + line["sendable"] = sent is not None + if sent is not None and not isinstance(arguments, dict): + request, error = core.worker_request( + _framed(core, features, sent), registries[core] + ) + line["same_as_object"] = json.dumps([request, error]) == readings[core] + line["answer"] = answers[core] + line["seconds"] = round(time.perf_counter() - started, 3) + return line + + +def summarize(calls: dict[str, dict], lines: dict[str, dict]) -> dict: + """Counts only: by run folder (each recorded call) and overall (each + distinct call).""" + folders: dict[str, Counter] = {} + for key, entry in calls.items(): + line = lines.get(key) + for folder, count in entry["folders"].items(): + tally = folders.setdefault(folder, Counter()) + tally["calls"] += count + if line is None: + tally["not_replayed"] += count + continue + tally["accepted" if line["accepted"] else "refused"] += count + tally[f"recorded_{line['recorded']}"] += count + tally["reading_differs"] += count * (not line["same_reading"]) + tally["result_differs"] += count * (not line["same_result"]) + done = [lines[key] for key in calls if key in lines] + overall = Counter( + distinct_calls=len(calls), + replayed=len(done), + recorded_calls=sum(sum(e["folders"].values()) for e in calls.values()), + ) + for line in done: + overall["accepted" if line["accepted"] else "refused"] += 1 + overall[f"recorded_{line['recorded']}"] += 1 + overall["reading_differs"] += not line["same_reading"] + overall["result_differs"] += not line["same_result"] + overall["sendable"] += line["sendable"] + overall["object_reading_differs"] += line.get("same_as_object") is False + overall["mcp_checked"] += "same_over_mcp" in line + overall["mcp_differs"] += line.get("same_over_mcp") is False + return { + "overall": dict(overall), + "folders": {name: dict(tally) for name, tally in sorted(folders.items())}, + } + + +def gate_failures(summary: dict) -> int: + overall = summary["overall"] + return sum( + overall.get(name, 0) + for name in ( + "reading_differs", + "result_differs", + "object_reading_differs", + "mcp_differs", + ) + ) + (overall["distinct_calls"] - overall["replayed"]) + + +def replay( + runs: Path, + board: Path, + out: Path, + pattern: str = DEFAULT_GLOB, + limit: int | None = None, + over_mcp: bool = False, + log=print, + engine_for_tests: tuple | None = None, +) -> dict: + """Replay every distinct call (see the module docstring); returns the + summary it writes. ``engine_for_tests`` is (system, registries, + simulation class) in place of the board's installed engine.""" + if engine_for_tests is None: + pilot._require_engine(board) + engine = pilot.board_engine(board) + pilot.set_stated_engine(engine) + core.set_stated_engine(engine) + calls = recorded_calls(runs, pattern) + out.mkdir(parents=True, exist_ok=True) + progress = out / "progress.jsonl" + lines: dict[str, dict] = {} + if progress.exists(): + for text in progress.read_text().splitlines(): + line = json.loads(text) + lines[line["key"]] = line + todo = [key for key in calls if key not in lines][:limit] + log(f"{len(calls)} distinct calls, {len(lines)} done before, {len(todo)} to replay") + if todo: + if engine_for_tests is not None: + system, registries, simulation_cls = engine_for_tests + else: + simulation_cls = None + system = pilot.build_tool_system(reform=True, snapshot=board) + registries = { + pilot: pilot.build_registry(system), + core: core.build_registry(system), + } + if {n: vars(v) for n, v in registries[pilot].items()} != { + n: vars(v) for n, v in registries[core].items() + }: + raise SystemExit("the two copies build different registries") + sessions: dict[frozenset, object] = {} + try: + with progress.open("a") as handle: + for index, key in enumerate(todo, start=1): + entry = calls[key] + line = { + "key": key, + **replay_one(system, registries, entry, simulation_cls), + } + if over_mcp and line["sendable"]: + line["same_over_mcp"] = ( + _over_mcp(sessions, board, entry) == line["answer"] + ) + lines[key] = line + handle.write(json.dumps(line) + "\n") + handle.flush() + if index % 100 == 0 or index == len(todo): + log(f"{index}/{len(todo)} replayed") + finally: + for session in sessions.values(): + session.close() + summary = { + "runs": str(runs), + "glob": pattern, + "board": str(board), + "engine": f"policyengine-us {engine}", + "harness_sha256": pilot._sha256(Path(pilot.__file__)), + "core_sha256": pilot._sha256(Path(core.__file__)), + **summarize(calls, lines), + } + summary["gate_failures"] = gate_failures(summary) + (out / "summary.json").write_text(json.dumps(summary, indent=2) + "\n") + return summary + + +def _over_mcp(sessions: dict, board: Path, entry: dict) -> str: + """The text the package's MCP server answers the call with: one server per + feature set, launched over stdio on the same board.""" + from mcp import StdioServerParameters + + from policybench_calculator.mcp_client import McpToolCall + + features = entry["features"] + if features not in sessions: + arm = "pe:" + "+".join(sorted(features)) if features else "pe" + sessions[features] = McpToolCall( + StdioServerParameters( + command=sys.executable, + args=[ + "-m", + "policybench_calculator.mcp_server", + *("--arm", arm, "--board", str(board), "--workers", "1"), + ], + cwd=str(ROOT), + env=dict(os.environ), + ) + ) + return json.dumps(sessions[features](entry["arguments"])[0]) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--runs", type=Path, required=True) + parser.add_argument("--board", type=Path, required=True) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--glob", default=DEFAULT_GLOB) + parser.add_argument("--limit", type=int) + parser.add_argument("--mcp", action="store_true") + args = parser.parse_args(argv) + summary = replay(args.runs, args.board, args.out, args.glob, args.limit, args.mcp) + print(json.dumps(summary["overall"], indent=2)) + print(f"gate failures: {summary['gate_failures']}") + return 1 if summary["gate_failures"] else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_calculator_recorded_calls.py b/tests/test_calculator_recorded_calls.py new file mode 100644 index 00000000..b545b136 --- /dev/null +++ b/tests/test_calculator_recorded_calls.py @@ -0,0 +1,247 @@ +"""Replay recorded calls through the harness's calculator and the package's. + +``scripts/replay_calculator_calls.py`` reads the tool pilot's household +records and checks that both copies read and answer every recorded call +alike. The development households are not public, so their records are not in +the repository: the last test here reads them from folders named by +``POLICYBENCH_RECORDED_RUNS`` and ``POLICYBENCH_RECORDED_BOARD`` and skips +without them. The tests before it check the script itself on records written +here, with a fake engine. +""" + +from __future__ import annotations + +import json +import os +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT), str(ROOT / "scripts"), str(ROOT / "tests")] + +import replay_calculator_calls as replay # noqa: E402 +import tool_pilot_argon as pilot # noqa: E402 + +from policybench_calculator import core # noqa: E402 + +VARIABLES = { + "age": ("person", "int", "age", "year"), + "employment_income": ("person", "float", "employment income", "year"), + "snap": ("spm_unit", "float", "SNAP", "month", None, True), + "state_code": ("household", "Enum", "state", "year", ("CA", "LA")), +} +REGISTRIES = { + module: {name: module.VariableInfo(*fields) for name, fields in VARIABLES.items()} + for module in (pilot, core) +} +SITUATION = { + "people": {"head": {"age": 40, "employment_income": 30000}}, + "households": {"home": {"members": ["head"], "state_code": "CA"}}, +} +ACCEPTED = json.dumps({"situation": SITUATION, "variables": ["snap"]}) +REFUSED = json.dumps({"situation": SITUATION, "variables": ["telepathy"]}) +WRITTEN = json.dumps( + {"situation": {"people": {"head": {"Age": 40}}}, "variables": ["age"]} +) + + +class FakeSimulation: + def __init__(self, tax_benefit_system, situation): + self.populations = { + "person": SimpleNamespace(ids=list(situation["people"])), + "spm_unit": SimpleNamespace(ids=["spm"]), + } + + def calculate(self, name, period): + return [1234.567] if name == "snap" else [40.0] + + +def _answer(arm: str, arguments) -> dict: + features = pilot.arm_features(arm) + message = pilot.tool_call_frame(features, arguments) if features else arguments + request, error = pilot.worker_request(message, REGISTRIES[pilot]) + if request is None: + return error + return pilot.execute_request(None, REGISTRIES[pilot], request, FakeSimulation) + + +def _record(folder: Path, name: str, arm: str, calls: list[tuple]) -> None: + features = pilot.arm_features(arm) + record = { + "scenario_id": name, + "arm": arm, + "turns": [ + { + "calls": [ + {"name": pilot.TOOL_NAME, "arguments": arguments, "result": result} + for arguments, result in calls + ] + + [{"name": "submit_outputs", "arguments": "{}", "result": None}] + } + ], + } + if arm != "pe": + # A version 1 record written before records kept their features has + # none; an arm without the calculator records None. + record["tool_features"] = None if features is None else sorted(features) + (folder / "households").mkdir(parents=True, exist_ok=True) + (folder / "households" / f"{name}.json").write_text(json.dumps(record)) + + +@pytest.fixture +def runs(tmp_path): + """Two run folders: version 1 calls, one of them recorded as a timeout and + one with a result no engine here gives; and names-feature calls.""" + timeout = {"error": "timeout", "message": "the calculation exceeded 60 seconds"} + stale = {"results": {"snap": {"values": {"spm": 1.0}}}} + _record( + tmp_path / "runs/model-a/pe/mctest", + "mt_000", + "pe", + [ + (ACCEPTED, _answer("pe", ACCEPTED)), + (ACCEPTED, _answer("pe", ACCEPTED)), + (REFUSED, _answer("pe", REFUSED)), + (WRITTEN, timeout), + ], + ) + _record( + tmp_path / "runs/model-a/pe/mctest", + "mt_001", + "pe", + [(ACCEPTED, timeout), ("{not json", _answer("pe", "{not json"))], + ) + _record( + tmp_path / "runs/model-b/abl-add-names/mctest", + "mt_000", + "pe:names", + [(WRITTEN, _answer("pe:names", WRITTEN)), (ACCEPTED, stale)], + ) + _record(tmp_path / "runs/model-b/none/mctest", "mt_000", "none", []) + return tmp_path / "runs" + + +def _replay(runs, out, **options): + return replay.replay( + runs, + pilot.SNAPSHOT, + out, + log=lambda text: None, + engine_for_tests=(None, REGISTRIES, FakeSimulation), + **options, + ) + + +def test_the_replay_counts_each_call_and_passes_the_gate(runs, tmp_path): + summary = _replay(runs, tmp_path / "out") + assert summary["gate_failures"] == 0 + overall = summary["overall"] + # Six distinct calls: four under version 1 (the accepted one, made three + # times, counts once) and two under the names feature. + assert overall["distinct_calls"] == overall["replayed"] == 6 + assert overall["recorded_calls"] == 8 + assert overall["accepted"] == 3 and overall["refused"] == 3 + assert overall["recorded_match"] == 4 + assert overall["recorded_infrastructure"] == 1 + assert overall["recorded_differs"] == 1 + assert overall["sendable"] == 5 and overall["object_reading_differs"] == 0 + assert summary["folders"] == { + "model-a/pe/mctest": { + "calls": 6, + "accepted": 3, + "refused": 3, + "recorded_match": 5, + "recorded_infrastructure": 1, + "reading_differs": 0, + "result_differs": 0, + }, + "model-b/abl-add-names/mctest": { + "calls": 2, + "accepted": 2, + "recorded_match": 1, + "recorded_differs": 1, + "reading_differs": 0, + "result_differs": 0, + }, + } + assert json.loads((tmp_path / "out/summary.json").read_text()) == summary + + +def test_a_rerun_resumes_from_its_progress_file(runs, tmp_path): + first = _replay(runs, tmp_path / "out", limit=2) + assert first["overall"]["replayed"] == 2 + assert first["gate_failures"] == 4, "calls not yet replayed fail the gate" + lines = (tmp_path / "out/progress.jsonl").read_text().splitlines() + assert len(lines) == 2 + second = _replay(runs, tmp_path / "out") + assert second["overall"]["replayed"] == 6 and second["gate_failures"] == 0 + resumed = (tmp_path / "out/progress.jsonl").read_text().splitlines() + assert resumed[:2] == lines and len(resumed) == 6 + + +def test_a_copy_that_answers_differently_fails_the_gate(runs, tmp_path, monkeypatch): + def rounds_differently(system, registry, request, simulation_cls=None): + result = pilot.execute_request(system, registry, request, simulation_cls) + for entry in result["results"].values(): + entry["values"] = {k: round(v) for k, v in entry["values"].items()} + return result + + monkeypatch.setattr(core, "execute_request", rounds_differently) + summary = _replay(runs, tmp_path / "out") + assert summary["overall"]["result_differs"] == 3 + assert summary["gate_failures"] == 3 + + +def test_the_command_exits_1_when_the_gate_fails(monkeypatch, capsys): + arguments = ["--runs", "runs", "--board", "board", "--out", "out"] + for failures in (0, 2): + monkeypatch.setattr( + replay, + "replay", + lambda *args, failures=failures: { + "overall": {"distinct_calls": 5}, + "gate_failures": failures, + }, + ) + assert replay.main(arguments) == (1 if failures else 0) + assert "gate failures: 2" in capsys.readouterr().out + + +def test_a_record_whose_features_are_not_its_arms_is_refused(runs): + path = runs / "model-b/abl-add-names/mctest/households/mt_000.json" + record = json.loads(path.read_text()) + record["tool_features"] = ["flat"] + path.write_text(json.dumps(record)) + with pytest.raises(SystemExit, match="ran with features"): + replay.recorded_calls(runs) + + +def test_recorded_infrastructure_results_are_told_apart(): + assert replay.is_infrastructure({"error": "timeout", "message": "..."}) + assert replay.is_infrastructure({"error": "not_run", "message": "..."}) + assert replay.is_infrastructure({"error": pilot.POOL_UNAVAILABLE}) + assert replay.is_infrastructure( + {"error": "engine", "message": "tool worker failed: "} + ) + assert replay.is_infrastructure(None) + assert not replay.is_infrastructure({"error": "engine", "message": "ValueError: x"}) + assert not replay.is_infrastructure({"error": "validation", "problems": []}) + assert not replay.is_infrastructure({"results": {}}) + + +@pytest.mark.slow +def test_the_recorded_development_calls_replay_alike(tmp_path): + """Every call the development runs recorded, on the board's engine.""" + runs = os.environ.get("POLICYBENCH_RECORDED_RUNS") + board = os.environ.get("POLICYBENCH_RECORDED_BOARD") + if not (runs and board): + pytest.skip("set POLICYBENCH_RECORDED_RUNS and POLICYBENCH_RECORDED_BOARD") + if pilot._versions()["policyengine-us"] != pilot.board_engine(Path(board)): + pytest.skip("the installed policyengine-us is not the board's") + out = Path(os.environ.get("POLICYBENCH_REPLAY_OUT") or tmp_path / "replay") + summary = replay.replay(Path(runs), Path(board), out) + assert summary["overall"]["distinct_calls"] > 0 + assert summary["gate_failures"] == 0, summary["overall"] From 841f29d3f060a688cc717b02a85fcfcc40dd1597 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 18 Nov 2026 08:27:31 -0500 Subject: [PATCH 4/9] Design the MCP arm: provider connectors, reachability, records and cost docs/calculator_mcp/design.md separates two arms the word could mean. With the harness as the MCP client the model sees the same prompt and tool, so a paid run measures only what the free replay already does. With a provider's connector as the client the provider shows the tool and runs the loop; that is the arm designed here: what OpenAI, Anthropic and Google document (read 2026-11-18, each claim checked by a second reader), how a provider could reach a local engine and what each route exposes, where the treatment can stay the pilot's and where it cannot (the 8-turn and 4-call limits), how the runner writes records that score and diagnose accept, and a cost estimate from the development runs' own records ($1.58 at list for four models; a $10 cap asked). Design only: no model call, nothing hosted. Also: the server answers an unexpected failure in its own words, since on a handshake-era connection the SDK sends a client the exception's text. Co-Authored-By: Claude Fable 5.2 --- docs/calculator_mcp/design.md | 219 +++++++++++++++++++++++++++ policybench_calculator/mcp_server.py | 10 +- 2 files changed, 228 insertions(+), 1 deletion(-) create mode 100644 docs/calculator_mcp/design.md diff --git a/docs/calculator_mcp/design.md b/docs/calculator_mcp/design.md new file mode 100644 index 00000000..cc27d633 --- /dev/null +++ b/docs/calculator_mcp/design.md @@ -0,0 +1,219 @@ +# The calculator over MCP: what exists, and the design of an MCP arm + +Status, 2026-11-18: this pull request adds the package, the server and the +checks below. The arm exists only as this design. Nobody has called a model +for it and no server faces the internet; both wait for a decision. + +## What exists + +- `policybench_calculator.core`: the calculator the tool pilot gives a model, + as a package. It is a verbatim copy of the one in + `scripts/tool_pilot_argon.py`, because the v2 confirmatory runner pins that + script to its treatment commit; `scripts/sync_calculator_core.py` writes the + copy and `tests/test_calculator_core.py` fails when the two differ. +- `policybench_calculator.mcp_server`: an MCP server with one tool, + `calculate_household`. It lists the name, description and input schema that + `calculate_tool_schema` builds for an arm, runs each call in the pilot's + worker pool on the board's pinned engine and reform, and answers with + `json.dumps` of the result, the text the pilot's `add_tool_result` sends a + model. It serves stdio, or Streamable HTTP on 127.0.0.1, and offers its + engine, board, features and schema hash as the resource + `policybench://calculator/provenance`. +- `policybench_calculator.mcp_client.McpToolCall`: a `tool_call` for + `run_household` (arguments in, result and seconds out) over an MCP session. +- `scripts/replay_calculator_calls.py`: replays recorded calls through the + harness's calculator and the package's, and with `--mcp` through the server. + +## Two arms that the word "MCP" could mean + +**A. The harness is the MCP client.** The harness lists the tool from the +server, offers it to the model as the same function tool as today, and sends +each call to the server through `McpToolCall`. The model receives the same +prompt and the same tool definition as in the function-tool arm, so the two +arms differ only by sampling noise. A paid run of this arm would measure +nothing that the replay does not already measure for free: the replay sends +the calls models really made through the server and compares every answer +with the function tool's. + +**B. The provider's connector is the MCP client.** The request names the +server; the provider's own servers list its tools, show them to the model, run +the model's calls and return a finished response. This is the arm the October +plan named ("an MCP arm through the providers' MCP connectors"), and the only +one that can show a difference: the provider decides how the tool looks to the +model and when the loop ends. + +The rest of this note designs arm B. Arm A needs no further work beyond a run +command, and the note recommends against paying for it. + +## What the providers document + +Read on 2026-11-18 from each provider's own documentation and, for litellm, +from the installed 1.88.1 source; a second reader then checked each claim +against the same sources. "Not found" means the pages do not say. Nothing in +this table comes from a call to a model. + +| | OpenAI | Anthropic | Google | +|---|---|---|---| +| Where | Responses API only | Messages API, beta header `mcp-client-2025-11-20` | Interactions API (preview), not `generateContent` | +| Request | `tools: [{"type": "mcp", "server_label", "server_url", "allowed_tools", "require_approval": "never", "headers"}]` | `mcp_servers: [{"type": "url", "url", "name", "authorization_token"}]` plus `tools: [{"type": "mcp_toolset", "mcp_server_name"}]` | `tools: [{"type": "mcp_server", "name", "url", "headers", "allowed_tools"}]` | +| Who calls the server | OpenAI's servers; "any server on the public Internet" | Anthropic's servers, over https only | Google's servers | +| Transports | Streamable HTTP or HTTP/SSE | Streamable HTTP or SSE | Streamable HTTP only | +| What the response shows | `mcp_list_tools`, then one `mcp_call` per call with `arguments`, `output` and `error` | `mcp_tool_use` (input) and `mcp_tool_result` (content, `is_error`) blocks | `mcp_server_tool_call` and `mcp_server_tool_result` steps | +| Fee beyond tokens | None ("No additional fees apply per tool call") | None on the pricing page | None on the pricing page | +| Limit on calls | `max_tool_calls` exists; whether it counts MCP calls is not found | Not found; server tools pause a turn after 10 iterations (`pause_turn`), and whether MCP calls count toward that is not found | Not found | +| Models | "most recent models"; examples use GPT-6.2 Astra | The page lists Opus 5.5, Sonnet 5.5 and Haiku 5.5 | Unresolved: one page says Gemini 3 lacks remote MCP, another's example uses Gemini 3.8 Flash | +| Private route | Secure MCP Tunnel (`tunnel_id`); eligibility outside enterprise is not stated | MCP tunnels, a research preview with access by request | Not found | +| Through litellm 1.88.1 | `litellm.responses()` passes the tool and returns the items unchanged | `litellm.completion()` sends the deprecated 2025-04-04 header and leaves `mcp_tool_use` blocks out of the message it returns; call the `anthropic` SDK directly | Not on the harness's path | + +Two details matter for the build. OpenAI's default for `require_approval` is +"always", so the request must set "never" or every call returns as an approval +request. And litellm 1.88.1 takes over any `server_url` of the form +`.../mcp/` for its own gateway, so the server's URL must end in `/mcp`. + +## How a provider would reach the server + +The server runs the engine in local worker processes. A provider's connector +needs a URL its servers can reach, so something must face the internet for as +long as a run lasts. The household set is not public, and the calls carry the +facts a model wrote from it; the model's provider already receives those facts +in the prompt, and any host or tunnel between the provider and the server +would receive them too. + +| Option | Set-up | Cost for about 3 hours | Who else sees the calls | Notes | +|---|---|---|---|---| +| Cloudflare tunnel from the run machine to the local server | Low | $0 | Cloudflare (it ends the TLS connection) | The engine and reform are the function arm's own install. The quick tunnel has no SSE (so the server must answer in plain JSON) and no uptime promise; a named tunnel needs a domain on Cloudflare. | +| Modal, an ASGI app with 2 to 4 warm workers | Medium | About $0.35 to $1.00 | Modal | PolicyEngine's usual host. Needs an image with the pinned engine and the reform; a request may run 150 seconds at most. | +| Cloud Run with minimum instances | Medium to high | About $0.35 to $1.40 | Google | Same image work as Modal. | +| The providers' own tunnels | Unknown | Not stated | The provider only | OpenAI's may need an enterprise organisation; Anthropic's needs an access request. Neither helps the other provider. | + +Recommended for a development run: the Cloudflare tunnel, up only while the +run lasts, because it serves the very install the function arm used and needs +no image. Modal is the better choice if the arm ever runs at confirmatory +scale or from a machine that sleeps. + +Whichever route a decision picks, the server needs four things it does not +have today. This pull request adds none of them, since no server may face the +internet yet: + +1. A bearer token it checks on every request (OpenAI sends `headers` or + `authorization`; Anthropic sends `authorization_token`; Google sends + `headers`), and the SDK's host check opened to the tunnel's name only. +2. A token per household in the URL path or a header, so the server can tell + one household's calls from another's. +3. Its own call log, one line per call: the household's token, the arguments + as received, the result text, the seconds, and the protocol version the + connector negotiated. +4. A limit on calls per household (see the next section). + +## Keeping the treatment the same, and where it cannot be + +- **The tool.** The server builds its listing from the same code as the + function tool, and the tests check that every field matches. On a + 2025-era MCP connection the SDK's schema model puts the input schema's + top-level keys in another order (`properties`, `required`, `type`; read + from the SDK's source, not yet observed on the wire); the content is equal. + How a provider then shows the tool to the model is not documented: OpenAI + carries a `server_label` beside the name and has no `strict` setting for + an MCP tool; Anthropic offers no strict setting on `mcp_toolset` either. + The request must leave OpenAI's optional `server_description` unset, since + the function arm has no such text. +- **The notice.** The arm sends the pe3 notice unchanged, including "You may + call it in up to 8 turns". +- **The answer.** A tool-contract model (GPT-6) still answers through + `submit_outputs`, an ordinary function the harness handles; a JSON-contract + model (Claude Opus 5.5) still answers in its JSON reply. +- **Results and errors.** The server returns every result, a validation or + engine error included, as ordinary text with `isError` unset, so the model + reads the same text as in the function arm. (OpenAI's call item has an + `error` field apart from `output` for failed calls; the pages do not say + what the model sees for a result the server marks as an error, so the + server marks none.) +- **The limits. This is the real difference.** The harness allows 8 tool + turns and 4 calculations in a turn, answers a fifth with `not_run`, and + then forces the answer. A connector runs the model's calls inside one + response, so the harness cannot count turns or refuse a call. The server + would enforce the largest number of calls the function arm permits a + household, 32, and answer any further call with the harness's own `not_run` + text. Turns have no equivalent. The development runs give the scale: pe3 + households made 1.5 to 4.8 calls on average by model, never more than 2 in + a turn, and only Claude Haiku 5.5 reached the 8-turn limit (5 of 20 + households). The write-up must report calls per household for both arms. +- **Arguments.** A connector sends arguments as a JSON object, so the + function arm's "arguments are not valid JSON" refusals cannot occur. + +## Recording a household so that score and diagnose still work + +`score` and `diagnose` read a household record's `turns[].calls[]` entries +(`name`, `arguments`, `result`, `tool_latency_seconds`), its predictions and +its treatment fields (`arm`, `tool_features`, `tool_notice_sha256`, +`calculate_tool_sha256`). The arm's runner writes the same record: + +- one call entry per connector call item, with `arguments` as the provider + reports them and `result` parsed from the output text; +- `tool_latency_seconds`, and a check of every argument and result, from the + server's own log for that household's token, which is the authority when + the two disagree; +- `arm: "pe3"` and the pe3 hashes, since the notice and the schema are pe3's, + with a new field naming the transport, in an output folder of its own + (`runs//mcp-pe3/`). The pinned script should then score and diagnose + the folder as it stands, with no change to `scripts/tool_pilot_argon.py`; + the build confirms that on fake connector responses before any paid call. + +The runner is a new script beside the harness. It reuses the harness's prompt, +request settings, answer parsing and cost code by import, and replaces only +the conversation loop: for OpenAI one `responses` request per household, plus +repairs; for Anthropic the `anthropic` SDK's `beta.messages.create`, continued +after each `pause_turn`. A server that stops answering must end the household +with a rerunnable status, never a scored one. + +## The run + +- **Households and pairing.** The 20 development households (`mt_000` to + `mt_019`; 10 for the frontier models, as before), with the v2-pilot prompt + on policyengine-us 2.60.4, paired with the pe3 records already on disk. + These are development data: the run is exploratory and stays out of the + confirmatory study. +- **Models.** GPT-6 Luna and GPT-6 Sol through OpenAI's connector; Claude + Haiku 5.5 and Claude Opus 5.5 through Anthropic's. Gemini waits: its + connector lives in another API than the function arm uses, and the pages + disagree on which models support it. +- **Measures.** Exact-match by output, paired by household, MCP against + function, with the bootstrap the pilot's `score` already runs; calls per + household; and a mechanical check that sends every call the arm recorded + through the function tool and expects the same text. +- **First, a probe.** One household on GPT-6 Luna and one on Claude Haiku 5.5 + (under one cent at the measured means) settles what the pages leave open: + whether + `max_tool_calls` counts MCP calls, whether `tool_choice: "required"` accepts + an MCP call, which protocol version each connector speaks, and how each + shows the tool's name. + +## Cost + +Model spend, from the development runs' own records (list prices rebuilt from +token counts; mean per household in the pe3 arm): + +| Model | Per household | Households | Estimate | +|---|---:|---:|---:| +| GPT-6 Luna | $0.0024 | 20 | $0.05 | +| GPT-6 Sol | $0.0544 | 10 | $0.54 | +| Claude Haiku 5.5 | $0.0041 | 20 | $0.08 | +| Claude Opus 5.5 | $0.0905 | 10 | $0.91 | +| **Four models** | | | **$1.58** | +| Gemini 3.5 Flash-Lite, if added | $0.0144 | 20 | $0.29 | +| Gemini 4 Argon, if added | $0.0554 | 10 | $0.55 ($1.11 from 1 December, when its price doubles) | + +Neither OpenAI nor Anthropic documents a fee for an MCP call; tool listings +and results bill as input tokens, as a function tool's do. A connector may +loop differently from the harness, and a first run needs reruns, so the +request is a cap of **$10 at list prices** for the four models, probe included. +Hosting adds nothing for a tunnel and about a dollar on Modal. + +## What a go would start + +1. The server additions above (token, per-household path, call log, call + limit), with tests, and the tunnel or Modal app. +2. The runner script and its record adapter, tested against recorded + connector responses before any paid call. +3. The two-household probe, then the run, then `score` and `diagnose` on the + new folder beside the pe3 one. diff --git a/policybench_calculator/mcp_server.py b/policybench_calculator/mcp_server.py index 4834f2fe..1035b7f9 100644 --- a/policybench_calculator/mcp_server.py +++ b/policybench_calculator/mcp_server.py @@ -221,7 +221,15 @@ async def call_tool(ctx, params) -> types.CallToolResult: code=types.INVALID_PARAMS, message=f"Unknown tool: {params.name}" ) arguments = {} if params.arguments is None else params.arguments - result, _ = await anyio.to_thread.run_sync(calculator.call, arguments) + try: + result, _ = await anyio.to_thread.run_sync(calculator.call, arguments) + except Exception as error: + # Said here, in the server's own words: on a handshake-era + # connection the SDK would otherwise send a client the + # exception's text. + raise MCPError( + code=types.INTERNAL_ERROR, message="the calculator is unavailable" + ) from error if result.get("error") == core.POOL_UNAVAILABLE: # Infrastructure, not an answer: the pilot stops the household # rather than show a model this result, so it is a protocol error. From 12df1d2cb71c59fb5a90ee12199b74ff5ee74c56 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 18 Nov 2026 08:59:07 -0500 Subject: [PATCH 5/9] Add the mcp extra and lock it; the server's tests now need the SDK pyproject.toml gains an optional `mcp` extra (mcp==2.3.0, the latest release on PyPI, uploaded 2026-10-02), puts the same pin in the dev extra so the server's tests run wherever the suite does, and adds the command policybench-calculator-mcp. uv.lock adds the 13 packages that pin brings and changes no other (uv 0.13.9, resolved on a GitHub runner): mcp and mcp-types 2.3.0, httpx2 and httpcore2 2.16.2, httpx2-jsfetch 1.0, opentelemetry-api 1.45.2, pyjwt 2.15.1, python-multipart 0.0.34, pywin32 312 (Windows only), sse-starlette 3.7.0, starlette 1.10.0, truststore 0.10.5 and uvicorn 0.54.0. Three of them (httpx2, httpcore2, python-multipart) were released on 2026-11-16. With the SDK installed, all seven session tests passed on their first run (GitHub run 44315093560): the in-process client, stdio with a handshake-era session, Streamable HTTP in both protocol eras, and McpToolCall in both modes. They no longer skip when mcp is missing. Also fixes the written-call generator in tests/test_calculator_core.py, which raised when it drew "other shape" and then "people" for one call (the same run found it; the two copies were never at fault). Co-Authored-By: Claude Fable 5.2 --- pyproject.toml | 7 ++ tests/test_calculator_core.py | 10 +- tests/test_calculator_mcp.py | 9 -- uv.lock | 197 +++++++++++++++++++++++++++++++++- 4 files changed, 206 insertions(+), 17 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 48de20e3..736db6a0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,10 +24,16 @@ dependencies = [ [project.optional-dependencies] dev = [ "hypothesis>=6.100", + "mcp==2.3.0", # the calculator's MCP server tests open real sessions "pytest>=8.0", "pytest-cov>=5.0", "ruff>=0.4", ] +# The calculator's MCP server (policybench_calculator.mcp_server), written +# against this release's low-level Server. +mcp = [ + "mcp==2.3.0", +] docs = [ "ipykernel>=6.0", "jupyter-book>=2.0", @@ -37,6 +43,7 @@ docs = [ [project.scripts] policybench = "policybench.cli:main" +policybench-calculator-mcp = "policybench_calculator.mcp_server:main" [tool.setuptools.packages.find] include = ["policybench*"] diff --git a/tests/test_calculator_core.py b/tests/test_calculator_core.py index 2b34d71c..1a73de53 100644 --- a/tests/test_calculator_core.py +++ b/tests/test_calculator_core.py @@ -468,8 +468,8 @@ def a_fact(pool): facts = draw(st.sampled_from(holding)) return facts, draw(st.sampled_from(sorted(set(facts) - {"members"}))) - for slip in draw(st.sampled_from([[], [], [0], [0], [0, 1]])): - del slip + other_shape = False + for _ in draw(st.sampled_from([[], [], [0], [0], [0, 1]])): kind = draw(st.sampled_from(SLIPS)) facts, name = a_fact(containers + unit_containers) if kind in ("spaces", "capitals", "label", "unknown name") and facts: @@ -523,8 +523,10 @@ def a_fact(pool): st.sampled_from([[], ["ghost"], [names[0], names[0]], "head"]) ) elif kind == "other shape": - flat = not flat - arguments["household" if flat else "situation"] = ( + other_shape = not other_shape + # The payload keeps its shape; "other shape" only files it under the + # argument the arm does not take. + arguments["household" if flat != other_shape else "situation"] = ( json.dumps(payload) if draw(st.booleans()) else payload ) message = json.dumps(arguments) if draw(st.booleans()) else arguments diff --git a/tests/test_calculator_mcp.py b/tests/test_calculator_mcp.py index 8ccc8b83..0cbc13cc 100644 --- a/tests/test_calculator_mcp.py +++ b/tests/test_calculator_mcp.py @@ -11,7 +11,6 @@ from __future__ import annotations import hashlib -import importlib.util import json import os import socket @@ -31,9 +30,6 @@ from policybench_calculator import core, mcp_client, mcp_server # noqa: E402 FAKE_SERVER = ROOT / "tests/calculator_mcp_fake.py" -needs_mcp = pytest.mark.skipif( - importlib.util.find_spec("mcp") is None, reason="needs the mcp extra" -) FLAT_HOUSEHOLD = { "state": "CA", @@ -236,7 +232,6 @@ def _listed(tools) -> dict: } -@needs_mcp @pytest.mark.parametrize("arm", sorted(CALLS)) def test_the_server_lists_the_pilots_tool_and_gives_the_pilots_answers(arm): import anyio @@ -275,7 +270,6 @@ async def session(): assert calculator.engine in seen["server"].description -@needs_mcp def test_a_pool_with_no_worker_is_a_protocol_error_not_an_answer(monkeypatch): import anyio from mcp import Client, MCPError @@ -308,7 +302,6 @@ def _launch(arm: str): ) -@needs_mcp def test_over_stdio_the_handshake_era_reads_the_same_tool_and_answers(): """A 2025-era client (initialize, then tools/list and tools/call) over the stdio transport, with the server in its own process.""" @@ -365,7 +358,6 @@ def http_server(): process.kill() -@needs_mcp def test_over_http_both_protocol_eras_read_the_same_tool_and_answers(http_server): import anyio from mcp import Client, ClientSession @@ -404,7 +396,6 @@ async def handshake(): assert seen["modern answers"] == seen["handshake answers"] == answers -@needs_mcp @pytest.mark.parametrize("mode", ["auto", "legacy"]) def test_the_client_is_a_tool_call_for_the_pilots_loop(mode): """McpToolCall has ToolPool.call's shape, and gives its results: for diff --git a/uv.lock b/uv.lock index ee8f23b6..182c4a6b 100644 --- a/uv.lock +++ b/uv.lock @@ -1,12 +1,13 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.11" resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version < '3.14' and sys_platform == 'win32'", - "python_full_version < '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", + "python_full_version < '3.12' and sys_platform == 'emscripten'", "python_full_version < '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] @@ -1136,6 +1137,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, ] +[[package]] +name = "httpcore2" +version = "2.16.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "h11" }, + { name = "truststore" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/92/9d/df40b41f7db0370f82019820709244e7b660c52aa3da3c9e5c4e8141f6e6/httpcore2-2.16.2.tar.gz", hash = "sha256:6c519d0f7b44f7269fa9bbb4d2763db395a4a2370f046d8e8e0a4b38227815d2", size = 70064, upload-time = "2026-11-16T10:12:19.491Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/e8/009c347feac27f8960605aa98d55ed263b5870dd4fd80b82fd1d00d5716c/httpcore2-2.16.2-py3-none-any.whl", hash = "sha256:16051ae2a42f776007543f32de9349a317b23d2cbb4e1456b4bac0e88b87419a", size = 85551, upload-time = "2026-11-16T10:12:16.674Z" }, +] + [[package]] name = "httpx" version = "0.28.1" @@ -1151,6 +1165,32 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, ] +[[package]] +name = "httpx2" +version = "2.16.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio", marker = "sys_platform != 'emscripten'" }, + { name = "httpcore2", marker = "sys_platform != 'emscripten'" }, + { name = "httpx2-jsfetch", marker = "python_full_version >= '3.12' and sys_platform == 'emscripten'" }, + { name = "idna" }, + { name = "truststore", marker = "sys_platform != 'emscripten'" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/1c/77/6515121dc5ac3c743ad1bff5afe635bcd1a3f23cc40db3c5c89f7d02917d/httpx2-2.16.2.tar.gz", hash = "sha256:748b615678f07d8e3b183efe81ad13b655ca88bfc56ce4589219b2d442860574", size = 103370, upload-time = "2026-11-16T10:12:20.49Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/77/de/8c4306a3d6aa2495111986addf33a9e561eff4c47552e4c4b9251160d0ad/httpx2-2.16.2-py3-none-any.whl", hash = "sha256:f05c13aade4c45dbf1c9060647a1058f0acad62398fad96e741269edb33d46f5", size = 97893, upload-time = "2026-11-16T10:12:18.192Z" }, +] + +[[package]] +name = "httpx2-jsfetch" +version = "1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cd/c4/0e5636363151a2a1795e0a77617168b9ca438e1748ec05fc9b5687f93d64/httpx2_jsfetch-1.0.tar.gz", hash = "sha256:70a0e3eabfef7cce5ad9c629f7d01ca05e418f586646f4ddf14782e4c1454c60", size = 6872, upload-time = "2026-08-07T00:13:07.492Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9b/43/832f631d32e4f1211caa2ba368317739fe71f0b8530e4c9d15dc454bac2a/httpx2_jsfetch-1.0-py3-none-any.whl", hash = "sha256:cb916b707601e69a07721aabc8f3f6659be3a6893bc1ff5c6f9e02241df2da32", size = 6382, upload-time = "2026-08-07T00:13:06.567Z" }, +] + [[package]] name = "huggingface-hub" version = "1.4.1" @@ -1821,6 +1861,44 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/af/33/ee4519fa02ed11a94aef9559552f3b17bb863f2ecfe1a35dc7f548cde231/matplotlib_inline-0.2.1-py3-none-any.whl", hash = "sha256:d56ce5156ba6085e00a9d54fead6ed29a9c47e215cd1bba2e976ef39f5710a76", size = 9516, upload-time = "2025-10-23T09:00:20.675Z" }, ] +[[package]] +name = "mcp" +version = "2.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "httpx2" }, + { name = "jsonschema" }, + { name = "mcp-types" }, + { name = "opentelemetry-api" }, + { name = "pydantic" }, + { name = "pyjwt", extra = ["crypto"] }, + { name = "python-multipart" }, + { name = "pywin32", marker = "sys_platform == 'win32'" }, + { name = "sse-starlette" }, + { name = "starlette" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, + { name = "uvicorn", marker = "sys_platform != 'emscripten'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9d/8d/e0d339616f4810e9051d4aba6887afab289ab1f81875fe908b606cdfd0e3/mcp-2.3.0.tar.gz", hash = "sha256:8b147a50441cf059dc88c684e0aeed3687f0aa0f39c6cde7b90330effd2b34d8", size = 4171955, upload-time = "2026-10-02T22:06:56.091Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/20/d7/4a2878f128df729db3ca04e71bfce26405cc2e0c9ebe19c592feeb4c61b9/mcp-2.3.0-py3-none-any.whl", hash = "sha256:dd0c44c089d16453e8ae31a3877a0054d7a2314caaa81f5e0541b9b1734b2377", size = 368664, upload-time = "2026-10-02T22:06:52.119Z" }, +] + +[[package]] +name = "mcp-types" +version = "2.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pydantic" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9e/2d/7c251e34207f6c51000312fc8839111ac45cfe02023f90b44e7f1051dd8e/mcp_types-2.3.0.tar.gz", hash = "sha256:d1e46549edb35ee19a94940fcee6d1addd7e589ab7ea92dda83f5d84781fc362", size = 65898, upload-time = "2026-10-02T22:06:57.863Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ce/48/32583066b155bb5d4507e7887dc88ee23118cc4de8e2a12870c49719e2a8/mcp_types-2.3.0-py3-none-any.whl", hash = "sha256:968efdbdaedfab06adae40d378a34395f1090c5921d4be3c9cde283aaf76d91d", size = 69108, upload-time = "2026-10-02T22:06:54.099Z" }, +] + [[package]] name = "mdurl" version = "0.1.2" @@ -2329,6 +2407,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c0/da/977ded879c29cbd04de313843e76868e6e13408a94ed6b987245dc7c8506/openpyxl-3.1.5-py2.py3-none-any.whl", hash = "sha256:5282c12b107bffeef825f4617dc029afaf41d0ea60823bbb665ef3079dc79de2", size = 250910, upload-time = "2024-06-28T14:03:41.161Z" }, ] +[[package]] +name = "opentelemetry-api" +version = "1.45.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, +] + [[package]] name = "overrides" version = "7.7.0" @@ -2430,7 +2520,7 @@ name = "pexpect" version = "4.9.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "ptyprocess", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "ptyprocess" }, ] sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450, upload-time = "2023-11-25T09:07:26.339Z" } wheels = [ @@ -2486,6 +2576,7 @@ dependencies = [ [package.optional-dependencies] dev = [ { name = "hypothesis" }, + { name = "mcp" }, { name = "pytest" }, { name = "pytest-cov" }, { name = "ruff" }, @@ -2496,6 +2587,9 @@ docs = [ { name = "nbclient" }, { name = "nbformat" }, ] +mcp = [ + { name = "mcp" }, +] [package.metadata] requires-dist = [ @@ -2505,6 +2599,8 @@ requires-dist = [ { name = "ipykernel", marker = "extra == 'docs'", specifier = ">=6.0" }, { name = "jupyter-book", marker = "extra == 'docs'", specifier = ">=2.0" }, { name = "litellm", extras = ["caching"], specifier = ">=1.30" }, + { name = "mcp", marker = "extra == 'dev'", specifier = "==2.3.0" }, + { name = "mcp", marker = "extra == 'mcp'", specifier = "==2.3.0" }, { name = "nbclient", marker = "extra == 'docs'", specifier = ">=0.10" }, { name = "nbformat", marker = "extra == 'docs'", specifier = ">=5.0" }, { name = "numpy", specifier = ">=1.25" }, @@ -2516,7 +2612,7 @@ requires-dist = [ { name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=5.0" }, { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.4" }, ] -provides-extras = ["dev", "docs"] +provides-extras = ["dev", "mcp", "docs"] [[package]] name = "policyengine" @@ -2909,6 +3005,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" }, ] +[[package]] +name = "pyjwt" +version = "2.15.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/43/ea/5194e52748b0da83d71e082d75496eaec6e58f419f5e184786ded517e6a9/pyjwt-2.15.1.tar.gz", hash = "sha256:4f259e80cdfb6b3fc18a7de51fd1ef9ec79652f25019bae68975ca2468a34df8", size = 121252, upload-time = "2026-09-28T18:40:42.598Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/50/ca/44de4e75f8aadc457f0634be3b542815078ded46dca30efb960edeecad6e/pyjwt-2.15.1-py3-none-any.whl", hash = "sha256:42d59d631f7768a1028a64c7ff581a9bf7519804daf91fc5b6c56e30eec5e193", size = 33860, upload-time = "2026-09-28T18:40:41.429Z" }, +] + +[package.optional-dependencies] +crypto = [ + { name = "cryptography" }, +] + [[package]] name = "pytest" version = "8.4.2" @@ -2969,6 +3079,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/51/e5/fecf13f06e5e5f67e8837d777d1bc43fac0ed2b77a676804df5c34744727/python_json_logger-4.0.0-py3-none-any.whl", hash = "sha256:af09c9daf6a813aa4cc7180395f50f2a9e5fa056034c9953aec92e381c5ba1e2", size = 15548, upload-time = "2025-10-06T04:15:17.553Z" }, ] +[[package]] +name = "python-multipart" +version = "0.0.34" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7e/c0/c753d487a83d873f6946cee6cbc26cea3fe59a476ad0de99a14938a2fbd8/python_multipart-0.0.34.tar.gz", hash = "sha256:b998ae90ca6e1e363261ce2e0e230281b8af53867b757970abd69ee9edcd843a", size = 52456, upload-time = "2026-11-16T10:40:38.261Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f5/0e/090c52b122d8ec5fa37942c1410fea9cf04ce98bca0c84dde7f0aa11594d/python_multipart-0.0.34-py3-none-any.whl", hash = "sha256:ebacd224bd686eee2f9aa1066a657affe07435a185834e05e5235e2e59173e91", size = 32585, upload-time = "2026-11-16T10:40:37.119Z" }, +] + [[package]] name = "pyvis" version = "0.3.2" @@ -2983,6 +3102,28 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ab/4b/e37e4e5d5ee1179694917b445768bdbfb084f5a59ecd38089d3413d4c70f/pyvis-0.3.2-py3-none-any.whl", hash = "sha256:5720c4ca8161dc5d9ab352015723abb7a8bb8fb443edeb07f7a322db34a97555", size = 756038, upload-time = "2023-02-24T20:29:46.758Z" }, ] +[[package]] +name = "pywin32" +version = "312" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1f/f5/10a6e845a00fc5e7afd0a988b744f403d4d57162a28d160a093c4d9322f0/pywin32-312-cp311-cp311-win32.whl", hash = "sha256:17948aeadbdb091f0ced6ef0841620794e68327b94ee415571c1203594b7215c", size = 6362659, upload-time = "2026-06-04T07:49:21.349Z" }, + { url = "https://files.pythonhosted.org/packages/35/c4/dcd2d62b5944b6d5db53413a5899016ccd57ffcb7278f3f81655d25d2027/pywin32-312-cp311-cp311-win_amd64.whl", hash = "sha256:d11417d84412f859b722fad0841b3614459ed0047f7542d8362e77884f6b6e8a", size = 6928825, upload-time = "2026-06-04T07:49:23.934Z" }, + { url = "https://files.pythonhosted.org/packages/b7/56/3cbb433fe4501cdba2eb9040f56a4e1a8243faa4186b25295564d1a7a79d/pywin32-312-cp311-cp311-win_arm64.whl", hash = "sha256:b2200a054ca6d6625c4842fc56a4976a4b47f96b73dbe5538c3f813a80359f47", size = 6721875, upload-time = "2026-06-04T07:49:26.416Z" }, + { url = "https://files.pythonhosted.org/packages/83/ff/32aa7d2ed0ab12b323aaa64f9b75e6ad4f8fd09f9ccfc28c79414d46838d/pywin32-312-cp312-cp312-win32.whl", hash = "sha256:dab4f65ac9c4e48400a2a0530c46c3c579cd5905ecd11b80692373915269208b", size = 6371877, upload-time = "2026-06-04T07:49:28.836Z" }, + { url = "https://files.pythonhosted.org/packages/03/d9/77040d3b43df3f3be32ea289433d660d2727f5ba327bc73be835127d9d60/pywin32-312-cp312-cp312-win_amd64.whl", hash = "sha256:b457f6d628a47e8a7346ce22acb7e1a46a4a78b52e1d17e1af56871bd19a93bc", size = 6914841, upload-time = "2026-06-04T07:49:31.85Z" }, + { url = "https://files.pythonhosted.org/packages/e3/cc/7b1ec671775756020a0ee7f4feeaf3c568f0ab86bd3900088cf986937a92/pywin32-312-cp312-cp312-win_arm64.whl", hash = "sha256:6017c58e12f6809fbb0555b75df144c2922a9ffd18e4b9b5afa863b6c1a9d950", size = 6727901, upload-time = "2026-06-04T07:49:34.244Z" }, + { url = "https://files.pythonhosted.org/packages/2d/41/12fbfd7f36ed2146d8bc9de96c2741296bf0d490b98508496cff322e274c/pywin32-312-cp313-cp313-win32.whl", hash = "sha256:7a27df850933d16a8eabfbaeb73d52b273e2da667f80d70b01a89d1f6828d02c", size = 6370184, upload-time = "2026-06-04T07:49:36.253Z" }, + { url = "https://files.pythonhosted.org/packages/ba/db/36a78e3403099d31d9746d13fdcde5accc43c1155f375a34d15983a479a7/pywin32-312-cp313-cp313-win_amd64.whl", hash = "sha256:c53e878d15a1c44788082bfe712a905433473aa38f86375b7cf8b45e3acbaaf9", size = 6914298, upload-time = "2026-06-04T07:49:38.876Z" }, + { url = "https://files.pythonhosted.org/packages/84/37/c1697194092b76de9ed47ca124323f02c57ffc8a45c06f88a3d5acaf01eb/pywin32-312-cp313-cp313-win_arm64.whl", hash = "sha256:59aba5d5940842075343a5ddc6b11f1cdf0d1567fe745290359dfbcc7c2eb831", size = 6727640, upload-time = "2026-06-04T07:49:41.083Z" }, + { url = "https://files.pythonhosted.org/packages/fc/2b/1f3cded5822fd49c02f40544cbb5f58c7cfd6b1694869fd476cb6170ee97/pywin32-312-cp314-cp314-win32.whl", hash = "sha256:a77a90fbb6881238d2ca9c6fd797b25817f3768fe78d214a90137ff055a75f5b", size = 6468928, upload-time = "2026-06-04T07:49:43.188Z" }, + { url = "https://files.pythonhosted.org/packages/21/82/3bf86d2e2808902013132e1ce905a7da0da53790f3836c64bf44d55e24f3/pywin32-312-cp314-cp314-win_amd64.whl", hash = "sha256:a4dd3a848290ef724347b19f301045831d8e802fa4464f491b98b1e0a081432e", size = 7024157, upload-time = "2026-06-04T07:49:45.34Z" }, + { url = "https://files.pythonhosted.org/packages/a4/0e/73f6d6800b4f27655abd9e9f6aaeaefcddb2b946e4674efa2bab184a7f7b/pywin32-312-cp314-cp314-win_arm64.whl", hash = "sha256:9fce94568364e0155e6dfb781ac5d95903be8baf28670632beab1b523f300daa", size = 6839598, upload-time = "2026-06-04T07:49:47.613Z" }, + { url = "https://files.pythonhosted.org/packages/eb/61/caa39686032d2ebdd04ff0ab5cbe163126c0066d98e00c9018646e42393b/pywin32-312-cp315-cp315-win32.whl", hash = "sha256:5c1fbe4a937a73ae9297384a3da38518cbc694c68ad8a809b2e19acd350f03ed", size = 6471159, upload-time = "2026-06-04T07:49:50.035Z" }, + { url = "https://files.pythonhosted.org/packages/0f/cd/7e1de64a4a6f69c04214169657ccab0d93a670ea50e35eb8f489d7378249/pywin32-312-cp315-cp315-win_amd64.whl", hash = "sha256:c2f03a0f73f804a13c2735b99392b0cd426bb4f2c4d0178e5ac966a0f21618d5", size = 7025293, upload-time = "2026-06-04T07:49:54.857Z" }, + { url = "https://files.pythonhosted.org/packages/23/ed/4532e9388e65fa16b46776ef47ad631a64eda1631884488af707666350ed/pywin32-312-cp315-cp315-win_arm64.whl", hash = "sha256:a8597d28f267b39074aef51fa593530082b39cbe5a074226096857b1fed2dfb9", size = 6840337, upload-time = "2026-06-04T07:49:57.531Z" }, +] + [[package]] name = "pywinpty" version = "3.0.3" @@ -3499,6 +3640,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/50/6c/8c2d9380c53c8fb98bdd9da633a8cc16cf83a89b21fa6e0653cc19e1b592/spm_calculator-1.0.0.post1-py3-none-any.whl", hash = "sha256:c9834a761891ba12de1edd585688c8b477be58e9a9c9fa92d9cfdf41e5396a41", size = 7395585, upload-time = "2026-09-14T02:49:54.541Z" }, ] +[[package]] +name = "sse-starlette" +version = "3.7.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "starlette" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/41/43/a232e3cd804293bd4f6d01e8895bc0f6f83ea148d712baf9d783c7d93d23/sse_starlette-3.7.0.tar.gz", hash = "sha256:326416da2ab52e9a41b3f409d3ff897eda45aa68c9f3b7b17d0913aab8d219c3", size = 43869, upload-time = "2026-11-07T11:15:49.389Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6a/11/25cabac0a24fa76f58637d8671b549c90d818d69d26beecf0c59a3b186e0/sse_starlette-3.7.0-py3-none-any.whl", hash = "sha256:f1d3136caa12d129284fca3d2ded79bc9af943320b6472712955fea52a6d3eea", size = 18432, upload-time = "2026-11-07T11:15:47.86Z" }, +] + [[package]] name = "stack-data" version = "0.6.3" @@ -3522,6 +3676,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/df/cb/e1da7e340586a078404c7e4328bfefc930867ace8a9a55916fd220cf9547/standard_imghdr-3.13.0-py3-none-any.whl", hash = "sha256:30a1bff5465605bb496f842a6ac3cc1f2131bf3025b0da28d4877d6d4b7cc8e9", size = 4639, upload-time = "2024-10-30T16:01:13.829Z" }, ] +[[package]] +name = "starlette" +version = "1.10.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/48/bb/3d8757f21e9a53d9035c9eb039a777047139a16bfdbedfc7a58241c3d914/starlette-1.10.0.tar.gz", hash = "sha256:b8399098d4c1e3522734f7235dc79b1fc967f96cf139c81e0fa30479e0685f9b", size = 2734356, upload-time = "2026-10-24T15:04:12.342Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/2e/947cfe02def9371c07cd5bf5b6b61c829e9aecb9904db02a66cfafbc1eec/starlette-1.10.0-py3-none-any.whl", hash = "sha256:478c0ab3b4ced6e82719849c118fa406f0278a3499c1a898cd15cd31bdc38ce4", size = 80571, upload-time = "2026-10-24T15:04:10.371Z" }, +] + [[package]] name = "tables" version = "3.11.1" @@ -3754,6 +3921,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/00/c0/8f5d070730d7836adc9c9b6408dec68c6ced86b304a9b26a14df072a6e8c/traitlets-5.14.3-py3-none-any.whl", hash = "sha256:b74e89e397b1ed28cc831db7aea759ba6640cb3de13090ca145426688ff1ac4f", size = 85359, upload-time = "2024-04-19T11:11:46.763Z" }, ] +[[package]] +name = "truststore" +version = "0.10.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ee/9f/c5201d42a484c061e528825fc8e2d565f5abd50a4ced6fb7d29c4ec99b2b/truststore-0.10.5.tar.gz", hash = "sha256:30d36967ccaded5cbb38d602c433f53600036c79d502f4533a49b60a03bbefcd", size = 28091, upload-time = "2026-10-12T22:27:31.808Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/e9/3a7820be2bb0fe53b6bc9c3be26d3d1158004e4c3ab953aa6840b955b1e9/truststore-0.10.5-py3-none-any.whl", hash = "sha256:9aaaedaefaf06d8b206278cf8b5012bc897f485a874503501e12d776df78951c", size = 19017, upload-time = "2026-10-12T22:27:30.377Z" }, +] + [[package]] name = "typer" version = "0.24.1" @@ -3841,6 +4017,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/65/a8/1791660a87f03d10a3bce00401a66035999c91f5a9a6987569b84df5719d/us-3.2.0-py3-none-any.whl", hash = "sha256:571714ad6d473c72bbd2058a53404cdf4ecc0129e4f19adfcbeb4e2d7e3dc3e7", size = 13775, upload-time = "2024-07-22T01:09:41.432Z" }, ] +[[package]] +name = "uvicorn" +version = "0.54.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/da/34/30e9280707135d2cfc589dfff3cb796bd07a3aeb1a3e415ba09dd89d7bb4/uvicorn-0.54.0.tar.gz", hash = "sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620", size = 112283, upload-time = "2026-09-25T06:52:37.601Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/38/0c/b54a4fdd7f90a3af8b02ebc9ce6712c2c208b7926a2f7bad95c33ebbe943/uvicorn-0.54.0-py3-none-any.whl", hash = "sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf", size = 87427, upload-time = "2026-09-25T06:52:35.829Z" }, +] + [[package]] name = "wcwidth" version = "0.6.0" From e30623cae4ccde596fb0a0df3e7312347d518e5f Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 18 Nov 2026 09:15:02 -0500 Subject: [PATCH 6/9] Replay: keep each answer in memory and write only its comparisons The progress file no longer holds a call's result text, which carries values from the non-public development households; a line keeps the call's hash and the comparisons, as the module docstring now says. Co-Authored-By: Claude Fable 5.2 --- scripts/replay_calculator_calls.py | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/scripts/replay_calculator_calls.py b/scripts/replay_calculator_calls.py index 9c76d183..0502472e 100644 --- a/scripts/replay_calculator_calls.py +++ b/scripts/replay_calculator_calls.py @@ -26,10 +26,11 @@ Steps 1, 2 and 4 are the gate: any difference exits 1. Step 3 is reported per run folder, because the records come from several commits of the harness. -The development households are not public, so neither the records nor this -script's per-call output belong in the repository: ``--out`` gets -``progress.jsonl`` (one line per distinct call, appended as it finishes, so a -rerun resumes) and ``summary.json`` (counts only). +The development households are not public, so the records stay outside the +repository and this script writes nothing of theirs: ``--out`` gets +``progress.jsonl`` (one line of comparisons per distinct call, keyed by a +hash and appended as the call finishes, so a rerun resumes) and +``summary.json`` (counts only). """ from __future__ import annotations @@ -110,8 +111,11 @@ def _framed(module, features: frozenset, arguments): return module.tool_call_frame(features, arguments) if features else arguments -def replay_one(system, registries: dict, entry: dict, simulation_cls=None) -> dict: - """One distinct call through both copies; see the module docstring.""" +def replay_one( + system, registries: dict, entry: dict, simulation_cls=None +) -> tuple[dict, str]: + """One distinct call through both copies (see the module docstring): the + comparisons, and the package's answer text.""" features, arguments = entry["features"], entry["arguments"] started = time.perf_counter() answers, readings, accepted = {}, {}, {} @@ -146,9 +150,8 @@ def replay_one(system, registries: dict, entry: dict, simulation_cls=None) -> di _framed(core, features, sent), registries[core] ) line["same_as_object"] = json.dumps([request, error]) == readings[core] - line["answer"] = answers[core] line["seconds"] = round(time.perf_counter() - started, 3) - return line + return line, answers[core] def summarize(calls: dict[str, dict], lines: dict[str, dict]) -> dict: @@ -248,13 +251,11 @@ def replay( with progress.open("a") as handle: for index, key in enumerate(todo, start=1): entry = calls[key] - line = { - "key": key, - **replay_one(system, registries, entry, simulation_cls), - } + line, answer = replay_one(system, registries, entry, simulation_cls) + line = {"key": key, **line} if over_mcp and line["sendable"]: line["same_over_mcp"] = ( - _over_mcp(sessions, board, entry) == line["answer"] + _over_mcp(sessions, board, entry) == answer ) lines[key] = line handle.write(json.dumps(line) + "\n") From 044690ef261850929c9daca1c4da50c5165a9bba Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 18 Nov 2026 09:24:52 -0500 Subject: [PATCH 7/9] Replay: test the path through the MCP server The launch of the package's server for a feature set moves into _server_parameters, so a test can put the fake-engine server in its place: with --mcp every call the protocol can carry goes through a server, one per feature set; refusals, which the validator alone decides, must match; and a server whose engine answers differently fails the gate on every accepted call. A second test pins the real launch command to the board and the call's features. Co-Authored-By: Claude Fable 5.2 --- scripts/replay_calculator_calls.py | 36 +++++++++-------- tests/test_calculator_recorded_calls.py | 54 +++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 16 deletions(-) diff --git a/scripts/replay_calculator_calls.py b/scripts/replay_calculator_calls.py index 0502472e..c3a35146 100644 --- a/scripts/replay_calculator_calls.py +++ b/scripts/replay_calculator_calls.py @@ -279,28 +279,32 @@ def replay( return summary -def _over_mcp(sessions: dict, board: Path, entry: dict) -> str: - """The text the package's MCP server answers the call with: one server per - feature set, launched over stdio on the same board.""" +def _server_parameters(board: Path, features: frozenset): + """How to launch the package's MCP server for one feature set over stdio, + on the board's engine, with one worker.""" from mcp import StdioServerParameters + arm = "pe:" + "+".join(sorted(features)) if features else "pe" + return StdioServerParameters( + command=sys.executable, + args=[ + "-m", + "policybench_calculator.mcp_server", + *("--arm", arm, "--board", str(board), "--workers", "1"), + ], + cwd=str(ROOT), + env=dict(os.environ), + ) + + +def _over_mcp(sessions: dict, board: Path, entry: dict) -> str: + """The text the package's MCP server answers the call with: one server per + feature set, kept open for the run.""" from policybench_calculator.mcp_client import McpToolCall features = entry["features"] if features not in sessions: - arm = "pe:" + "+".join(sorted(features)) if features else "pe" - sessions[features] = McpToolCall( - StdioServerParameters( - command=sys.executable, - args=[ - "-m", - "policybench_calculator.mcp_server", - *("--arm", arm, "--board", str(board), "--workers", "1"), - ], - cwd=str(ROOT), - env=dict(os.environ), - ) - ) + sessions[features] = McpToolCall(_server_parameters(board, features)) return json.dumps(sessions[features](entry["arguments"])[0]) diff --git a/tests/test_calculator_recorded_calls.py b/tests/test_calculator_recorded_calls.py index b545b136..d4fe28e3 100644 --- a/tests/test_calculator_recorded_calls.py +++ b/tests/test_calculator_recorded_calls.py @@ -210,6 +210,60 @@ def test_the_command_exits_1_when_the_gate_fails(monkeypatch, capsys): assert "gate failures: 2" in capsys.readouterr().out +def test_the_mcp_path_sends_each_sendable_call_through_a_server( + runs, tmp_path, monkeypatch +): + """With --mcp every call the protocol can carry also goes through an MCP + server, one per feature set, and a different answer fails the gate. The + server launched here is the fake-engine one, whose results differ from + this test's fake engine by design: so the refusals, which come from the + validator alone, must match, and every accepted call must be caught.""" + from mcp import StdioServerParameters + + launched = [] + + def fake_server(board, features): + arm = "pe:" + "+".join(sorted(features)) if features else "pe" + launched.append(arm) + return StdioServerParameters( + command=sys.executable, + args=[str(ROOT / "tests/calculator_mcp_fake.py"), "stdio", arm], + env=dict(os.environ), + ) + + monkeypatch.setattr(replay, "_server_parameters", fake_server) + summary = _replay(runs, tmp_path / "out", over_mcp=True) + overall = summary["overall"] + assert sorted(launched) == ["pe", "pe:names"] + assert overall["mcp_checked"] == overall["sendable"] == 5 + assert overall["mcp_differs"] == overall["accepted"] == 3 + assert summary["gate_failures"] == 3 + lines = [ + json.loads(text) + for text in (tmp_path / "out/progress.jsonl").read_text().splitlines() + ] + assert all(line["same_over_mcp"] for line in lines if not line["accepted"]) + assert not any(line["same_over_mcp"] for line in lines if line["accepted"]) + assert all("answer" not in line for line in lines) + + +def test_the_real_server_is_launched_on_the_board_with_the_calls_features(): + board = pilot.SNAPSHOT + for features, arm in ( + (frozenset(), "pe"), + (frozenset({"names", "flat"}), "pe:flat+names"), + (frozenset(pilot.TOOL_FEATURES), "pe:" + "+".join(sorted(pilot.TOOL_FEATURES))), + ): + parameters = replay._server_parameters(board, features) + assert parameters.command == sys.executable + assert parameters.args[:2] == ["-m", "policybench_calculator.mcp_server"] + assert parameters.args[2:] == [ + *("--arm", arm, "--board", str(board), "--workers", "1") + ] + assert core.arm_features(arm) == features + assert parameters.cwd == str(ROOT) + + def test_a_record_whose_features_are_not_its_arms_is_refused(runs): path = runs / "model-b/abl-add-names/mctest/households/mt_000.json" record = json.loads(path.read_text()) From 9c69afa8efd7cb53a8e5b86f6ad129f08eaa5fb6 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 18 Nov 2026 09:26:50 -0500 Subject: [PATCH 8/9] Test the MCP server end to end on the engine A slow test starts the server as its command does (stdio, the frozen board, the pilot's own worker with its output off the wire) and compares its answers with the pilot's pool on the same board, for a household written for the test: accepted, read under a label, explained in brief and in full, and refused. It needs the frozen board's engine and two engine workers, so the suite's default run leaves it out; run it with -m slow. Co-Authored-By: Claude Fable 5.2 --- tests/test_calculator_mcp.py | 79 ++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/tests/test_calculator_mcp.py b/tests/test_calculator_mcp.py index 0cbc13cc..cc9c7fed 100644 --- a/tests/test_calculator_mcp.py +++ b/tests/test_calculator_mcp.py @@ -418,6 +418,85 @@ def test_the_client_is_a_tool_call_for_the_pilots_loop(mode): assert [json.dumps(result) for result, _ in results] == _pilot_answers(arm, calls) +# A household written for this test (no benchmark household), for the engine. +ENGINE_HOUSEHOLD = { + "state": "CA", + "people": [ + {"role": "head", "facts": {"age": 34, "employment_income": 28000}}, + {"role": "dependent", "facts": {"age": 6}}, + ], +} +LABELLED_HOUSEHOLD = { + "state": "CA", + "people": [ + {"role": "head", "facts": {"age": 34, "gross wages and salaries": 28000}}, + {"role": "dependent", "facts": {"Age": 6}}, + ], +} +ENGINE_CALLS = [ + {"household": ENGINE_HOUSEHOLD, "variables": ["eitc", "snap", "income_tax"]}, + {"household": json.dumps(LABELLED_HOUSEHOLD), "variables": ["eitc"]}, + {"household": ENGINE_HOUSEHOLD, "variables": ["eitc"], "explain": ["eitc"]}, + { + "household": ENGINE_HOUSEHOLD, + "variables": ["eitc"], + "explain": ["eitc"], + "detail": "full", + "period": "2026", + }, + {"household": ENGINE_HOUSEHOLD, "variables": ["telepathy"]}, + {"situation": {"people": {"head": {"age": 34}}}, "variables": ["eitc"]}, +] +ENGINE_TIMEOUT_SECONDS = 600.0 + + +@pytest.mark.slow +def test_on_the_engine_the_server_answers_as_the_pilots_pool(): + """End to end on policyengine-us: the server as its command starts it + (stdio, the frozen board, the pilot's own worker) against the pilot's pool + on the same board, for calls it accepts, explains and refuses. Needs the + frozen board's engine, starts two engine workers, and takes minutes.""" + from mcp import StdioServerParameters + + engine = pilot.board_engine() + if pilot._versions()["policyengine-us"] != engine: + pytest.skip("the installed policyengine-us is not the frozen board's") + arm = "pe3" + pool = pilot.ToolPool( + size=1, timeout=ENGINE_TIMEOUT_SECONDS, tool_features=pilot.arm_features(arm) + ) + try: + expected = [json.dumps(pool.call(arguments)[0]) for arguments in ENGINE_CALLS] + assert pool.counters() == {"timeouts": 0, "crashes": 0, "lost": 0} + finally: + pool.close() + launch = StdioServerParameters( + command=sys.executable, + args=[ + *("-m", "policybench_calculator.mcp_server", "--arm", arm), + *("--workers", "1", "--timeout", str(ENGINE_TIMEOUT_SECONDS)), + ], + cwd=str(ROOT), + env=dict(os.environ), + ) + with mcp_client.McpToolCall( + launch, call_timeout=2 * ENGINE_TIMEOUT_SECONDS + ) as tool_call: + listed = tool_call.tool() + provenance = tool_call.provenance() + answers = [json.dumps(tool_call(arguments)[0]) for arguments in ENGINE_CALLS] + assert listed == _pilot_tool(arm, engine) + assert provenance["policyengine-us"] == engine + assert provenance["fix_module_sha256"] == pilot.FIX_MODULE_SHA256 + assert answers == expected + results = [json.loads(text) for text in answers] + assert all("results" in result for result in results[:4]), results[:2] + assert results[1].get("notes"), "the labelled household is read with notes" + assert "explanations" in results[2] and "explanations" in results[3] + assert results[2]["explanations"] != results[3]["explanations"] + assert [result.get("error") for result in results[4:]] == ["validation"] * 2 + + def test_the_schema_hash_is_the_sorted_dumps_sha256(): calculator = fake.calculator("pe") assert ( From ca23666f63d035074cedcba72d5622b996a50e95 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 18 Nov 2026 09:29:24 -0500 Subject: [PATCH 9/9] Fix the MCP-path test: a call the protocol cannot carry has no MCP comparison The test read same_over_mcp on every refused line, and the line for arguments that are not JSON has none (GitHub run 44324015286; the path's own counts had passed). It now checks the sendable lines and that the unsendable one carries no comparison. Co-Authored-By: Claude Fable 5.2 --- tests/test_calculator_recorded_calls.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/test_calculator_recorded_calls.py b/tests/test_calculator_recorded_calls.py index d4fe28e3..46acb9e9 100644 --- a/tests/test_calculator_recorded_calls.py +++ b/tests/test_calculator_recorded_calls.py @@ -242,8 +242,12 @@ def fake_server(board, features): json.loads(text) for text in (tmp_path / "out/progress.jsonl").read_text().splitlines() ] - assert all(line["same_over_mcp"] for line in lines if not line["accepted"]) - assert not any(line["same_over_mcp"] for line in lines if line["accepted"]) + sent = [line for line in lines if line["sendable"]] + unsent = [line for line in lines if not line["sendable"]] + assert len(sent) == 5 and len(unsent) == 1 + assert "same_over_mcp" not in unsent[0] + assert all(line["same_over_mcp"] for line in sent if not line["accepted"]) + assert not any(line["same_over_mcp"] for line in sent if line["accepted"]) assert all("answer" not in line for line in lines)