// Known-answer checks for pure monthly operating/debt composition. #include "sc2k/sim/monthly_finance.hpp" #include "sc2k/io/native_finance.hpp" #include "test_harness.hpp" #include #include #include using namespace sc2k; static sim::DebtInstrument due_instrument() { sim::DebtInstrument instrument; instrument.id = 1; instrument.kind = sim::DebtKind::AmortisingBond; instrument.origin = sim::DebtOrigin::NativeIssue; instrument.originalPrincipal = 10000; instrument.remainingPrincipal = 10000; instrument.annualRate = 400; instrument.issuePeriod = 0; instrument.maturityPeriod = 60; instrument.nextDuePeriod = 1; instrument.termMonths = 60; instrument.contractedPayment = 185; instrument.frequency = sim::PaymentFrequency::Monthly; return instrument; } static sim::MunicipalDebt due_debt() { sim::MunicipalDebt debt; debt.nextId = 2; debt.instruments = {due_instrument()}; return debt; } static sim::MunicipalDebt supervised_debt_due_at(sim::Period period) { sim::MunicipalDebt debt = due_debt(); debt.instruments[0].nextDuePeriod = period; debt.instruments[0].maturityPeriod = 120; debt.instruments[0].termMonths = 120; debt.support.status = sim::FiscalStatus::GovernmentSupervision; debt.support.lastBailoutPeriod = 0; debt.support.bailoutEligibleAgainPeriod = 60; debt.support.lastBailoutAmount = 10000; return debt; } int main() { // This month's revenue can turn an otherwise-insufficient debt quote into one atomic Ready quote. { std::array records{}; // 75 * 120 / (12 * 75) = 10 cash. records[0].rate = 75; records[0].value = 120; const sim::MunicipalDebt debt = due_debt(); const sim::MonthlyFinanceQuoteResult result = sim::quote_monthly_finance( records, sim::OperatingBudgetState{}, debt, 1, 175); CHECK(result.status == sim::MonthlyFinanceQuoteStatus::Ready); CHECK(result.quote.has_value()); CHECK(!result.pendingOperatingState); if (result.quote) { CHECK(result.quote->operating.revenueCash == 10); CHECK(result.quote->operating.treasuryAfterRevenue == 185); CHECK(result.quote->debt.treasuryBefore == 185); CHECK(result.quote->debt.aggregatePayment == 185); CHECK(result.quote->debt.treasuryAfter == 0); CHECK(result.quote->operating.treasuryAfter == 0); } } // Revenue that still cannot cover senior debt yields one non-committable composite quote. { std::array records{}; records[0].rate = 75; records[0].value = 120; const sim::MunicipalDebt debt = due_debt(); const sim::MonthlyFinanceQuoteResult result = sim::quote_monthly_finance( records, sim::OperatingBudgetState{}, debt, 1, 174); CHECK(result.status == sim::MonthlyFinanceQuoteStatus::InsufficientForDebt); CHECK(result.quote.has_value()); if (result.quote) { CHECK(result.quote->operating.treasuryAfterRevenue == 184); CHECK(result.quote->debt.treasuryBefore == 184); CHECK(result.quote->debt.treasuryAfter == -1); } } // Debt affordability is resolved before the one-time Critical operating decision is exposed. { std::array records{}; records[5].rate = 12; records[5].value = 10; sim::MunicipalDebt debt; const sim::MonthlyFinanceQuoteResult paused = sim::quote_monthly_finance( records, sim::OperatingBudgetState{}, debt, 8, 4); CHECK(paused.status == sim::MonthlyFinanceQuoteStatus::AwaitingCriticalDecision); CHECK(paused.quote.has_value()); CHECK(paused.pendingOperatingState && paused.pendingOperatingState->pendingDecisionPeriod == 8); if (paused.pendingOperatingState) { const sim::MonthlyFinanceQuoteResult accepted = sim::quote_monthly_finance(records, *paused.pendingOperatingState, debt, 8, 4, true); CHECK(accepted.status == sim::MonthlyFinanceQuoteStatus::Ready); CHECK(accepted.quote && accepted.quote->operating.nextState.coverageBasisPoints == 4000); } } // A persisted government decision takes precedence and no operating proposal is produced. { sim::MunicipalDebt debt = due_debt(); debt.support.pending = sim::PendingBailout{1, 185, 100, 10000, 10085}; const sim::MonthlyFinanceQuoteResult result = sim::quote_monthly_finance({}, sim::OperatingBudgetState{}, debt, 1, 100); CHECK(result.status == sim::MonthlyFinanceQuoteStatus::AwaitingGovernmentDecision); CHECK(!result.quote && !result.pendingOperatingState); } // The two authorities must advance together; aligned repeats are idempotent, mismatches fail closed. { sim::MunicipalDebt debt; debt.lastProcessedPeriod = 12; sim::OperatingBudgetState operating; operating.lastProcessedPeriod = 12; const auto aligned = sim::quote_monthly_finance({}, operating, debt, 12, 0); CHECK(aligned.status == sim::MonthlyFinanceQuoteStatus::AlreadyProcessed); operating.lastProcessedPeriod.reset(); CHECK(sim::quote_monthly_finance({}, operating, debt, 12, 0).status == sim::MonthlyFinanceQuoteStatus::InvalidState); debt.lastProcessedPeriod.reset(); operating.lastProcessedPeriod = 12; CHECK(sim::quote_monthly_finance({}, operating, debt, 12, 0).status == sim::MonthlyFinanceQuoteStatus::InvalidState); } // Identical snapshots produce identical composite decisions and arithmetic. { std::array records{}; records[0].rate = 75; records[0].value = 120; const sim::MunicipalDebt debt = due_debt(); const auto first = sim::quote_monthly_finance( records, sim::OperatingBudgetState{}, debt, 1, 175); const auto second = sim::quote_monthly_finance( records, sim::OperatingBudgetState{}, debt, 1, 175); CHECK(first == second); } // A Ready quote commits revenue, debt, rationed operations, state, and events together. { std::array records{}; records[0].rate = 75; records[0].value = 120; records[5].rate = 12; records[5].value = 10; City city; city.set_funds(180); sim::MunicipalDebt debt = due_debt(); sim::OperatingBudgetState operating; const auto result = sim::quote_monthly_finance(records, operating, debt, 1, city.funds()); CHECK(result.status == sim::MonthlyFinanceQuoteStatus::Ready && result.quote); sim::EventBuffer events; events.begin_batch(25); if (result.quote) { CHECK(sim::commit_monthly_finance( city, debt, operating, records, *result.quote, &events) == sim::MonthlyFinanceCommitResult::Committed); } CHECK(city.funds() == 0); CHECK(debt.lastProcessedPeriod == 1); CHECK(debt.instruments[0].remainingPrincipal == 9848); CHECK(operating.lastProcessedPeriod == 1); CHECK(operating.coverageBasisPoints == 5000); CHECK(operating.consecutiveDistressMonths == 0); CHECK(events.view().size() == 2); const auto* paid = std::get_if(&events.view()[0].payload); const auto* settled = std::get_if( &events.view()[1].payload); CHECK(paid && paid->totalPaid == 185 && paid->fundsAfter == 5); const sim::MonthlyOperatingBudgetSettled expected{ 1, 10, 185, 10, 5, 5000, 0}; CHECK(settled && *settled == expected); CHECK(events.view()[0].stamp.ordinal == 0 && events.view()[1].stamp.ordinal == 1); } // Any changed input makes the quote stale and leaves every authority and event untouched. { std::array records{}; records[0].rate = 75; records[0].value = 120; City city; city.set_funds(175); sim::MunicipalDebt debt = due_debt(); sim::OperatingBudgetState operating; const auto result = sim::quote_monthly_finance(records, operating, debt, 1, city.funds()); CHECK(result.status == sim::MonthlyFinanceQuoteStatus::Ready && result.quote); const sim::MunicipalDebt debtBefore = debt; const sim::OperatingBudgetState operatingBefore = operating; records[0].value = 240; sim::EventBuffer events; events.begin_batch(25); if (result.quote) { CHECK(sim::commit_monthly_finance( city, debt, operating, records, *result.quote, &events) == sim::MonthlyFinanceCommitResult::StaleQuote); } CHECK(city.funds() == 175 && debt == debtBefore && operating == operatingBefore && events.view().empty()); } // A Critical proposal cannot bypass its explicit decision, and narrowing fails atomically. { std::array criticalRecords{}; criticalRecords[5].rate = 12; criticalRecords[5].value = 10; City criticalCity; criticalCity.set_funds(4); sim::MunicipalDebt criticalDebt; sim::OperatingBudgetState criticalOperating; const auto paused = sim::quote_monthly_finance(criticalRecords, criticalOperating, criticalDebt, 0, criticalCity.funds()); CHECK(paused.status == sim::MonthlyFinanceQuoteStatus::AwaitingCriticalDecision); if (paused.quote) { CHECK(sim::commit_monthly_finance(criticalCity, criticalDebt, criticalOperating, criticalRecords, *paused.quote) == sim::MonthlyFinanceCommitResult::StaleQuote); } CHECK(criticalCity.funds() == 4 && !criticalDebt.lastProcessedPeriod && !criticalOperating.lastProcessedPeriod); std::array overflowing{}; overflowing[0].rate = std::numeric_limits::max(); overflowing[0].value = std::numeric_limits::max(); City overflowCity; overflowCity.set_funds(0); sim::MunicipalDebt overflowDebt; sim::OperatingBudgetState overflowOperating; const auto tooLarge = sim::quote_monthly_finance( overflowing, overflowOperating, overflowDebt, 0, 0); CHECK(tooLarge.status == sim::MonthlyFinanceQuoteStatus::Ready && tooLarge.quote); if (tooLarge.quote) { CHECK(sim::commit_monthly_finance(overflowCity, overflowDebt, overflowOperating, overflowing, *tooLarge.quote) == sim::MonthlyFinanceCommitResult::InvalidState); } CHECK(overflowCity.funds() == 0 && !overflowDebt.lastProcessedPeriod && !overflowOperating.lastProcessedPeriod); } // Recording the first Critical decision persists only the pause marker and emits exactly once. { std::array records{}; records[5].rate = 12; records[5].value = 10; sim::MunicipalDebt debt; sim::OperatingBudgetState operating; const auto paused = sim::quote_monthly_finance(records, operating, debt, 4, 4); CHECK(paused.status == sim::MonthlyFinanceQuoteStatus::AwaitingCriticalDecision); sim::EventBuffer events; events.begin_batch(100); CHECK(sim::record_monthly_finance_critical_decision( operating, paused, &events) == sim::MonthlyFinanceDecisionRecordResult::Recorded); CHECK(operating.pendingDecisionPeriod == 4); CHECK(!operating.lastProcessedPeriod); CHECK(operating.coverageBasisPoints == 10000); CHECK(operating.consecutiveDistressMonths == 0); CHECK(events.view().size() == 1); const auto* required = std::get_if( &events.view()[0].payload); const sim::CriticalOperatingBudgetDecisionRequired expected{ 4, 4, 0, 0, 10, 4, 4000}; CHECK(required && *required == expected); const sim::OperatingBudgetState recorded = operating; events.begin_batch(100); CHECK(sim::record_monthly_finance_critical_decision( operating, paused, &events) == sim::MonthlyFinanceDecisionRecordResult::StaleQuote); CHECK(operating == recorded && events.view().empty()); } // A monthly debt shortfall persists an offer without committing revenue, carries, or instruments. { std::array records{}; records[0].rate = 75; records[0].value = 120; City city; city.set_funds(174); sim::MunicipalDebt debt = due_debt(); sim::OperatingBudgetState operating; const sim::MunicipalDebt debtBefore = debt; const auto shortfall = sim::quote_monthly_finance( records, operating, debt, 1, city.funds()); CHECK(shortfall.status == sim::MonthlyFinanceQuoteStatus::InsufficientForDebt); sim::OperatingForecastInput forecast; forecast.currentMonth = 1; sim::EventBuffer events; events.begin_batch(25); CHECK(sim::record_monthly_finance_support_offer(city, debt, operating, records, shortfall, forecast, &events) == sim::MonthlyFinanceSupportOfferResult::Offered); CHECK(city.funds() == 174 && !operating.lastProcessedPeriod); CHECK(debt.instruments == debtBefore.instruments && !debt.lastProcessedPeriod && debt.support.pending); const sim::PendingBailout expectedPending{1, 185, 174, 10000, 10001, sim::BailoutContext::MonthlyFinance, 10}; CHECK(debt.support.pending == std::optional{expectedPending}); CHECK(events.view().size() == 2); const auto* defaulted = std::get_if(&events.view()[0].payload); const auto* offered = std::get_if(&events.view()[1].payload); const sim::DebtDefaultDetected expectedDefault{1, 185, 174}; const sim::GovernmentSupportOffered expectedOffer{ 1, 185, 174, 10000, 10001}; CHECK(defaulted && *defaulted == expectedDefault); CHECK(offered && *offered == expectedOffer); const auto encoded = sim::validate_municipal_debt(debt) == sim::MunicipalDebtValidationError::None ? io::encode_native_finance(debt) : std::nullopt; CHECK(encoded && io::decode_native_finance(*encoded) == debt); const sim::MunicipalDebt offeredDebt = debt; events.begin_batch(25); CHECK(sim::record_monthly_finance_support_offer(city, debt, operating, records, shortfall, forecast, &events) == sim::MonthlyFinanceSupportOfferResult::InvalidState); CHECK(debt == offeredDebt && events.view().empty()); } // A changed treasury makes the support proposal stale without creating a decision. { std::array records{}; records[0].rate = 75; records[0].value = 120; City city; city.set_funds(174); sim::MunicipalDebt debt = due_debt(); sim::OperatingBudgetState operating; const auto shortfall = sim::quote_monthly_finance( records, operating, debt, 1, city.funds()); city.set_funds(173); sim::OperatingForecastInput forecast; forecast.currentMonth = 1; CHECK(sim::record_monthly_finance_support_offer(city, debt, operating, records, shortfall, forecast) == sim::MonthlyFinanceSupportOfferResult::StaleQuote); CHECK(!debt.support.pending && !debt.lastProcessedPeriod && !operating.lastProcessedPeriod); } // Accepted support commits the previously uncommitted revenue exactly once across save/reload. { std::array records{}; records[0].rate = 75; records[0].value = 120; City city; city.set_funds(174); sim::MunicipalDebt debt = due_debt(); sim::OperatingBudgetState operating; const auto shortfall = sim::quote_monthly_finance( records, operating, debt, 1, city.funds()); sim::OperatingForecastInput forecast; forecast.currentMonth = 1; CHECK(sim::record_monthly_finance_support_offer(city, debt, operating, records, shortfall, forecast) == sim::MonthlyFinanceSupportOfferResult::Offered); const auto encoded = io::encode_native_finance(debt); const auto decoded = encoded ? io::decode_native_finance(*encoded) : std::nullopt; CHECK(decoded.has_value()); if (decoded) debt = *decoded; sim::EventBuffer events; events.begin_batch(25); CHECK(sim::accept_monthly_finance_support( city, debt, operating, records, 1, false, &events) == sim::MonthlyFinanceSupportCommandResult::Committed); CHECK(city.funds() == 10000); CHECK(debt.lastProcessedPeriod == 1 && !debt.support.pending); CHECK(debt.support.status == sim::FiscalStatus::GovernmentSupervision); CHECK(debt.support.lastBailoutPeriod == 1 && debt.support.bailoutEligibleAgainPeriod == 61 && debt.support.lastBailoutAmount == 10001); CHECK(debt.instruments[0].remainingPrincipal == 9848); CHECK(operating.lastProcessedPeriod == 1 && operating.coverageBasisPoints == 10000); CHECK(events.view().size() == 3); CHECK(std::get_if(&events.view()[0].payload)); const auto* settled = std::get_if( &events.view()[1].payload); const auto* accepted = std::get_if( &events.view()[2].payload); CHECK(settled && settled->revenueReceived == 10 && settled->fundsAfter == 10000); CHECK(accepted && accepted->injection == 10001 && accepted->treasuryAfterPayment == 10000); } // Support and Critical cuts remain two explicit decisions but commit as one transaction. { std::array records{}; records[5].rate = 12; records[5].value = 30000; City city; city.set_funds(0); sim::MunicipalDebt debt = due_debt(); sim::OperatingBudgetState operating; const auto shortfall = sim::quote_monthly_finance( records, operating, debt, 1, city.funds()); sim::OperatingForecastInput forecast; forecast.currentMonth = 1; CHECK(sim::record_monthly_finance_support_offer(city, debt, operating, records, shortfall, forecast) == sim::MonthlyFinanceSupportOfferResult::Offered); sim::EventBuffer events; events.begin_batch(25); CHECK(sim::accept_monthly_finance_support( city, debt, operating, records, 1, false, &events) == sim::MonthlyFinanceSupportCommandResult::AwaitingCriticalDecision); CHECK(city.funds() == 0 && debt.support.pending && operating.pendingDecisionPeriod == 1); CHECK(events.view().size() == 1); CHECK(std::get_if( &events.view()[0].payload)); events.begin_batch(25); CHECK(sim::accept_monthly_finance_support( city, debt, operating, records, 1, true, &events) == sim::MonthlyFinanceSupportCommandResult::Committed); CHECK(city.funds() == 0 && !debt.support.pending && debt.support.status == sim::FiscalStatus::GovernmentSupervision); CHECK(operating.lastProcessedPeriod == 1 && !operating.pendingDecisionPeriod && operating.coverageBasisPoints == 3333 && operating.consecutiveDistressMonths == 1); CHECK(events.view().size() == 3); } // A second default during active supervision dismisses without settling any part of the month. { const std::array records{}; sim::MunicipalDebt debt = supervised_debt_due_at(59); const sim::MunicipalDebt before = debt; sim::OperatingBudgetState operating; const auto quote = sim::quote_monthly_finance(records, operating, debt, 59, 0); CHECK(quote.status == sim::MonthlyFinanceQuoteStatus::DismissalRequired); CHECK(quote.quote && !quote.quote->supervisionEnds); sim::EventBuffer events; events.begin_batch(1475); CHECK(sim::commit_monthly_finance_dismissal( debt, operating, records, 0, quote, &events) == sim::MonthlyFinanceDismissalCommitResult::Dismissed); CHECK(debt.instruments == before.instruments && !debt.lastProcessedPeriod && !operating.lastProcessedPeriod); CHECK(debt.support.status == sim::FiscalStatus::Dismissed && debt.support.dismissalReason == sim::DismissalReason::RepeatedDebtDefault); CHECK(events.view().size() == 2); CHECK(std::get_if(&events.view()[0].payload)); CHECK(std::get_if(&events.view()[1].payload)); } // Expired supervision ends before a payable boundary and before a newly eligible support offer. { const std::array records{}; sim::MunicipalDebt payableDebt = supervised_debt_due_at(60); sim::OperatingBudgetState payableOperating; City payableCity; payableCity.set_funds(185); const auto payable = sim::quote_monthly_finance(records, payableOperating, payableDebt, 60, payableCity.funds()); CHECK(payable.status == sim::MonthlyFinanceQuoteStatus::Ready); CHECK(payable.quote && payable.quote->supervisionEnds); sim::EventBuffer events; events.begin_batch(1500); if (payable.quote) { CHECK(sim::commit_monthly_finance(payableCity, payableDebt, payableOperating, records, *payable.quote, &events) == sim::MonthlyFinanceCommitResult::Committed); } CHECK(payableDebt.support.status == sim::FiscalStatus::Normal); CHECK(events.view().size() == 3); CHECK(std::get_if( &events.view()[0].payload)); CHECK(std::get_if(&events.view()[1].payload)); CHECK(std::get_if( &events.view()[2].payload)); sim::MunicipalDebt defaultingDebt = supervised_debt_due_at(60); sim::OperatingBudgetState defaultingOperating; City defaultingCity; defaultingCity.set_funds(0); const auto defaulting = sim::quote_monthly_finance(records, defaultingOperating, defaultingDebt, 60, defaultingCity.funds()); CHECK(defaulting.status == sim::MonthlyFinanceQuoteStatus::InsufficientForDebt); CHECK(defaulting.quote && defaulting.quote->supervisionEnds); sim::OperatingForecastInput forecast; forecast.currentMonth = 0; events.begin_batch(1500); CHECK(sim::record_monthly_finance_support_offer(defaultingCity, defaultingDebt, defaultingOperating, records, defaulting, forecast, &events) == sim::MonthlyFinanceSupportOfferResult::Offered); CHECK(defaultingDebt.support.status == sim::FiscalStatus::Normal && defaultingDebt.support.pending); CHECK(events.view().size() == 3); CHECK(std::get_if( &events.view()[0].payload)); CHECK(std::get_if(&events.view()[1].payload)); CHECK(std::get_if( &events.view()[2].payload)); } if (failures == 0) std::printf("monthly_finance: all checks passed\n"); else std::printf("monthly_finance: %d FAILED\n", failures); return failures ? 1 : 0; }