Stopping auto carry-over for one input needs a formula, which drops the input from exports and the household builder

Abierto
#665 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
25/100
Tipo de issue
Error
Claridad
Bastante claro
Estado de actividad
Activo
Stack tecnológico
python
Área
backend

Línea de trabajo

Start with the carry-over branch in policyengine_core/simulations/simulation.py (around L1956-L1960), which checks only calculate_output, and with is_input_variable() in policyengine_core/variables/variable.py (around L673-L679). Run the reproduction in the issue against tests/fixtures/carry_over.py. Done means the reporter's script gives the expected results and is_input_variable() stays True for a raw input with a default formula. The fix needs a maintainer decision on the new per-variable setting, so confirm the design before coding.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Core has no per-variable switch for auto_carry_over_input_variables. To make a raw input apply only to the period someone entered it for, a country package gives the variable a formula that returns the default. That formula also makes is_input_variable() return False, so the input drops out of Core's input exports and the web app's household builder, and the API's variable metadata flags it as a non-input.

What happens

When a variable has no formula, or its formula returns None for a period, Core falls back on an earlier input. It uprates that input if the variable declares uprating, and otherwise carries it if the system turns on auto_carry_over_input_variables (simulation.py L1868-L1874). The carry-over branch tests no per-variable setting other than calculate_output (L1956-L1960). A formula that returns the default stops both paths. A value supplied for the period itself still wins, because Core returns a stored value before it runs any formula (L1731-L1734).

Core counts any variable with a formula as a non-input (variable.py L673-L679), so every reader of is_input_variable() then treats the raw input as computed.

Reproduction

We wrote this from Core at e556c9e (3.37.1), following tests/fixtures/carry_over.py, and have not run it. The comments give the values we expect; the printed arrays may differ in format.

# Not run. Written from policyengine-core e556c9e (3.37.1).
import numpy as np

from policyengine_core import periods
from policyengine_core.country_template import CountryTaxBenefitSystem, entities
from policyengine_core.parameters import ParameterNode
from policyengine_core.simulations import SimulationBuilder
from policyengine_core.variables import Variable


class carried_input(Variable):
    value_type = float
    entity = entities.Person
    definition_period = periods.YEAR
    label = "Plain input"


class uprated_input(Variable):
    value_type = float
    entity = entities.Person
    definition_period = periods.YEAR
    uprating = "agi.index"
    label = "Plain input with an uprating index"


class formula_input(Variable):
    value_type = float
    entity = entities.Person
    definition_period = periods.YEAR
    label = "Raw input with a default formula"

    def formula(person, period, parameters):
        return person.empty_array()


system = CountryTaxBenefitSystem()
system.auto_carry_over_input_variables = True  # as policyengine-us sets it
system.parameters.add_child(
    "agi",
    ParameterNode(
        "agi",
        data={"index": {"values": {"2025-01-01": 17_837.9, "2026-01-01": 18_810.4}}},
    ),
)
system.add_variables(carried_input, uprated_input, formula_input)

sim = SimulationBuilder().build_default_simulation(system, count=2)
for name in ("carried_input", "uprated_input", "formula_input"):
    sim.set_input(name, "2025", np.array([40_000.0, -1.0]))

print(sim.calculate("carried_input", "2026"))  # [40000, -1]: carried
print(sim.calculate("uprated_input", "2026"))  # about [42180.75, -1.0545]: uprated
print(sim.calculate("formula_input", "2026"))  # [0, 0]: the formula's default
print(sim.calculate("formula_input", "2025"))  # [40000, -1]: the input wins
print(system.get_variable("formula_input").is_input_variable())  # False
print("carried_input" in sim.to_input_dict())  # True
print("formula_input" in sim.to_input_dict())  # False
print("formula_input" in sim.true_input_variables)  # False

Why policyengine-us hits it

The policyengine-us package turns carry-over on (system.py L114), while Core leaves it off by default (tax_benefit_system.py L136). It also sets the CBO adjusted gross income index as the uprating of every plain float USD input that declares none, unless the name appears in NO_DEFAULT_UPRATING_VARIABLES (default_uprating.py L4-L6, L110-L134). Core uprates from the latest earlier input (simulation.py L1903-L1955).

The index rises from $17,837.9 billion for 2025 to $18,810.4 billion for 2026 (income_by_source.yaml L56-L57), a factor of about 1.0545. Without a formula, a 2025 entry of 40,000 would read about 42,180.75 in 2026, and a supplied -1 would read about -1.0545 (our arithmetic, not run). Core uprates stored inputs and never a default, so only a supplied -1 moves.

Some of its inputs record a fact about one period: a form line for one tax year, a payment in one month, or the days in a partial month. For these, carry-over applies an entry to later periods, and the default uprating also scales a dollar amount. At least 21 such variables on policyengine-us main already return a default from a formula. For example, a comment in the medicaid_ltss_irwe_monthly_payments formula reads: "A zero fallback prevents Core from carrying or uprating past inputs." Open draft PR PolicyEngine/policyengine-us#11222 adds two more, and each one's documentation tells users that the input exports leave a supplied amount out (dependent_care_employer_benefits_forfeited_or_carried_forward, taxable_dependent_care_benefits_reported).

The 21 default-returning formulas on policyengine-us main (b274cac)

What the formula costs

  • Input exports. By default, true_input_variables, to_input_dict() and to_input_dataframe() export only variables that pass is_input_variable() (simulation.py L3335-L3342, L3353-L3364, L3404-L3428, L3455-L3492). They leave out a supplied value of a formula-backed input. include_computed_variables=True brings it back, but it also exports every other known period, calculated values included.
  • The household builder. The API (policyengine-api) publishes isInputVariable from is_input_variable() (country.py L324). The web app keeps only input variables (VariableResolver.ts L357-L364), and the household builder offers and searches only that list (HouseholdBuilderForm.tsx L306-L316, L368-L382). The policyengine.py package publishes the same flag (model_version.py L102-L107, L255). A policyengine-us test keeps one variable formula-free for this reason (test_input_variable_definitions.py L57-L59). We read this path in each repo's current default branch and did not test the live services.
  • Abolition parameters. add_abolition_parameters() creates gov.abolitions.<name> for every bool, int or float variable that fails is_input_variable() (tax_benefit_system.py L247-L256), and policyengine-us calls it (system.py L137). When a reform turns that parameter on, Core returns the default before it reads a stored value (simulation.py L1720-L1734), so it would discard a supplied amount. We have not checked whether the app's policy editor lists these parameters.

Options

1. Let a variable opt out of carry-over

Add a Variable attribute that keeps is_input_variable() true and takes the variable out of carry-over. It would switch off both the cross_period_fallback test (L1870-L1873) and the carry-over branch (L1956-L1960), so a period without an entry reads the default. subsample applies the same rule when it picks a weight period (L3532-L3536), so the switch belongs there too.

class reported_amount(Variable):
    value_type = float
    entity = Person
    definition_period = YEAR
    carry_over = False  # name open

Uprating already works per variable: Core uprates a variable only when it declares uprating (L1904), and policyengine-us can add these names to NO_DEFAULT_UPRATING_VARIABLES. Maintainers could instead have the attribute block uprating as well. That choice needs a rule for a variable that also declares uprating, as check_computation_modes has for a formula with uprating (variable.py L413-L421).

Trade-offs:

  • Core gains a public attribute that its carry-over tests and docs must cover.
  • The attribute has to stay opt-in. A dataset loaded for one year feeds later years through carry-over (L1956-L2005), so an opted-out variable without uprating reads its default in those years. That suits one-period facts, but a stock or a characteristic needs the carry.
  • In return, the 21 variables above and the two in PolicyEngine/policyengine-us#11222 could drop their formulas. They would appear as inputs in exports and the builder, and lose their abolition parameters (inferred from the source above).

Core already skips carry-over for a variable that sets calculate_output (L1872, L1958). That hook serves calculate_add and calculate_divide aggregation (helpers.py L4-L9), so a package that set it only to stop carry-over would rely on a side effect. We infer from the source that it would stop carry-over but not uprating; we have not tested it.

2. Export recorded inputs of formula-backed variables

Core already records each value a caller passes to set_input, whether or not the variable has a formula (_get_set_input_periods, L3366-L3382), and subsample rebuilds from that record (L3604). The to_input_* methods could export from it too.

Trade-offs:

  • A dataset load in any format calls set_input for every column the system knows (L1246-L1294, holder.py L837-L846). A blanket export would write out stored values of formula variables, which then override the formulas on reload. #417 and #418 describe that hazard, and #496 closed it. We have not checked whether current datasets carry such columns.
  • An explicit list avoids the hazard. Open draft PR #646 adds TaxBenefitSystem.source_input_variables, and its _is_exportable_input_variable accepts the names on that list (simulation.py L3258-L3267 at 8a094a2). We infer from that change that it would export the variables a package lists.
  • Either way, is_input_variable() stays False and the formula stays. The API and policyengine.py still flag the variable as a non-input, the app still hides it, and Core still creates its abolition parameter.

Related

  • #646 takes the export route for formula variables that keep their formulas.
  • #634 would report whether a read takes its value from a carried input. It would not stop the carry, and it covers only variables with no formula and no uprating.
  • #513 asks Core to keep a missing input apart from zero. PolicyEngine/policyengine-us#11222 marks "not supplied" with a -1 default.

🤖 Generated with Claude Code

Lenguaje dominante
Python
Estrellas
22
Forks
31
Merge medio
1 d 19 h
PR fusionados (30 d)
14

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de PolicyEngine/policyengine-core

Todos los issues de PolicyEngine/policyengine-core

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.