diff --git a/README.md b/README.md index 9c217fe2..fe23d4ff 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,20 @@ The comparator signature match is syntactic; elaborated type equivalence require rechecks the archive offline. This tests source integrity and claim fidelity; it is not a mathematical referee report or a substitute for a full Lean rebuild. +## Cryptomania and bounded agency (research draft) + +The [FAW-01 finite agency witness](paper/agency_without_cryptomania.md), +[FAW-02 persistence and regret proofs](paper/agency_persistence.md), and +[FAW-03 unknown-reliability Bayesian experiment design](paper/agency_unknown_reliability.md) +study resource-bounded decision-making without cryptographic hardness premises. +FAW-03 distinguishes one-label nonidentifiability from two-label channel +identification and derives a finite-horizon adaptive stopping policy that +improves reward by conserving calibration labels. These are synthetic exact +probability and paper arguments, without empirical model runs, Lean proofs or +conclusions about theological claims. +The associated [draft PR #16](https://github.com/MoralityLabAI/EvalMath/pull/16) +remains open for review. + ## License Apache License 2.0; see [`LICENSE`](LICENSE). diff --git a/output/agency_persistence/persistence_v1.json b/output/agency_persistence/persistence_v1.json new file mode 100644 index 00000000..598c80a7 --- /dev/null +++ b/output/agency_persistence/persistence_v1.json @@ -0,0 +1,323 @@ +{ + "generated_at_utc": "2026-10-27T05:55:04.544266+00:00", + "schema_version": "1.0", + "mechanism": "fresh_uniform_polarity_each_epoch; sealed_heldout_feedback", + "signal_reliability": "3/4", + "label_cost": "1/32", + "fixed_schedule": "m_t=5*bit_length(t)", + "heldout_schedule": "n_t=t+1", + "five_label_cher_bound_squared": "243/1024", + "finite_horizon_reports": [ + { + "horizon": 1, + "heldout_trials": 2, + "scheduled_calibration_labels": 5, + "label_upper_bound": 5, + "schedule_oracle_regret": "53/512", + "schedule_avg_oracle_regret": "53/1024", + "schedule_regret_bound_per_trial": "1/4", + "schedule_net_gain_over_chance": "123/512", + "schedule_net_gain_per_trial": "123/1024", + "optimized_calibration_labels": 3, + "optimized_oracle_regret": "5/32", + "optimized_avg_oracle_regret": "5/64", + "optimized_regret_bound_per_trial": "21/64", + "optimized_net_gain_over_chance": "1/4", + "optimized_net_gain_per_trial": "1/8", + "certificates": { + "stage_certificates": true, + "optimizer_certificates": true, + "heldout_count": true, + "labels_at_most_5Tlog": true, + "cumulative_regret_at_most_T_over_2": true, + "average_regret_at_most_inverse_horizon": true, + "baseline_gain_identity": true, + "normalized_net_lower_bound": true, + "optimal_net_dominates_schedule": true, + "optimal_regret_bound": true, + "optimal_average_regret_bound": true, + "schedule_positive_net": true, + "optimized_positive_net": true + } + }, + { + "horizon": 2, + "heldout_trials": 5, + "scheduled_calibration_labels": 15, + "label_upper_bound": 20, + "schedule_oracle_regret": "46375/262144", + "schedule_avg_oracle_regret": "9275/262144", + "schedule_regret_bound_per_trial": "1/5", + "schedule_net_gain_over_chance": "158425/262144", + "schedule_net_gain_per_trial": "31685/262144", + "optimized_calibration_labels": 8, + "optimized_oracle_regret": "319/1024", + "optimized_avg_oracle_regret": "319/5120", + "optimized_regret_bound_per_trial": "13/40", + "optimized_net_gain_over_chance": "705/1024", + "optimized_net_gain_per_trial": "141/1024", + "certificates": { + "stage_certificates": true, + "optimizer_certificates": true, + "heldout_count": true, + "labels_at_most_5Tlog": true, + "cumulative_regret_at_most_T_over_2": true, + "average_regret_at_most_inverse_horizon": true, + "baseline_gain_identity": true, + "normalized_net_lower_bound": true, + "optimal_net_dominates_schedule": true, + "optimal_regret_bound": true, + "optimal_average_regret_bound": true, + "schedule_positive_net": true, + "optimized_positive_net": true + } + }, + { + "horizon": 4, + "heldout_trials": 14, + "scheduled_calibration_labels": 40, + "label_upper_bound": 60, + "schedule_oracle_regret": "85365373/268435456", + "schedule_avg_oracle_regret": "85365373/3758096384", + "schedule_regret_bound_per_trial": "1/7", + "schedule_net_gain_over_chance": "518614403/268435456", + "schedule_net_gain_per_trial": "518614403/3758096384", + "optimized_calibration_labels": 22, + "optimized_oracle_regret": "5153/8192", + "optimized_avg_oracle_regret": "5153/114688", + "optimized_regret_bound_per_trial": "31/112", + "optimized_net_gain_over_chance": "17887/8192", + "optimized_net_gain_per_trial": "17887/114688", + "certificates": { + "stage_certificates": true, + "optimizer_certificates": true, + "heldout_count": true, + "labels_at_most_5Tlog": true, + "cumulative_regret_at_most_T_over_2": true, + "average_regret_at_most_inverse_horizon": true, + "baseline_gain_identity": true, + "normalized_net_lower_bound": true, + "optimal_net_dominates_schedule": true, + "optimal_regret_bound": true, + "optimal_average_regret_bound": true, + "schedule_positive_net": true, + "optimized_positive_net": true + } + }, + { + "horizon": 8, + "heldout_trials": 44, + "scheduled_calibration_labels": 105, + "label_upper_bound": 160, + "schedule_oracle_regret": "74179081871/137438953472", + "schedule_avg_oracle_regret": "74179081871/6047313952768", + "schedule_regret_bound_per_trial": "1/11", + "schedule_net_gain_over_chance": "986677840241/137438953472", + "schedule_net_gain_per_trial": "986677840241/6047313952768", + "optimized_calibration_labels": 60, + "optimized_oracle_regret": "2720507/2097152", + "optimized_avg_oracle_regret": "2720507/92274688", + "optimized_regret_bound_per_trial": "9/44", + "optimized_net_gain_over_chance": "16416005/2097152", + "optimized_net_gain_per_trial": "16416005/92274688", + "certificates": { + "stage_certificates": true, + "optimizer_certificates": true, + "heldout_count": true, + "labels_at_most_5Tlog": true, + "cumulative_regret_at_most_T_over_2": true, + "average_regret_at_most_inverse_horizon": true, + "baseline_gain_identity": true, + "normalized_net_lower_bound": true, + "optimal_net_dominates_schedule": true, + "optimal_regret_bound": true, + "optimal_average_regret_bound": true, + "schedule_positive_net": true, + "optimized_positive_net": true + } + }, + { + "horizon": 16, + "heldout_trials": 152, + "scheduled_calibration_labels": 270, + "label_upper_bound": 400, + "schedule_oracle_regret": "548015945261849/562949953421312", + "schedule_avg_oracle_regret": "548015945261849/85568392920039424", + "schedule_regret_bound_per_trial": "1/19", + "schedule_net_gain_over_chance": "16094192052755687/562949953421312", + "schedule_net_gain_per_trial": "16094192052755687/85568392920039424", + "optimized_calibration_labels": 158, + "optimized_oracle_regret": "93097547/33554432", + "optimized_avg_oracle_regret": "93097547/5100273664", + "optimized_regret_bound_per_trial": "41/304", + "optimized_net_gain_over_chance": "1016295861/33554432", + "optimized_net_gain_per_trial": "1016295861/5100273664", + "certificates": { + "stage_certificates": true, + "optimizer_certificates": true, + "heldout_count": true, + "labels_at_most_5Tlog": true, + "cumulative_regret_at_most_T_over_2": true, + "average_regret_at_most_inverse_horizon": true, + "baseline_gain_identity": true, + "normalized_net_lower_bound": true, + "optimal_net_dominates_schedule": true, + "optimal_regret_bound": true, + "optimal_average_regret_bound": true, + "schedule_positive_net": true, + "optimized_positive_net": true + } + }, + { + "horizon": 32, + "heldout_trials": 560, + "scheduled_calibration_labels": 675, + "label_upper_bound": 960, + "schedule_oracle_regret": "117804885426777433/72057594037927936", + "schedule_avg_oracle_regret": "117804885426777433/40352252661239644160", + "schedule_regret_bound_per_trial": "1/35", + "schedule_net_gain_over_chance": "8450293405645591207/72057594037927936", + "schedule_net_gain_per_trial": "8450293405645591207/40352252661239644160", + "optimized_calibration_labels": 414, + "optimized_oracle_regret": "24583160911/4294967296", + "optimized_avg_oracle_regret": "24583160911/2405181685760", + "optimized_regret_bound_per_trial": "23/280", + "optimized_net_gain_over_chance": "521146121137/4294967296", + "optimized_net_gain_per_trial": "521146121137/2405181685760", + "certificates": { + "stage_certificates": true, + "optimizer_certificates": true, + "heldout_count": true, + "labels_at_most_5Tlog": true, + "cumulative_regret_at_most_T_over_2": true, + "average_regret_at_most_inverse_horizon": true, + "baseline_gain_identity": true, + "normalized_net_lower_bound": true, + "optimal_net_dominates_schedule": true, + "optimal_regret_bound": true, + "optimal_average_regret_bound": true, + "schedule_positive_net": true, + "optimized_positive_net": true + } + }, + { + "horizon": 64, + "heldout_trials": 2144, + "scheduled_calibration_labels": 1640, + "label_upper_bound": 2240, + "schedule_oracle_regret": "1778341719620366629487/590295810358705651712", + "schedule_avg_oracle_regret": "1778341719620366629487/1265594217409064917270528", + "schedule_regret_bound_per_trial": "1/67", + "schedule_net_gain_over_chance": "284367552351762198037905/590295810358705651712", + "schedule_net_gain_per_trial": "284367552351762198037905/1265594217409064917270528", + "optimized_calibration_labels": 1048, + "optimized_oracle_regret": "12992021482201/1099511627776", + "optimized_avg_oracle_regret": "12992021482201/2357352929951744", + "optimized_regret_bound_per_trial": "51/1072", + "optimized_net_gain_over_chance": "540337205196071/1099511627776", + "optimized_net_gain_per_trial": "540337205196071/2357352929951744", + "certificates": { + "stage_certificates": true, + "optimizer_certificates": true, + "heldout_count": true, + "labels_at_most_5Tlog": true, + "cumulative_regret_at_most_T_over_2": true, + "average_regret_at_most_inverse_horizon": true, + "baseline_gain_identity": true, + "normalized_net_lower_bound": true, + "optimal_net_dominates_schedule": true, + "optimal_regret_bound": true, + "optimal_average_regret_bound": true, + "schedule_positive_net": true, + "optimized_positive_net": true + } + } + ], + "fixed_budget_lower_bound_controls": [ + [ + "2/3", + 0, + "1/6" + ], + [ + "2/3", + 1, + "1/9" + ], + [ + "2/3", + 3, + "1/81" + ], + [ + "2/3", + 8, + "1/19683" + ], + [ + "3/4", + 0, + "1/4" + ], + [ + "3/4", + 1, + "1/8" + ], + [ + "3/4", + 3, + "1/128" + ], + [ + "3/4", + 8, + "1/131072" + ], + [ + "4/5", + 0, + "3/10" + ], + [ + "4/5", + 1, + "3/25" + ], + [ + "4/5", + 3, + "3/625" + ], + [ + "4/5", + 8, + "3/1953125" + ] + ], + "checks": { + "stage_certificates": true, + "horizon_certificates": true, + "first_budget_five": true, + "power_of_two_boundary_budgets": true, + "first_epoch_exact_accuracy": true, + "every_tested_epoch_positive_net": true, + "optimized_nets_dominate": true, + "finite_fixed_budget_regret_floor": true, + "fresh_polarity_prevents_cross_epoch_transfer": true, + "shared_polarity_allows_transfer": true, + "uninformative_signal_negative_control": true + }, + "all_passed": true, + "evidence_level": "algebraic_argument_plus_finite_exact_tests", + "theological_hypothesis_identified": false, + "public_key_cryptography_assumed": false, + "empirical_agents_evaluated": false, + "lean_formalized": false, + "source_sha256": { + "src/spiral_ln/agency_persistence.py": "f460122e0bc70f1f14433db4d67793be4720c4e04f0de8161a4e4123cef57efe", + "tests/test_agency_persistence.py": "e12b8eaa5e03335d79906a0a0bc02a03bfd60776785f102894520be597010ed0", + "scripts/verify_agency_persistence.py": "2f27fa4e64f4192e98907a924577172760a373c62619c3dcf38eced7ed2a40ee", + "paper/agency_persistence.md": "9bf7d223d070d351c0c03dbf644a49ebe7c6cdbf5c456b24872ef9d758f5a76b" + } +} diff --git a/output/agency_unknown/unknown_v1.json b/output/agency_unknown/unknown_v1.json new file mode 100644 index 00000000..e3ea7126 --- /dev/null +++ b/output/agency_unknown/unknown_v1.json @@ -0,0 +1,112 @@ +{ + "generated_at_utc": "2026-10-27T06:36:43.149400+00:00", + "schema_version": "1.0", + "mechanism": "q_shared_across_epochs; fresh_uniform_theta; sealed_heldout_feedback", + "prior": [ + [ + "1/2", + "1/2" + ], + [ + "1", + "1/2" + ] + ], + "posterior_after_one_label": [ + [ + "1/2", + "1/2" + ], + [ + "1", + "1/2" + ] + ], + "posterior_after_agree": [ + [ + "1/2", + "1/3" + ], + [ + "1", + "2/3" + ] + ], + "posterior_after_disagree": [ + [ + "1/2", + "1" + ], + [ + "1", + "0" + ] + ], + "same_pair_probability": "3/4", + "single_label_epoch_value": "1/2", + "adaptive_epoch_result": { + "epochs": 13, + "heldout_trials": 72, + "value_over_chance": "7", + "first_action": "buy", + "first_stop_value": "6", + "first_buy_value": "7", + "expected_gold_labels": "11", + "expected_heldout_correct": "54", + "expected_oracle_correct": "54", + "expected_oracle_regret": "0", + "expected_label_cost": "11", + "value_identity": true, + "policy_states": 114 + }, + "pair_identification": [ + [ + 1, + "1/2" + ], + [ + 2, + "3/4" + ], + [ + 4, + "15/16" + ], + [ + 8, + "247/256" + ], + [ + 16, + "64839/65536" + ] + ], + "checks": { + "one_label_q_uninformative": true, + "two_label_same_event_probability": true, + "same_pair_updates_q": true, + "different_pair_identifies_noisy_channel": true, + "one_label_accuracy": true, + "fixed_one_label_net": true, + "global_optimal_first_action_buy": true, + "forward_utility_identity": true, + "expected_global_gain_is_seven": true, + "no_early_experiment_gain_six": true, + "gold_label_budget_bounded": true, + "oracle_gap_nonnegative": true, + "separated_rates_identifiable": true, + "exact_identification_converges_in_fixture": true + }, + "all_passed": true, + "evidence_level": "algebraic_proof_and_finite_exact_bayes_planning", + "real_agent_evidence": false, + "cryptographic_world_identified": false, + "theological_hypothesis_identified": false, + "lean_formalized": false, + "source_sha256": { + "src/spiral_ln/agency_unknown.py": "c9413b626a075f6f2657fb5c96db4c601f893425650d529a3edbd7462714e057", + "tests/test_agency_unknown.py": "5c970eae121520e795b86688be81cded994f5fb8aea88fe2e13e98fdfb1c71cb", + "scripts/verify_agency_unknown.py": "6cd28c21f289e2df9760334b05a1a3078e45cf24738d64d0072b219fddb5c761", + "paper/agency_unknown_reliability.md": "420243562fa438e951c686654684af40a77e741fdb24f583130937dc06714231" + } +} diff --git a/output/agency_worlds/agency_v1.json b/output/agency_worlds/agency_v1.json new file mode 100644 index 00000000..f4bd1924 --- /dev/null +++ b/output/agency_worlds/agency_v1.json @@ -0,0 +1,69 @@ +{ + "schema_version": "1.0", + "generated_at_utc": "2026-10-27T05:16:54.795508+00:00", + "channel_accuracy": "3/4", + "hidden_polarity_prior": [ + "1/2", + "1/2" + ], + "sample_counts": [ + 0, + 1, + 2, + 3, + 4, + 5 + ], + "heldout_success": [ + "1/2", + "5/8", + "5/8", + "43/64", + "43/64", + "715/1024" + ], + "unlimited_calibration_oracle_accuracy": "3/4", + "memorized_training_label_score": "1", + "training_vs_heldout_gap_at_one_label": "3/8", + "plan": { + "max_samples": 5, + "label_cost": "1/32", + "value_by_samples": [ + "1/2", + "19/32", + "9/16", + "37/64", + "35/64", + "555/1024" + ], + "optimal_value": "19/32", + "optimal_sample_counts": [ + 1 + ] + }, + "checks": { + "formula_matches_enumeration": true, + "no_feedback_is_chance": true, + "one_label_improves_heldout": true, + "three_labels_improve_further": true, + "even_tie_matches_previous_odd": true, + "uninformative_channel_stays_chance": true, + "perfect_channel_after_one_label": true, + "success_bounded_by_oracle": true, + "reused_label_score_exceeds_heldout": true, + "finite_plan_favors_one_label": true, + "one_label_net_value": true, + "finite_learning_gap_is_positive": true + }, + "all_passed": true, + "evidence_level": "algebraic_identity_and_finite_verified_example", + "real_agent_evidence": false, + "cryptographic_world_identified": false, + "theological_hypothesis_identified": false, + "source_sha256": { + "src/spiral_ln/agency_worlds.py": "f372da6e25335147dc991664e6dddbe59f10048452c41c1f15c6a13e7ba6abb7", + "tests/test_agency_worlds.py": "f9695762f7967ed402541915c105dac7b9b71c30ec6134411b18e0b45e3bafb2", + "scripts/verify_agency_worlds.py": "efc27440a8924877908cd466648eb42ad0bcac2ea62555a7370ca8a60a52e2ac", + "paper/agency_without_cryptomania.md": "e46d22e50a775d85ddf3d7677c65af390d8588ce164e3229718f71fbd7d015b8" + } +} diff --git a/paper/agency_persistence.md b/paper/agency_persistence.md new file mode 100644 index 00000000..69e6015e --- /dev/null +++ b/paper/agency_persistence.md @@ -0,0 +1,137 @@ +# FAW-02: persistent bounded agency in every hypothetical cryptographic world + +**Draft 0.1, 2026-10-27.** Follow-up to [FAW-01](agency_without_cryptomania.md). This note concerns an *operational* definition of agency: useful information acquisition, choice under a declared budget, repeated fresh challenges and independent scoring. It makes no claim to detect consciousness, moral agency or divine intention. Its complexity-world statement is a **conditional independence argument**, not a proof that all five worlds are consistent or that our universe belongs to one of them. + +## 1. Protocol and information boundaries + +At epoch \(t\ge 1\), independently sample a uniformly random polarity \(\theta_t\in\{0,1\}\). For each calibration or test item, sample an independent uniform state \(s\), a noise bit \(e\) with \(P(e=0)=q=3/4\), and show the signal \(y=s\oplus\theta_t\oplus e\). Calibration supplies the true state \(s\); held-out testing reveals only \(y\) before a prediction. Correct predictions earn unit reward. **Test labels, correctness, rewards and all other grader feedback are sealed until the epoch is complete.** The epoch's polarity is freshly sampled, so past-epoch calibration has no predictive advantage on the new polarity. + +Let \(n_t=t+1\) denote the number of independent held-out decisions. The **sufficient fixed schedule** buys + +\[ +m_t=5b_t,\qquad b_t=\lceil\log_2(t+1)\rceil=\operatorname{bit\_length}(t),\] + +labeled calibration examples, each costing \(c=1/32\) reward units. The agent infers \(\theta_t\) by a majority vote over the observed calibration polarities \(s_i\oplus y_i\) (ties select 0), and predicts \(\hat s_j=y_j\oplus\hat\theta_t\) for each held-out item. The environment and success law are known; the *fresh* polarity and trial noises are not. + +An agent with no current-epoch labels has success probability \(1/2\) on every test prediction despite its full earlier history. A polarity-informed oracle attains \(3/4\). Let \(A_m(q)\) denote the exact fresh-test success from FAW-01, and let \(p_m=1-\alpha_m(q)\) be the polarity inference error. For \(q=3/4\), + +\[A_m(3/4)=3/4-\tfrac12p_m,\qquad r_m=3/4-A_m(3/4)=\tfrac12p_m.\] + +**Information caveat.** Exposing any test reward during the epoch changes the game and may let the agent learn the polarity after testing starts. Keeping a fixed polarity across epochs similarly makes past labels informative. Both changes invalidate the stated chance baseline. This is the same distinction between player-facing feedback and post-play measurement emphasized in the parent EvalMath testbed. + +## 2. The logarithmic-label theorem + +**Theorem FAW-02/A (algebraic proof, not Lean formalized).** In the stated protocol, the scheduled agent's expected cumulative oracle regret \(R_T\) and total calibration labels \(L_T\) through epoch \(T\ge1\) obey + +\[ +R_T\le T/2,\qquad L_T\le5T\lceil\log_2(T+1)\rceil. +\] + +There are exactly \(D_T=\sum_{t=1}^T(t+1)=T(T+3)/2\) held-out decisions. Consequently, + +\[ +\boxed{\frac{R_T}{D_T}\le\frac1{T+3}},\qquad +\boxed{\frac{L_T}{D_T}\le\frac{10\lceil\log_2(T+1)\rceil}{T+3}}. +\] + +Both right-hand sides tend to zero. The error guarantee is population-expectation regret under the declared stochastic law, with independent *epoch* polarities and feedback sealing. It is neither pathwise regret nor a high-probability concentration theorem for the realized trajectory. + +*Proof.* If \(K\) of \(m\) calibration bits are correctly polarized, then \(K\sim\mathrm{Binomial}(m,3/4)\). An erroneous majority requires \(K\le m/2\), including the possibility of an even-size tie. Markov's inequality applied to \(3^{-K}\) gives + +\[ +\begin{aligned} +p_m&\le P(K\le m/2)\\ +&\le 3^{m/2}\,\mathbb E[3^{-K}]\\ +&=3^{m/2}\left(\tfrac34\cdot\tfrac13+\tfrac14\right)^m\\ +&=\left(\tfrac{\sqrt3}{2}\right)^m. +\end{aligned} +\] + +The last expression is bounded using only an integer certificate: + +\[ +\left(\tfrac34\right)^5=\frac{243}{1024}\le\frac14. +\] + +For \(m=m_t=5b_t\), squaring the upper bound yields \(p_{m_t}^2\le(243/1024)^{b_t}\le(1/4)^{b_t}\). Thus \(p_{m_t}\le2^{-b_t}\le1/(t+1)\). Each epoch's regret is at most \((t+1)\cdot p_{m_t}/2\le1/2\). Summing gives \(R_T\le T/2\). The budget bound follows from monotonicity of integer bit length. Dividing by the exact \(D_T\) gives both displayed normalized inequalities. \(\square\) + +### Reward after calibration expense + +Define the net gain over the uncalibrated chance policy by + +\[G_T=\sum_{t=1}^T n_t\big(A_{m_t}(3/4)-1/2\big)-cL_T.\] + +Because \(G_T=D_T/4-R_T-cL_T\), the theorem yields + +\[ +\frac{G_T}{D_T}\ge\frac14-\frac1{T+3}-\frac{10c\lceil\log_2(T+1)\rceil}{T+3},\quad +\lim_{T\to\infty}\frac{G_T}{D_T}=\frac14. +\] + +The upper limit follows from the oracle's accuracy ceiling and nonnegative label cost. The calibration fraction and its normalized cost vanish while the per-test net gain over the chance policy approaches a positive constant. + +**Proposition FAW-02/B (positive net gain every epoch).** At the specified \(c=1/32\), even each *individual* epoch has strictly positive expected net gain over chance. The epoch-level lower bound is + +\[g_t\ge\frac{8(t-1)-5b_t}{32}.\] + +For \(t\ge3\) this lower bound is positive: the integer numerator equals 6 at \(t=3\), and each increment in \(t\) raises it by \(8-5(b_{t+1}-b_t)\ge3\). The two exceptions, \(t=1,2\), have exact positive net gains \(123/512\) and \(95449/262144\), verified by finite binomial sums. The proof is valid for all positive integers \(t\), while the computer enumerates only finitely many examples. + +## 3. A bounded agent that chooses its calibration budget + +A second agent solves the exact finite planning problem + +\[ +m_t^*\in\operatorname*{argmax}_{0\le m\le m_t} +\big[n_t\big(A_m(3/4)-\tfrac12\big)-cm\big]. +\] + +In a tie, it selects the smallest number of labels. This is an agent choosing its *evaluation acquisition budget* under a stated utility function, with the stochastic law supplied in advance. It is not autonomous task discovery, training-weight editing, or evidence of actual RSI. + +**Theorem FAW-02/C (cost-optimized agent).** Let \(R_T^*\) be this agent's cumulative expected oracle regret. For each epoch, comparing the chosen policy against the feasible scheduled policy gives + +\[n_t r_{m_t^*}+cm_t^*\le n_t r_{m_t}+cm_t\le\tfrac12+cm_t.\] + +Since costs are nonnegative, summing yields + +\[ +\boxed{\frac{R_T^*}{D_T}\le\frac1{T+3}+\frac{10c\lceil\log_2(T+1)\rceil}{T+3}\longrightarrow0.} +\] + +Its expected net value is at least the fixed schedule's value at *every epoch* by construction, so Proposition B gives a strictly positive epoch-level net advantage for the specified cost. The planner's exact finite search requires at most \(m_t+1\) candidate budgets and rational binomial calculations; the theorem charges for purchased labels, and it leaves planning computation outside the reward accounting. + +## 4. A fixed acquisition cap prevents vanishing regret + +**Theorem FAW-02/D (nonadaptive within-epoch lower bound).** Let \(q\in(1/2,1)\) be fixed and rational. Suppose every epoch starts with a fresh fair polarity, the number of calibration labels \(m_t\le M\) is chosen before seeing that epoch's calibration data, and rewards stay sealed. Any polarity inference rule based on those labels has oracle gap at least + +\[ +\boxed{\epsilon(q,M)=(2q-1)\min\{\tfrac12,(1-q)^M\}>0.} +\] + +*Proof.* For \(m=0\), the Bayes error in the fair hidden polarity is \(1/2\). For \(m\ge1\), majority is Bayes-optimal in the symmetric binary channel. The event that *every* observed calibration polarity is flipped has probability \((1-q)^m\), and majority chooses the wrong polarity on that event. Thus its Bayes error is at least \((1-q)^m\ge(1-q)^M\). Any competing decoder has Bayes error at least that of majority. The held-out correctness gap against an informed oracle is \((2q-1)\) times polarity error. Past epochs are independent of the fresh polarity, so choosing a sample count using old-epoch information leaves the bound intact. \(\square\) + +The lower bound quantifies an **acquisition lower bound under a fixed label cap**. Adaptive stopping based on current-epoch labels, a changed observation process, long-lived polarity, and revealed test rewards need independent analysis. It is a statement about statistical information and bounded decisions; it does not imply NP hardness, one-way functions or public-key encryption. + +## 5. Evidence ledger and falsifiers + +| Claim | Evidence level | Boundary | +|---|---|---| +| FAW-02/A: vanishing expected regret with logarithmic labels | Algebraic proof above; finite exact fixture | Assumes refreshed polarity and sealed rewards | +| FAW-02/B: positive net reward in each epoch | Algebraic inequality + exact first two cases | Specific \(q=3/4\), \(c=1/32\), \(n_t=t+1\) | +| FAW-02/C: cost-optimized budget retains a vanishing regret bound | Algebraic comparison + exact finite optimizer | Optimizer knows the reward law and has restricted choices | +| FAW-02/D: fixed nonadaptive label cap incurs positive regret | Algebraic lower bound + exact controls | Within-epoch adaptive sampling outside this proof | +| Model survives Algorithmica, Heuristica, Pessiland, Minicrypt and Cryptomania as a conditional toy construction | Independence from cryptographic assumptions | Does not establish the consistency or truth of any world | +| Any implication from persistent *functional* progress to divine enjoyment of struggle | Philosophical bridge axiom | No mathematical or observational proof supplied | + +Three pre-registered failure checks alter the protocol. Under \(q=1/2\), calibration yields no population advantage. If \(\theta_{t+1}=\theta_t\), information from a previous epoch transfers, changing the no-current-calibration baseline. If held-out success or labels are leaked during the epoch, the observation channel changes and the original expectation formula needs revision. The verifier checks the first two with exact rational controls; the last is excluded by the declared protocol. + +The five-world context follows [Impagliazzo's interview](https://www.quantamagazine.org/the-researcher-who-explores-computation-by-conjuring-new-worlds-20240327/) and the definitions in [the Sorbonne quantum information explainer](https://qics.sorbonne-universite.fr/en/impact-quantum-computers-impagliazzos-five-worlds). The separate hierarchy result \(P\subsetneq EXP\) used in FAW-01 is explained in [UIC lecture notes](https://www.cs.uic.edu/~block/courses/cs505-spring2025/lecture-07.html). FAW-02 relies only on the direct binomial derivations above. + +## Reproduce + +```sh +PYTHONPATH=src python -m pytest -q tests/test_agency_worlds.py tests/test_agency_persistence.py +PYTHONPATH=src python scripts/verify_agency_persistence.py --output /tmp/agency_persistence.json +python scripts/check_receipts.py --only agency_persistence +``` + +The receipt records source hashes and exact rational finite evidence. It is regenerated, never edited by hand. Every theorem here is a **paper proof**, and no Lean build or empirical AI experiment is claimed. The PR remains a draft pending independent review of the quantifiers and adversarial protocol edits. diff --git a/paper/agency_unknown_reliability.md b/paper/agency_unknown_reliability.md new file mode 100644 index 00000000..cead6505 --- /dev/null +++ b/paper/agency_unknown_reliability.md @@ -0,0 +1,115 @@ +# FAW-03: Bayesian experiment design with an unknown evaluation channel + +**Draft 0.1, 2026-10-27.** Extends [FAW-01](agency_without_cryptomania.md) and [FAW-02](agency_persistence.md). The object is an exact finite stochastic control experiment about **evaluation-channel reliability**, adaptive calibration and generalization. No model, religious hypothesis, cryptographic algorithm, or real-world evaluator is observed here. All probabilities and costs in the executable verification use `fractions.Fraction`. + +## 1. Protocol and quantifiers + +One global, unknown reliability parameter \(q\) belongs to a *finite declared support* \(\mathcal Q\subseteq[1/2,1]\), with proper rational prior \(\pi(q)\). The true \(q\) is sampled **once at the beginning** and persists across epochs. At the start of epoch \(i\), sample a fresh independent fair polarity \(\theta_i\in\{0,1\}\). Every calibration or held-out item independently draws uniform true state \(s\) and Bernoulli noise bit \(e\) with \(P(e=0\mid q)=q\). The observed signal is \(y=s\oplus\theta_i\oplus e\). A calibration purchase reveals an independently certified gold label \(s\), providing the observed polarity \(z=s\oplus y=\theta_i\oplus e\). + +Each epoch has a known number \(n_i\) of held-out predictions, calibration purchase cost \(c_i\ge0\), and within-epoch acquisition cap \(M_i\). The agent can purchase labels **adaptively** using all current-epoch calibration results and previous epochs' calibration history. It decides when to stop buying, then predicts every held-out state. Held-out true labels, verdicts and scores remain **sealed through the full horizon**, including between epochs. Unpurchased gold items and hidden states are unavailable. Planning computation itself has no charged cost. The rules and prior are known; actual \(q\), current \(\theta_i\), and noise are unknown. + +This is a stylized gold-anchored channel audit. If gold labels themselves are corrupted, reused, selected after observing model behavior, or generated by a correlated grader, the likelihood and all conclusions about reliability require re-auditing. + +## 2. Learning reliability needs two labels per fresh polarity + +For a single observed calibration polarity \(z\), marginalizing the fair \(\theta_i\) gives + +\[ + P(z=0\mid q)=P(z=1\mid q)=\tfrac12 \quad\text{for every }q. +\] + +**FAW-03/A (one-label impossibility; algebraic identity).** One calibration item from each of arbitrarily many independent fresh-polarity epochs carries zero information about \(q\): the likelihood of every such sequence is \(2^{-N}\). With epoch polarities independent and fair, \(P(q\mid z_1,\dots,z_N)=\pi(q)\). An agent can still use the one item to infer its current polarity imperfectly and improve that epoch's predictions. The impossibility concerns **reliability identification**, not the current-epoch prediction utility. + +For two labels sharing one polarity, let \(A=\mathbf1[z_1=z_2]\). Marginalizing \(\theta_i\) gives + +\[ +\boxed{P(A=1\mid q)=a(q)=q^2+(1-q)^2.} +\] + +**FAW-03/B (identification with two-label epochs; algebraic identity).** On \([1/2,1]\), \(a(q)\) is strictly increasing. Hence each distinct rational \(q\) in a finite support has a distinct agreement probability. Two independently labeled examples per epoch, with refreshed polarity between epochs, make channel reliability statistically identifiable. The likelihood updates through the counts of agreement and disagreement from *independent two-label epochs*, never by treating different epochs' polarities as shared. + +For a true support point \(q_*\), write \(a_*=a(q_*)\) and \(\delta_* = \min_{q\ne q_*}|a(q)-a_*|>0\). After \(N\ge1\) two-label epochs, estimate \(q\) by selecting the nearest support agreement rate to the empirical frequency of agreement. Nearest-rate ties select the smaller \(q\). A wrong decision requires a deviation of at least \(\delta_*/2\). Thus **FAW-03/C (finite-support consistency; probabilistic inequality)** follows from Chebyshev's inequality: + +\[ + \boxed{P(\widehat q_N\ne q_*)\le\min\!\left(1,\frac{4a_*(1-a_*)}{N\delta_*^2}\right)\longrightarrow0.} +\] + +The bound is worst-case and loose for small \(N\). It certifies consistency for every fixed finite separated support. The executable program also enumerates exact binomial identification probabilities on predeclared small horizons. + +## 3. Exact Bayesian posterior and optimal acquisition + +Let \(k_0,k_1\) count observations with \(z=0,1\) in the current epoch. The unnormalized posterior masses are + +\[ + w(q,0)=\tfrac{\pi(q)}2 q^{k_0}(1-q)^{k_1},\qquad + w(q,1)=\tfrac{\pi(q)}2 (1-q)^{k_0}q^{k_1}. +\] + +Normalize by their sum \(Z\) on any positive-probability history. The probability that a new observation is zero, which also equals the probability that prediction \(\hat s=y\) is correct on a *fresh held-out item*, is + +\[ + p_0=\sum_{q,\theta}P(q,\theta\mid k_0,k_1) + \begin{cases}q,&\theta=0,\\1-q,&\theta=1.\end{cases} +\] + +The Bayes-optimal held-out accuracy is \(A=\max\{p_0,1-p_0\}\). The conditioned oracle, which knows \(q\) and \(\theta_i\), has expected accuracy \(\sum_q q\,P(q\mid k_0,k_1)\). An agent choosing the wrong prediction can be caught by independently held-out labels; selecting calibration budgets on a reused grading set is outside the protocol. + +**FAW-03/D (finite-horizon optimality; Bellman induction).** Suppose \(V_i(\pi;k_0,k_1)\) is expected *future* reward above chance, after prior calibration costs have been paid. Define \(\pi'\) as the marginal current posterior of \(q\). The agent may stop and collect the expected held-out advantage, carrying \(\pi'\) to the next independent-polarity epoch: + +\[ +S_i=n_i(A-1/2)+V_{i+1}(\pi';0,0). +\] + +If labels remain, it may buy one more at cost \(c_i\), followed by a conditional branch: + +\[ +B_i=-c_i+p_0 V_i(\pi;k_0+1,k_1)+(1-p_0)V_i(\pi;k_0,k_1+1). +\] + +Take \(V_i=\max\{S_i,B_i\}\) with stopping preferred on equality, force stopping when the cap is reached, and set the value beyond the final epoch to zero. The \(q\) prior is updated at the epoch boundary, while \(\theta\) is refreshed. Finite backward induction proves the planner is Bayes-optimal among all policies respecting these action and information boundaries. It does **not** imply computationally efficient planning for large supports, horizons or more general environments. No Lean formalization exists yet. + +## 4. Complete finite witness: an experiment with zero immediate reward + +Take \(\mathcal Q=\{1/2,1\}\) with equal prior probability. Each purchased gold label costs one unit. The preliminary epoch has zero held-out decisions and a two-label cap. Each of the following twelve epochs offers six independently held-out decisions and at most one label. All twelve polarities are freshly redrawn, while the true \(q\) persists. + +The agent could skip the preliminary audit. Without prior reliability information, the single-label decision is worth + +\[ +6\bigl[\tfrac12\cdot 0+\tfrac12\cdot(1-1/2)\bigr]-1 = 1/2 +\] + +expected net units per later epoch, hence **6** over twelve epochs. + +Buying two preliminary labels costs **2**, reveals whether their observed polarities agree, and changes future decisions: + +| First-epoch observed pair | Probability | Posterior \(P(q=1)\) | Future action | Net gain per later epoch | +|---|---:|---:|---|---:| +| Agree | 3/4 | 2/3 | Buy one label | 1 | +| Disagree | 1/4 | 0 | Buy zero labels | 0 | + +The expected future net gain is \(12[(3/4)\cdot1+(1/4)\cdot0]=9\). Subtracting the preliminary cost gives **7**, one unit more than the alternative. An immediate-horizon planner for the first epoch would refuse to buy any label because that epoch has zero test reward. The full thirteen-epoch planner rationally buys two. The first label by itself does not update reliability and has negative value when only one preliminary purchase is permitted. + +The exact global Bellman policy buys an expected **11** labels in total: two for the first audit and nine expected labels over the remaining epochs. Skipping the audit uses twelve expected labels. Both strategies achieve **54** expected correct held-out predictions out of **72**, which equals the expected reliability-informed oracle accuracy for this support. Thus the full improvement from early experimentation is a lower *calibration cost*, with no change in population predictive success. The fixture is intentionally chosen to expose this mechanism with integer values. For general \(q\) supports, positive oracle regret and nontrivial policy errors remain possible. + +## 5. Falsifiers and limitations + +- **Polarity persistent instead of refreshed:** one label from different epochs may then reveal reliability, defeating FAW-03/A. +- **Reliability resampled every epoch:** the preliminary audit loses its value for future episodes; the initial optimum is to stop, giving expected future gain 6 in the specified fixture. +- **Untrusted gold labels:** the same posterior may estimate a mixture of grader bias, source-label error, and signal error instead of \(q\). +- **Leaked held-out rewards:** test feedback becomes training information, changing the Bayes information state and evaluation estimand. +- **Misspecified prior:** unknown reliability outside the finite declared support requires robust, continuous-prior, or misspecification analysis. +- **Price/label availability changes:** any costs, budgets or trial counts outside the declared fixture require recomputing the finite Bellman policy. + +This is a *constructive functional learning witness* that never assumes one-way functions, NP hardness, or public-key cryptography. It cannot identify our actual complexity world, moral agency, consciousness, or what a creator prefers. The philosophical bridge between mathematical struggle and theological elegance is still an independent hypothesis. FAW-03 extends the existence result by adding unknown environment parameters and decision-relevant information acquisition. + +## Evidence and reproduction + +The mathematical identities are supported by direct derivation; the Bellman optimality theorem is proved by finite recursion over reachable states. The source contains separate exhaustive latent-world enumeration tests that calculate held-out accuracy and brute-force **all policies in a two-purchase decision tree** independently of the optimized dynamic program. A twelve-epoch finite audit tests the larger state graph and checks an independent net-value accounting identity. All rational values, checks and four source-file hashes are saved in a reproducible receipt. This is synthetic evidence only. + +```sh +PYTHONPATH=src python -m pytest -q tests/test_agency_unknown.py +PYTHONPATH=src python scripts/verify_agency_unknown.py --output /tmp/agency_unknown.json +python scripts/check_receipts.py --only agency_unknown +``` + +For the relationship to feedback-channel separation, read [evaluation design calculus](evaluation_design_calculus.md), [gold calibration](gold_calibration_second_grader.md), and the first two [agency notes](agency_persistence.md). The statements here are paper proofs; the Lean build and any application to real AI-evaluation records are separate future verification gates. diff --git a/paper/agency_without_cryptomania.md b/paper/agency_without_cryptomania.md new file mode 100644 index 00000000..384afc88 --- /dev/null +++ b/paper/agency_without_cryptomania.md @@ -0,0 +1,90 @@ +# Agency without Cryptomania: an exact finite witness and a hierarchy argument + +**Draft 0.1, 2026-10-27.** Independent workstream adjacent to the five-world assumption audit in [EvalMath PR #14](https://github.com/MoralityLabAI/EvalMath/pull/14). This note is a formal treatment of an interpretation of the claim that a creator may value intelligent struggle. It makes **no empirical claim about the existence, intentions, or preferences of God**. It does not select which complexity world is real. + +**Research question.** Does a meaningful opportunity for bounded agents to learn, deliberate, and improve require asymptotically secure public-key cryptography? The answer depends on how "meaningful" is defined. Under the deliberately weak *functional agency witness* below, it does not: a constant-time learnable decision problem suffices. More ambitious meanings require explicit bridge axioms. + +## 1. Distinguish the five worlds from the agency hypothesis + +The Impagliazzo taxonomy separates five possibilities by hardness strength, including *Algorithmica* (`P = NP`), *Heuristica* (worst-case NP hardness without average-case NP hardness), *Pessiland* (average-case NP hardness without one-way functions), *Minicrypt* (one-way functions without public-key encryption) and *Cryptomania* (public-key encryption exists). These are *hypothetical* cases; our program neither proves them separately consistent nor rules them out. For careful provenance see [Impagliazzo five worlds via Sorbonne Université](https://qics.sorbonne-universite.fr/en/impact-quantum-computers-impagliazzos-five-worlds) and [Hirahara's survey](https://researchmap.jp/shuichi.hirahara/published_papers/40816859/attachment_file.pdf). + +A polynomial-time attack on a particular curve breaks a concrete scheme under its security assumptions. It does not establish the universal statement that *all* public-key encryption is impossible. A proof of `P = NP` would exclude the standard asymptotic definition of Cryptomania; it would not erase time-bounded choice, noisy information, undecidable problems, or complexity beyond NP. Practical feasibility additionally depends on exponents, constants and available resources. + +## 2. Exact functional agency witness (FAW-01) + +The following is an intentionally narrow, falsifiable *operational* definition, not a definition of moral worth or consciousness. A functional agency witness has (a) available policies with different expected utility in a common environment; (b) a bounded, causally available information channel; (c) an independently scored policy whose expected utility improves after useful calibration; and (d) a finite budget choice with a measurable opportunity cost. "Meaningful" in a broader philosophical sense remains an external premise. + +Let hidden channel polarity `theta` and the state `s` be independent, uniform bits. On any interaction the agent receives a signal `y = s XOR theta XOR e`, where `Pr(e = 0) = q` and `1/2 <= q <= 1`. A *labeled calibration item* shows `(s,y)`; a held-out item provides only `y`. Its state, polarity prior and noise law match calibration, but its noise is fresh. The agent learns `theta` by majority vote over `s_i XOR y_i`, choosing zero on a tie. It then predicts held-out `s_hat = y XOR theta_hat`. Scoring gives reward one when `s_hat = s` and zero otherwise. Sample acquisition costs `c` per labeled example. + +Let `alpha_m(q)` be the probability that majority voting recovers `theta` from `m` calibration labels. For every nonnegative integer `m`, + +\[ +\alpha_m(q)=\sum_{k>m/2}\binom{m}{k}q^k(1-q)^{m-k} ++\tfrac12\mathbf 1_{2\mid m}\binom{m}{m/2}q^{m/2}(1-q)^{m/2}. +\] + +**Claim A1, algebraic identity.** The fresh held-out probability of success is + +\[ +A_m(q)=(1-q)+(2q-1)\alpha_m(q),\quad A_0(q)=\tfrac12. +\] + +*Proof.* Conditional on `theta_hat = theta`, the fresh signal is correct with probability `q`; conditional on a wrong inferred polarity, it is correct with probability `1-q`. Total probability yields the formula. For even `m`, a tied majority has equal prior likelihood under both polarities, so a deterministic zero tie-break succeeds with probability one half under the uniform prior. In this particular symmetric model the resulting tie term is exactly the displayed factor. + +A full-information oracle that knows the polarity obtains `q` on future items, leaving unavoidable noise when `q < 1`. All mathematical work here concerns the synthetic declared distribution. It makes no claim about an actual AI evaluator. + +**Claim A2, finite verified fixture.** At `q = 3/4`, + +| Calibration labels | Held-out success | Improvement over zero labels | +|---:|---:|---:| +| 0 | 1/2 | 0 | +| 1 | 5/8 | 1/8 | +| 2 | 5/8 | 1/8 | +| 3 | 43/64 | 11/64 | +| 4 | 43/64 | 11/64 | +| 5 | 715/1024 | 203/1024 | + +The finite program independently enumerates polarities, calibration noise, and fresh held-out noise to check the binomial formula. The train and held-out draws are independent. With a cost `c=1/32` per calibration label and a budget `m <= 5`, one label uniquely maximizes `A_m(q)-mc`, giving `19/32`; zero labels give `1/2`. This yields both a measurable advantage to information and a nontrivial finite choice concerning its cost. The program records all ties rather than inventing a unique choice. + +The information-access negative control is also exact: a policy that memorizes the one labeled calibration item can score `1` on that reused item while its independent held-out success is `5/8`, a gap of `3/8`. That apparent training success has a different estimand from population learning. + +Degenerate controls: when `q=1/2`, every budget obtains `1/2` held-out accuracy; when `q=1`, one label identifies the polarity exactly. Neither control licenses an interpretation of observed model learning. + +**Claim A3, interpretive limit.** The FAW-01 fixture uses constant-size binary operations and exact finite probabilities. Its existence does not assume a one-way function, hardness of NP, or public-key encryption. Embedding it in the five *hypothetical* worlds gives the same payoff law. Hence, given this operational definition, the proposition "agency witness implies public-key encryption" has a simple counterexample. The argument says nothing about whether any of the five worlds is logically consistent, nor whether this limited operational witness suffices for the theological meaning of struggle. + +## 3. Stronger computational challenge survives Algorithmica + +**Claim H1, cited theorem application.** The deterministic time-hierarchy theorem yields `P` as a proper subset of `EXP`. Even if `P = NP`, there are decidable languages outside polynomial time. More specifically, for each fixed polynomial time budget `n^k` (with conventional machine-model and time-constructibility conditions), a decidable language can be diagonalized to exceed that budget while remaining in a larger deterministic time class. This is an *unconditional worst-case existence* claim. It supplies neither average-case hardness on a natural distribution, efficient solution verification, nor public-key cryptography. An accessible [proof and time-hierarchy derivation](https://introtcs.org/public/lec_11_running_time.html) appears in Barak's *Introduction to Theoretical Computer Science*. + +A more ethically interesting notion of struggle needs an explicit family of resource-bounded learning environments with natural tasks, consequential rewards, adaptation and independent evaluation. Such a theorem is **open here**. FAW-01 establishes an elementary information-limited instance, and H1 identifies an independent complexity-theoretic source of difficulty. They are different evidence types. + +## 4. Falsification ledger + +| Observed result | What follows | What remains open | +|---|---|---| +| Prove `P = NP` | Rules out Cryptomania's standard asymptotic hardness premise | Whether bounded agency has moral meaning; practical exponents | +| Discover polynomial-time ECDLP for a named curve | Breaks the asymptotic ECDLP premise of the affected scheme | Existence of secure public-key encryption from another assumption | +| Demonstrate secure PKE from a named assumption | Conditional route to Cryptomania | Whether the assumption is true; creator's preference | +| Run `q=1/2` in FAW-01 | Zero feedback benefit, as the model predicts | Whether useful information exists in other environments | +| Observe real-agent gains on reused evaluations | Potential measurement artefact | True transfer until held-out evaluation confirms it | +| Reject the theological bridge "a good struggle requires PKE" | Revised philosophical hypothesis | Complexity world's actual identity | + +A creator-preference hypothesis becomes mathematically discriminating only with explicit bridge assumptions connecting a utility over possible worlds to particular complexity statements. A broad claim that God enjoys struggle is consistent with every row of the world taxonomy. No cryptographic experiment can independently infer divine intentions. + +## 5. Proof obligations and scope + +- **Algebraic identity:** A1, by elementary total probability and finite binomial counting. Not Lean-formalized. +- **Finite verified example:** A2 and all boundary cases, exact rational tests and independently enumerated witness. No AI was run. +- **Synthetic mechanism:** A3, restricted to the FAW-01 operational definition. +- **Cited:** H1 (deterministic time hierarchy), not proved in this repository. +- **Open:** Natural-distribution hardness in the agency setting, principled mapping from functional to moral agency, theological bridge axioms, and any empirical world selection. + +To reproduce from repository root: + +```sh +PYTHONPATH=src python -m pytest -q tests/test_agency_worlds.py +PYTHONPATH=src python scripts/verify_agency_worlds.py --output /tmp/agency_worlds.json +python scripts/check_receipts.py --only agency_worlds +``` + +The committed receipt includes source hashes, rational values and twelve independently checked invariants. The verifier never overwrites an existing receipt. The repository's general `verify.yml` workflow runs this test file with the full test suite and the registered receipt checker; its status must be read separately from local results. diff --git a/scripts/check_receipts.py b/scripts/check_receipts.py index 7791cf67..02c6002b 100644 --- a/scripts/check_receipts.py +++ b/scripts/check_receipts.py @@ -27,6 +27,12 @@ RECEIPTS = { "openai_eth_fidelity": ("scripts/verify_proof_fidelity_openai_eth.py", "output/proof_fidelity/openai_eth_v0_2.json", [], False), + "agency_unknown": ("scripts/verify_agency_unknown.py", + "output/agency_unknown/unknown_v1.json", [], False), + "agency_persistence": ("scripts/verify_agency_persistence.py", + "output/agency_persistence/persistence_v1.json", [], False), + "agency_worlds": ("scripts/verify_agency_worlds.py", + "output/agency_worlds/agency_v1.json", [], False), "design_calculus": ("scripts/verify_evaluation_design_calculus.py", "output/evaluation_design_calculus/v0_verification.json", [], False), "prime_atlas": ("scripts/verify_prime_eval_atlas.py", diff --git a/scripts/verify_agency_persistence.py b/scripts/verify_agency_persistence.py new file mode 100644 index 00000000..f59dcda7 --- /dev/null +++ b/scripts/verify_agency_persistence.py @@ -0,0 +1,50 @@ +"""Verify FAW-02 with exact rational fixtures and immutable source receipts.""" + +from __future__ import annotations + +import argparse +import json +from datetime import datetime, timezone +from fractions import Fraction +from hashlib import sha256 +from pathlib import Path + +from spiral_ln.agency_persistence import fixture + +SOURCES = ( + "src/spiral_ln/agency_persistence.py", + "tests/test_agency_persistence.py", + "scripts/verify_agency_persistence.py", + "paper/agency_persistence.md", +) + + +def _encode(value: object) -> str: + if isinstance(value, Fraction): + return str(value) + raise TypeError(f"nonserializable: {type(value)!r}") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path) + args = parser.parse_args() + root = Path(__file__).resolve().parents[1] + report = { + "generated_at_utc": datetime.now(timezone.utc).isoformat(), + **fixture(), + "source_sha256": {relative: sha256((root / relative).read_bytes()).hexdigest() + for relative in SOURCES}, + } + rendered = json.dumps(report, indent=2, default=_encode) + "\n" + if args.output: + args.output.parent.mkdir(parents=True, exist_ok=True) + with args.output.open("x", encoding="utf-8") as stream: + stream.write(rendered) + else: + print(rendered, end="") + return 0 if report["all_passed"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/verify_agency_unknown.py b/scripts/verify_agency_unknown.py new file mode 100644 index 00000000..db1958fb --- /dev/null +++ b/scripts/verify_agency_unknown.py @@ -0,0 +1,50 @@ +"""Regenerate exact FAW-03 unknown-reliability Bayesian experiment receipt.""" + +from __future__ import annotations + +import argparse +import json +from datetime import datetime, timezone +from fractions import Fraction +from hashlib import sha256 +from pathlib import Path + +from spiral_ln.agency_unknown import fixture + +SOURCES = ( + "src/spiral_ln/agency_unknown.py", + "tests/test_agency_unknown.py", + "scripts/verify_agency_unknown.py", + "paper/agency_unknown_reliability.md", +) + + +def _encode(value: object) -> str: + if isinstance(value, Fraction): + return str(value) + raise TypeError(f"cannot encode {type(value)!r}") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path) + args = parser.parse_args() + root = Path(__file__).resolve().parents[1] + report = { + "generated_at_utc": datetime.now(timezone.utc).isoformat(), + **fixture(), + "source_sha256": {rel: sha256((root/rel).read_bytes()).hexdigest() + for rel in SOURCES}, + } + output = json.dumps(report, indent=2, default=_encode)+"\n" + if args.output is not None: + args.output.parent.mkdir(parents=True, exist_ok=True) + with args.output.open("x", encoding="utf-8") as stream: + stream.write(output) + else: + print(output, end="") + return 0 if report["all_passed"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/verify_agency_worlds.py b/scripts/verify_agency_worlds.py new file mode 100644 index 00000000..443855bd --- /dev/null +++ b/scripts/verify_agency_worlds.py @@ -0,0 +1,52 @@ +"""Regenerate a deterministic exact-rational finite agency receipt.""" + +from __future__ import annotations + +import argparse +import json +from datetime import datetime, timezone +from fractions import Fraction +from hashlib import sha256 +from pathlib import Path + +from spiral_ln.agency_worlds import fixture + + +SOURCES = ( + "src/spiral_ln/agency_worlds.py", + "tests/test_agency_worlds.py", + "scripts/verify_agency_worlds.py", + "paper/agency_without_cryptomania.md", +) + + +def _encode(value: object) -> str: + if isinstance(value, Fraction): + return str(value) + raise TypeError(f"nonserializable: {type(value)!r}") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path) + args = parser.parse_args() + root = Path(__file__).resolve().parents[1] + report = { + "schema_version": "1.0", + "generated_at_utc": datetime.now(timezone.utc).isoformat(), + **fixture(), + "source_sha256": {name: sha256((root / name).read_bytes()).hexdigest() + for name in SOURCES}, + } + rendered = json.dumps(report, indent=2, default=_encode) + "\n" + if args.output: + args.output.parent.mkdir(parents=True, exist_ok=True) + with args.output.open("x", encoding="utf-8") as stream: + stream.write(rendered) + else: + print(rendered, end="") + return 0 if report["all_passed"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/spiral_ln/agency_persistence.py b/src/spiral_ln/agency_persistence.py new file mode 100644 index 00000000..c8277bff --- /dev/null +++ b/src/spiral_ln/agency_persistence.py @@ -0,0 +1,236 @@ +"""Exact persistent learning with fresh hidden polarity in each evaluation epoch. + +A small operational agent learns using labeled calibration, makes held-out +choices with rewards sealed until the epoch ends, and pays for labels. The +instance has no cryptographic hardness premise. All arithmetic is rational. +""" + +from __future__ import annotations + +from fractions import Fraction as Q + +from spiral_ln.agency_worlds import calibration_accuracy, heldout_success + +Q_SIGNAL = Q(3, 4) +C_LABEL = Q(1, 32) + + +def _epoch(epoch: int) -> int: + if isinstance(epoch, bool) or not isinstance(epoch, int) or epoch < 1: + raise ValueError("epoch must be a positive integer") + return epoch + + +def _cost(cost: Q) -> Q: + if not isinstance(cost, Q): + raise TypeError("cost must be an exact Fraction") + if cost < 0: + raise ValueError("cost must be nonnegative") + return cost + + +def label_budget(epoch: int) -> int: + """5 * ceil(log2(t+1)), evaluated as an exact integer.""" + return 5 * _epoch(epoch).bit_length() + + +def epoch_metrics(epoch: int, cost: Q = C_LABEL) -> dict[str, object]: + """Calibration then t+1 fresh held-out predictions with sealed feedback.""" + t = _epoch(epoch) + c = _cost(cost) + bits = t.bit_length() + samples = label_budget(t) + decisions = t + 1 + alpha = calibration_accuracy(Q_SIGNAL, samples) + error = 1 - alpha + accuracy = heldout_success(Q_SIGNAL, samples) + oracle_regret = decisions * (Q_SIGNAL - accuracy) + gross_gain = decisions * (accuracy - Q(1, 2)) + net_gain = gross_gain - samples*c + # In the Chernoff calculation, p_error^2 <= (3/4)^m. + # The pure-rational factor (3/4)^5 = 243/1024 <= 1/4 yields + # p_error <= 2^(-bit_length(t)) <= 1/(t+1). + certificate = { + "chernoff_square": error**2 <= Q(3, 4)**samples, + "five_label_factor": Q(243, 1024) <= Q(1, 4), + "epoch_within_binary_scale": decisions <= (1 << bits), + "polarity_error_bound": error <= Q(1, 2)**bits, + "single_test_regret_bound": Q_SIGNAL-accuracy <= Q(1, 2*decisions), + "epoch_oracle_regret_bound": oracle_regret <= Q(1, 2), + "net_lower_bound": net_gain >= Q(8*(t-1)-5*bits, 32) if c == C_LABEL else True, + "positive_net_witness": net_gain > 0 if c == C_LABEL else True, + } + return { + "epoch": t, + "bits": bits, + "calibration_labels": samples, + "independent_heldout_trials": decisions, + "polarity_recovery": alpha, + "polarity_error": error, + "heldout_success": accuracy, + "oracle_regret": oracle_regret, + "baseline_gain": gross_gain, + "label_cost": samples*c, + "net_baseline_gain": net_gain, + "net_lower_bound": Q(8*(t-1)-5*bits, 32) if c == C_LABEL else None, + "certificate": certificate, + } + + +def optimal_epoch(epoch: int, cost: Q = C_LABEL) -> dict[str, object]: + """Choose the best label count in the SAME declared finite budget. + + This is a rational planning fixture with the outcome distribution known, + rather than an experiment where a model designs its own evaluation. + Computation cost is excluded; the acquisition cost is fully included. + """ + t = _epoch(epoch) + c = _cost(cost) + decisions = t+1 + budget = label_budget(t) + net_values = tuple(decisions*(heldout_success(Q_SIGNAL, n)-Q(1, 2)) - n*c + for n in range(budget+1)) + maximum = max(net_values) + ties = tuple(n for n, utility in enumerate(net_values) if utility == maximum) + chosen = ties[0] # minimum acquisition cost among exact equal-utility ties + accuracy = heldout_success(Q_SIGNAL, chosen) + regret = decisions*(Q_SIGNAL-accuracy) + scheduled = epoch_metrics(t, c) + return { + "epoch": t, + "budget": budget, + "selected_labels": chosen, + "equally_optimal_label_counts": ties, + "heldout_success": accuracy, + "oracle_regret": regret, + "net_baseline_gain": maximum, + "certificate": { + "budget_respected": chosen <= budget, + "net_no_worse_than_schedule": maximum >= scheduled["net_baseline_gain"], + # Optimality: N*r_opt+c*m_opt <= N*r_sched+c*m_sched + "costed_oracle_regret_bound": regret + c*chosen <= Q(1, 2)+c*budget, + }, + } + + +def horizon_metrics(horizon: int, cost: Q = C_LABEL) -> dict[str, object]: + """Expected cumulative value of T independent epochs under both policies.""" + T = _epoch(horizon) + c = _cost(cost) + stages = tuple(epoch_metrics(t, c) for t in range(1, T+1)) + choices = tuple(optimal_epoch(t, c) for t in range(1, T+1)) + decisions = T*(T+3)//2 + labels = sum(s["calibration_labels"] for s in stages) + regret = sum((s["oracle_regret"] for s in stages), Q(0)) + gross = sum((s["baseline_gain"] for s in stages), Q(0)) + net = gross - c*labels + opt_labels = sum(x["selected_labels"] for x in choices) + opt_regret = sum((x["oracle_regret"] for x in choices), Q(0)) + opt_net = sum((x["net_baseline_gain"] for x in choices), Q(0)) + bit_bound = 5*T*T.bit_length() + opt_regret_upper = Q(T, 2)+c*bit_bound + certificates = { + "stage_certificates": all(all(x["certificate"].values()) for x in stages), + "optimizer_certificates": all(all(x["certificate"].values()) for x in choices), + "heldout_count": sum(s["independent_heldout_trials"] for s in stages) == decisions, + "labels_at_most_5Tlog": labels <= bit_bound, + "cumulative_regret_at_most_T_over_2": regret <= Q(T, 2), + "average_regret_at_most_inverse_horizon": regret/decisions <= Q(1, T+3), + "baseline_gain_identity": gross == Q(decisions, 4)-regret, + "normalized_net_lower_bound": net/decisions >= Q(1, 4)-Q(1, T+3)-c*Q(10*T.bit_length(), T+3), + "optimal_net_dominates_schedule": opt_net >= net, + "optimal_regret_bound": opt_regret <= opt_regret_upper, + "optimal_average_regret_bound": opt_regret/decisions <= Q(1, T+3)+c*Q(10*T.bit_length(), T+3), + "schedule_positive_net": net > 0 if c == C_LABEL else True, + "optimized_positive_net": opt_net > 0 if c == C_LABEL else True, + } + return { + "horizon": T, + "heldout_trials": decisions, + "scheduled_calibration_labels": labels, + "label_upper_bound": bit_bound, + "schedule_oracle_regret": regret, + "schedule_avg_oracle_regret": regret/decisions, + "schedule_regret_bound_per_trial": Q(1, T+3), + "schedule_net_gain_over_chance": net, + "schedule_net_gain_per_trial": net/decisions, + "optimized_calibration_labels": opt_labels, + "optimized_oracle_regret": opt_regret, + "optimized_avg_oracle_regret": opt_regret/decisions, + "optimized_regret_bound_per_trial": Q(1, T+3)+c*Q(10*T.bit_length(), T+3), + "optimized_net_gain_over_chance": opt_net, + "optimized_net_gain_per_trial": opt_net/decisions, + "certificates": certificates, + } + + +def fixed_label_regret_floor(q: Q, max_labels: int) -> Q: + """A positive gap if every fresh-polarity epoch has <= M labels. + + With m>=1 the all-flipped-noise event yields erroneous polarity with + probability (1-q)^m; with m=0 error is 1/2. Even adaptive choices + based solely on past independent epochs cannot predict fresh theta. + This formula addresses declared nonadaptive within-epoch sample counts; + adaptively stopping from current-epoch labels needs separate analysis. + """ + if not isinstance(q, Q) or not Q(1, 2) < q < 1: + raise ValueError("q must be an exact Fraction strictly inside (1/2,1)") + if isinstance(max_labels, bool) or not isinstance(max_labels, int) or max_labels < 0: + raise ValueError("max_labels must be a nonnegative integer") + return (2*q-1)*min(Q(1, 2), (1-q)**max_labels) + + +def prior_epoch_transfer(q: Q, calibration_labels: int, shared_polarity: bool) -> Q: + """Control: old labels help only when the hidden polarity persists. + + Each held-out signal's state is fresh and uniform, and feedback stays + sealed. With independently refreshed hidden polarity, a past-epoch + estimate has probability 1/2 of being correct in the next epoch. + """ + accuracy = heldout_success(q, calibration_labels) # validate both inputs + if not isinstance(shared_polarity, bool): + raise TypeError("shared_polarity must be boolean") + return accuracy if shared_polarity else Q(1, 2) + + +def fixture() -> dict[str, object]: + """Exact finite fixtures; all-horizon proofs are stated in the note.""" + horizons = (1, 2, 4, 8, 16, 32, 64) + reports = tuple(horizon_metrics(t) for t in horizons) + floors = tuple((q, m, fixed_label_regret_floor(q, m)) + for q in (Q(2, 3), Q(3, 4), Q(4, 5)) for m in (0, 1, 3, 8)) + checks = { + "stage_certificates": all(all(epoch_metrics(t)["certificate"].values()) for t in range(1, 65)), + "horizon_certificates": all(all(x["certificates"].values()) for x in reports), + "first_budget_five": label_budget(1) == 5, + "power_of_two_boundary_budgets": (label_budget(2), label_budget(3), label_budget(4)) == (10, 10, 15), + "first_epoch_exact_accuracy": epoch_metrics(1)["heldout_success"] == Q(715, 1024), + "every_tested_epoch_positive_net": all(epoch_metrics(t)["net_baseline_gain"] > 0 for t in range(1, 65)), + "optimized_nets_dominate": all(optimal_epoch(t)["net_baseline_gain"] >= epoch_metrics(t)["net_baseline_gain"] + for t in range(1, 65)), + "finite_fixed_budget_regret_floor": all(floor > 0 and all(q-heldout_success(q, n) >= floor + for n in range(m+1)) + for q, m, floor in floors), + "fresh_polarity_prevents_cross_epoch_transfer": prior_epoch_transfer(Q_SIGNAL, 1, False) == Q(1, 2), + "shared_polarity_allows_transfer": prior_epoch_transfer(Q_SIGNAL, 1, True) == Q(5, 8), + "uninformative_signal_negative_control": all(heldout_success(Q(1, 2), label_budget(t)) == Q(1, 2) + for t in range(1, 32)), + } + return { + "schema_version": "1.0", + "mechanism": "fresh_uniform_polarity_each_epoch; sealed_heldout_feedback", + "signal_reliability": Q_SIGNAL, + "label_cost": C_LABEL, + "fixed_schedule": "m_t=5*bit_length(t)", + "heldout_schedule": "n_t=t+1", + "five_label_cher_bound_squared": Q(243, 1024), + "finite_horizon_reports": reports, + "fixed_budget_lower_bound_controls": floors, + "checks": checks, + "all_passed": all(checks.values()), + "evidence_level": "algebraic_argument_plus_finite_exact_tests", + "theological_hypothesis_identified": False, + "public_key_cryptography_assumed": False, + "empirical_agents_evaluated": False, + "lean_formalized": False, + } diff --git a/src/spiral_ln/agency_unknown.py b/src/spiral_ln/agency_unknown.py new file mode 100644 index 00000000..96d0ddb2 --- /dev/null +++ b/src/spiral_ln/agency_unknown.py @@ -0,0 +1,339 @@ +"""FAW-03: exact Bayesian calibration with unknown persistent channel reliability. + +Within each epoch polarity is fresh; q persists across epochs and belongs to +an explicitly declared finite rational prior. Labeled calibration returns +z=s XOR y; reward labels remain sealed until all test decisions finish. + +Dynamic programming charges each acquired gold label and maximizes expected +held-out reward net of label costs. No live models, graders or cryptography. +""" + +from __future__ import annotations + +from functools import lru_cache +from fractions import Fraction as Q +from itertools import product +from math import comb + +Prior = tuple[tuple[Q, Q], ...] # (reliability, probability), sorted uniquely +DEFAULT_PRIOR: Prior = ((Q(1, 2), Q(1, 2)), (Q(1), Q(1, 2))) + + +def validate_prior(prior: Prior) -> Prior: + if not isinstance(prior, tuple) or not prior: + raise ValueError("prior must be a nonempty tuple") + qs: list[Q] = [] + weight = Q(0) + for entry in prior: + if not isinstance(entry, tuple) or len(entry) != 2: + raise ValueError("prior entries must be (q, weight) tuples") + q, w = entry + if not isinstance(q, Q) or not isinstance(w, Q): + raise TypeError("reliabilities and weights must be Fractions") + if not Q(1, 2) <= q <= 1 or w <= 0: + raise ValueError("reliabilities in [1/2,1], weights positive") + qs.append(q) + weight += w + if qs != sorted(set(qs)) or weight != 1: + raise ValueError("distinct q values must be sorted and weights sum to 1") + return prior + + +def _nonnegative_int(value: int, name: str) -> int: + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + raise ValueError(f"{name} must be a nonnegative integer") + return value + + +def _cost(value: Q) -> Q: + if not isinstance(value, Q): + raise TypeError("cost must be a Fraction") + if value < 0: + raise ValueError("cost must be nonnegative") + return value + + +def agreement_probability(q: Q) -> Q: + """Probability two within-epoch calibration polarities are equal.""" + if not isinstance(q, Q) or not Q(1, 2) <= q <= 1: + raise ValueError("q must be a Fraction in [1/2,1]") + return q*q + (1-q)*(1-q) + + +def _joint(prior: Prior, zeros: int, ones: int) -> tuple[tuple[Q, int, Q], ...]: + """Joint posterior on (q, theta) for one ordered calibration history. + + Counts are sufficient for the likelihood of the *ordered* observations. + The combinatorial multiplicity is used only when integrating all sequences. + """ + _nonnegative_int(zeros, "zeros") + _nonnegative_int(ones, "ones") + unnormalized = [] + for q, w in prior: + unnormalized.append((q, 0, w*Q(1, 2)*q**zeros*(1-q)**ones)) + unnormalized.append((q, 1, w*Q(1, 2)*(1-q)**zeros*q**ones)) + total = sum((weight for _, _, weight in unnormalized), Q(0)) + if total == 0: + raise ValueError("observation path has probability zero under prior") + return tuple((q, theta, weight/total) for q, theta, weight in unnormalized) + + +def state(prior: Prior, zeros: int, ones: int) -> dict[str, object]: + """Posterior prediction on a fresh item, independent of training samples.""" + validate_prior(prior) + masses = _joint(prior, zeros, ones) + p_same = sum((w*(q if theta == 0 else 1-q) for q, theta, w in masses), Q(0)) + q_posterior = tuple((q, sum((w for x, _, w in masses if x == q), Q(0))) + for q, _ in prior) + oracle = sum((q*w for q, w in q_posterior), Q(0)) + return { + "observations_zero": zeros, + "observations_one": ones, + "q_posterior": q_posterior, + "next_zero_probability": p_same, + "predict_flip": p_same < Q(1, 2), # on equality, predict s=y + "fresh_accuracy": max(p_same, 1-p_same), + "oracle_accuracy": oracle, + "oracle_gap": oracle-max(p_same, 1-p_same), + } + + +def after_pairs(prior: Prior, agree: int, differ: int) -> Prior: + """Bayes update from pairs in independent epochs with fresh theta.""" + validate_prior(prior) + _nonnegative_int(agree, "agree") + _nonnegative_int(differ, "differ") + raw = tuple((q, w*agreement_probability(q)**agree* + (1-agreement_probability(q))**differ) for q, w in prior) + z = sum((w for _, w in raw), Q(0)) + if z == 0: + raise ValueError("pair data impossible under prior") + return tuple((q, w/z) for q, w in raw if w > 0) + + +def _posterior_state(prior: Prior, zeros: int, ones: int) -> dict[str, object]: + """Internal state with zero-probability prior members retained for memoization.""" + return state(prior, zeros, ones) + + +def solve_epochs( + prior: Prior, + trials: tuple[int, ...], + caps: tuple[int, ...], + costs: tuple[Q, ...], +) -> dict[str, object]: + """Exact global Bayes-optimal acquisition policy over a finite horizon. + + At epoch boundary q persists and theta is redrawn uniformly; only the + posterior of q carries forward. All held-out judgments remain sealed. + The state contains the current epoch's calibration counts, remaining + acquisition budget, and the current q prior. Planning computation is free. + """ + validate_prior(prior) + if not trials or not (len(trials) == len(caps) == len(costs)): + raise ValueError("nonempty equal-length epoch tuples required") + for n, cap, c in zip(trials, caps, costs): + _nonnegative_int(n, "heldout trials") + _nonnegative_int(cap, "label cap") + _cost(c) + + decisions: dict[tuple[int, Prior, int, int], dict[str, object]] = {} + + @lru_cache(maxsize=None) + def epoch_start(i: int, epoch_prior: Prior) -> Q: + if i == len(trials): + return Q(0) + return within(i, epoch_prior, 0, 0) + + @lru_cache(maxsize=None) + def within(i: int, epoch_prior: Prior, zeros: int, ones: int) -> Q: + current = _posterior_state(epoch_prior, zeros, ones) + acquired = zeros + ones + # Bayes value of ending the current epoch, with future q learning. + q_next = tuple((q, w) for q, w in current["q_posterior"] if w > 0) + stop = trials[i]*(current["fresh_accuracy"]-Q(1, 2)) + epoch_start(i+1, q_next) + p0 = current["next_zero_probability"] + buy: Q | None = None + if acquired < caps[i]: + next0 = within(i, epoch_prior, zeros+1, ones) if p0 > 0 else Q(0) + next1 = within(i, epoch_prior, zeros, ones+1) if p0 < 1 else Q(0) + buy = -costs[i] + p0*next0+(1-p0)*next1 + decision = "buy" if buy is not None and buy > stop else "stop" + decisions[(i, epoch_prior, zeros, ones)] = { + "stop_value": stop, + "buy_value": buy, + "decision": decision, + "value": buy if decision == "buy" else stop, + "predict_flip": current["predict_flip"], + "fresh_accuracy": current["fresh_accuracy"], + "next_zero_probability": p0, + "q_posterior": q_next, + } + return decisions[(i, epoch_prior, zeros, ones)]["value"] + + value = epoch_start(0, prior) + + @lru_cache(maxsize=None) + def assess(i: int, epoch_prior: Prior, zeros: int, ones: int) -> tuple[Q, Q, Q, Q]: + """Expected (acquired labels, number of useful tests, correct, oracle). + + Correct and oracle are unnormalized expected *counts* across remaining + epochs. These are evaluated under the saved optimal policy. + """ + if i == len(trials): + return Q(0), Q(0), Q(0), Q(0) + decision = decisions[(i, epoch_prior, zeros, ones)] + if decision["decision"] == "stop": + next_prior = decision["q_posterior"] + labs, tests, correct, oracle = assess(i+1, next_prior, 0, 0) + current = _posterior_state(epoch_prior, zeros, ones) + return (labs, tests+trials[i], correct+trials[i]*current["fresh_accuracy"], + oracle+trials[i]*current["oracle_accuracy"]) + p0 = decision["next_zero_probability"] + x0 = assess(i, epoch_prior, zeros+1, ones) if p0 > 0 else (Q(0),)*4 + x1 = assess(i, epoch_prior, zeros, ones+1) if p0 < 1 else (Q(0),)*4 + return tuple((Q(1) if j == 0 else Q(0)) + p0*x0[j]+(1-p0)*x1[j] + for j in range(4)) + + labels, tests, correct, oracle = assess(0, prior, 0, 0) + assert tests == sum(trials) + initial_stop = decisions[(0, prior, 0, 0)] + # Source of optional planner diagnostics: public top-level decisions only. + return { + "epochs": len(trials), + "heldout_trials": sum(trials), + "value_over_chance": value, + "first_action": initial_stop["decision"], + "first_stop_value": initial_stop["stop_value"], + "first_buy_value": initial_stop["buy_value"], + "expected_gold_labels": labels, + "expected_heldout_correct": correct, + "expected_oracle_correct": oracle, + "expected_oracle_regret": oracle-correct, + "expected_label_cost": sum_expected_cost(prior, trials, caps, costs, decisions), + "value_identity": value == correct-Q(tests, 2)-sum_expected_cost( + prior, trials, caps, costs, decisions), + "policy_states": len(decisions), + "_policy": decisions, + } + + +def sum_expected_cost(prior: Prior, trials: tuple[int, ...], caps: tuple[int, ...], + costs: tuple[Q, ...], policy: dict) -> Q: + """Evaluate acquisition charges from a policy tree, across epoch boundaries.""" + @lru_cache(maxsize=None) + def visit(i: int, epoch_prior: Prior, zeros: int, ones: int) -> Q: + if i == len(trials): + return Q(0) + d = policy[(i, epoch_prior, zeros, ones)] + if d["decision"] == "stop": + return visit(i+1, d["q_posterior"], 0, 0) + p0 = d["next_zero_probability"] + return costs[i] + (p0*visit(i, epoch_prior, zeros+1, ones) if p0 > 0 else Q(0)) + ( + (1-p0)*visit(i, epoch_prior, zeros, ones+1) if p0 < 1 else Q(0)) + return visit(0, prior, 0, 0) + + +def fixed_budget_value(prior: Prior, trials: int, labels: int, cost: Q) -> Q: + """Exhaustive fixed number of labels, with posterior-optimal heldout action.""" + validate_prior(prior) + _nonnegative_int(trials, "trials") + _nonnegative_int(labels, "labels") + _cost(cost) + ans = Q(0) + for n0 in range(labels+1): + n1 = labels-n0 + prob = sum((w*Q(1, 2)*(q**n0*(1-q)**n1+ + (1-q)**n0*q**n1) for q, w in prior), Q(0)) + if prob > 0: + acc = state(prior, n0, n1)["fresh_accuracy"] + ans += Q(comb(labels, n0))*prob*trials*(acc-Q(1, 2)) + return ans-cost*labels + + +def one_label_posterior_invariant(prior: Prior) -> bool: + """With an independent uniform polarity, one gold label reveals no q.""" + validate_prior(prior) + return (state(prior, 1, 0)["q_posterior"] == prior and + state(prior, 0, 1)["q_posterior"] == prior) + + +def _closest_q(prior: Prior, empirical: Q) -> Q: + """Nearest agreement rate, deterministic lower-q tie break.""" + return min((q for q, _ in prior), key=lambda q: (abs(agreement_probability(q)-empirical), q)) + + +def identification_success(prior: Prior, true_q: Q, pairs: int) -> Q: + """Exact probability the agreement-rate estimator identifies true q.""" + validate_prior(prior) + _nonnegative_int(pairs, "pairs") + if true_q not in tuple(q for q, _ in prior): + raise ValueError("true q must be in prior support") + a = agreement_probability(true_q) + return sum((Q(comb(pairs, k))*a**k*(1-a)**(pairs-k) + for k in range(pairs+1) + if _closest_q(prior, Q(k, pairs) if pairs else Q(1, 2)) == true_q), Q(0)) + + +def identification_chebyshev_bound(prior: Prior, true_q: Q, pairs: int) -> Q: + """Exact upper bound on P(misidentification) from separated agreement rates.""" + validate_prior(prior) + _nonnegative_int(pairs, "pairs") + others = tuple(abs(agreement_probability(q)-agreement_probability(true_q)) + for q, _ in prior if q != true_q) + if true_q not in tuple(q for q, _ in prior) or not others or pairs == 0: + raise ValueError("need >0 pairs and true q in support of at least two q") + delta = min(others) + a = agreement_probability(true_q) + return min(Q(1), 4*a*(1-a)/(pairs*delta**2)) + + +def fixture() -> dict[str, object]: + """A predeclared finite toy witness; no claims of asymptotic PKE relevance.""" + prior = DEFAULT_PRIOR + # A preliminary zero-test audit of q can improve costs on later episodes: + # 12 fresh polarities, each with 6 independently held-out decisions and cap 1. + # The early two-label q-audit can be worthwhile despite no immediate reward. + episode = solve_epochs(prior, (0,)+(6,)*12, (2,)+(1,)*12, (Q(1),)*13) + fixed_one = fixed_budget_value(prior, 6, 1, Q(1)) + first = state(prior, 1, 0) + same = state(prior, 2, 0) + different = state(prior, 1, 1) + seen = tuple((k, identification_success(prior, Q(1, 2), k)) for k in (1, 2, 4, 8, 16)) + checks = { + "one_label_q_uninformative": one_label_posterior_invariant(prior), + "two_label_same_event_probability": Q(3, 4) == sum( + (w*agreement_probability(q) for q, w in prior), Q(0)), + "same_pair_updates_q": same["q_posterior"] == ((Q(1, 2), Q(1, 3)), (Q(1), Q(2, 3))), + "different_pair_identifies_noisy_channel": different["q_posterior"] == ((Q(1, 2), Q(1)), (Q(1), Q(0))), + "one_label_accuracy": first["fresh_accuracy"] == Q(3, 4), + "fixed_one_label_net": fixed_one == Q(1, 2), + "global_optimal_first_action_buy": episode["first_action"] == "buy", + "forward_utility_identity": episode["value_identity"], + "expected_global_gain_is_seven": episode["value_over_chance"] == Q(7), + "no_early_experiment_gain_six": episode["first_stop_value"] == Q(6), + "gold_label_budget_bounded": episode["expected_gold_labels"] <= Q(14), + "oracle_gap_nonnegative": episode["expected_oracle_regret"] >= 0, + "separated_rates_identifiable": all(agreement_probability(prior[i][0]) < agreement_probability(prior[i+1][0]) + for i in range(len(prior)-1)), + "exact_identification_converges_in_fixture": seen[-1][1] > seen[0][1], + } + return { + "schema_version": "1.0", + "mechanism": "q_shared_across_epochs; fresh_uniform_theta; sealed_heldout_feedback", + "prior": prior, + "posterior_after_one_label": first["q_posterior"], + "posterior_after_agree": same["q_posterior"], + "posterior_after_disagree": different["q_posterior"], + "same_pair_probability": Q(3, 4), + "single_label_epoch_value": fixed_one, + "adaptive_epoch_result": {k: v for k, v in episode.items() if k != "_policy"}, + "pair_identification": seen, + "checks": checks, + "all_passed": all(checks.values()), + "evidence_level": "algebraic_proof_and_finite_exact_bayes_planning", + "real_agent_evidence": False, + "cryptographic_world_identified": False, + "theological_hypothesis_identified": False, + "lean_formalized": False, + } diff --git a/src/spiral_ln/agency_worlds.py b/src/spiral_ln/agency_worlds.py new file mode 100644 index 00000000..55ab57f7 --- /dev/null +++ b/src/spiral_ln/agency_worlds.py @@ -0,0 +1,131 @@ +"""An exact finite agency witness independent of cryptographic hardness assumptions. + +The calibration and held-out draws are independent. This is a *synthetic* +decision experiment; it neither settles P vs NP nor tests a real model or God. +All reported probabilities use Fraction, without random sampling. +""" + +from __future__ import annotations + +from fractions import Fraction as Q +from itertools import product +from math import comb + + +def _check(q: Q, samples: int) -> None: + if not isinstance(q, Q): + raise TypeError("q must be a fractions.Fraction") + if q < Q(1, 2) or q > 1: + raise ValueError("q must be in [1/2, 1]") + if not isinstance(samples, int) or isinstance(samples, bool) or samples < 0: + raise ValueError("samples must be a nonnegative integer") + + +def calibration_accuracy(q: Q, samples: int) -> Q: + """Probability a majority decoder learns a uniformly random channel polarity. + + A calibration item discloses its true state s and noisy signal y. If the + hidden polarity is theta, y = s XOR theta XOR noise; P(noise=0) = q. + Ties are broken in favor of theta=0 (equivalently half a chance of correct + polarity under the uniform prior). No item is reused for held-out scoring. + """ + _check(q, samples) + threshold = samples // 2 + total = sum(Q(comb(samples, k)) * q**k * (1 - q)**(samples - k) + for k in range(threshold + 1, samples + 1)) + if samples % 2 == 0: + total += Q(1, 2) * Q(comb(samples, threshold)) * q**threshold * (1-q)**threshold + return total + + +def heldout_success(q: Q, samples: int) -> Q: + """Held-out correctness under learned polarity; all inputs exact.""" + alpha = calibration_accuracy(q, samples) + return (1-q) + (2*q-1)*alpha + + +def enumerate_heldout_success(q: Q, samples: int) -> Q: + """Independent finite sum over theta, labeled errors and future error. + + Enumeration uses a literal majority vote and fresh test noise rather than + the binomial closed form. Intended for small sample counts as a check. + """ + _check(q, samples) + result = Q(0) + for theta in (0, 1): + for errors in product((0, 1), repeat=samples): + probability = Q(1, 2) + observed_polarities = [theta ^ e for e in errors] + for e in errors: + probability *= q if e == 0 else 1-q + estimate = int(2 * sum(observed_polarities) > samples) + for fresh_error in (0, 1): + if estimate == (theta ^ fresh_error): + result += probability * (q if fresh_error == 0 else 1-q) + return result + + +def net_value(q: Q, samples: int, label_cost: Q) -> Q: + """Accuracy less a per-label rational cost, with no score reuse.""" + _check(q, samples) + if not isinstance(label_cost, Q): + raise TypeError("label_cost must be a fractions.Fraction") + if label_cost < 0: + raise ValueError("label_cost must be nonnegative") + return heldout_success(q, samples) - samples * label_cost + + +def optimal_calibration(q: Q, max_samples: int, label_cost: Q) -> dict[str, object]: + """Enumerate feasible training budgets; preserve all ties explicitly.""" + _check(q, max_samples) + values = tuple(net_value(q, n, label_cost) for n in range(max_samples+1)) + best = max(values) + return { + "max_samples": max_samples, + "label_cost": label_cost, + "value_by_samples": values, + "optimal_value": best, + "optimal_sample_counts": tuple(n for n, value in enumerate(values) if value == best), + } + + +def fixture() -> dict[str, object]: + """Exact finite checks, not a claim about real or hypothetical universes.""" + q = Q(3, 4) + samples = (0, 1, 2, 3, 4, 5) + successes = tuple(heldout_success(q, n) for n in samples) + plan = optimal_calibration(q, 5, Q(1, 32)) + independent_checks = { + "formula_matches_enumeration": all( + heldout_success(rate, n) == enumerate_heldout_success(rate, n) + for rate in (Q(1, 2), Q(2, 3), Q(3, 4), Q(1)) for n in range(8)), + "no_feedback_is_chance": successes[0] == Q(1, 2), + "one_label_improves_heldout": successes[1] == Q(5, 8), + "three_labels_improve_further": successes[3] == Q(43, 64), + "even_tie_matches_previous_odd": successes[2] == successes[1] and successes[4] == successes[3], + "uninformative_channel_stays_chance": all( + heldout_success(Q(1, 2), n) == Q(1, 2) for n in range(10)), + "perfect_channel_after_one_label": all( + heldout_success(Q(1), n) == Q(1) for n in range(1, 10)), + "success_bounded_by_oracle": all(value <= q for value in successes), + "reused_label_score_exceeds_heldout": Q(1) - successes[1] == Q(3, 8), + "finite_plan_favors_one_label": plan["optimal_sample_counts"] == (1,), + "one_label_net_value": plan["optimal_value"] == Q(19, 32), + "finite_learning_gap_is_positive": (successes[1] - successes[0]) == Q(1, 8), + } + return { + "channel_accuracy": q, + "hidden_polarity_prior": (Q(1, 2), Q(1, 2)), + "sample_counts": samples, + "heldout_success": successes, + "unlimited_calibration_oracle_accuracy": q, + "memorized_training_label_score": Q(1), + "training_vs_heldout_gap_at_one_label": Q(1) - successes[1], + "plan": plan, + "checks": independent_checks, + "all_passed": all(independent_checks.values()), + "evidence_level": "algebraic_identity_and_finite_verified_example", + "real_agent_evidence": False, + "cryptographic_world_identified": False, + "theological_hypothesis_identified": False, + } diff --git a/tests/test_agency_persistence.py b/tests/test_agency_persistence.py new file mode 100644 index 00000000..207bad95 --- /dev/null +++ b/tests/test_agency_persistence.py @@ -0,0 +1,150 @@ +"""Independent exact controls for FAW-02. No model or judge is executed.""" + +from fractions import Fraction as Q + +import pytest + +from spiral_ln.agency_worlds import heldout_success +from spiral_ln.agency_persistence import ( + C_LABEL, Q_SIGNAL, epoch_metrics, fixed_label_regret_floor, fixture, + horizon_metrics, label_budget, optimal_epoch, prior_epoch_transfer, +) + + +def independent_majority_accuracy(q: Q, m: int) -> Q: + """Convolve independent Bernoulli noises; no binomial coefficients.""" + mass = [Q(1)] + for _ in range(m): + new = [Q(0)] * (len(mass)+1) + for successes, weight in enumerate(mass): + new[successes] += weight*(1-q) + new[successes+1] += weight*q + mass = new + return sum((v for k, v in enumerate(mass) if 2*k > m), Q(0)) + ( + Q(1, 2)*mass[m//2] if m % 2 == 0 else Q(0)) + + +@pytest.mark.parametrize("m", tuple(range(25))) +@pytest.mark.parametrize("q", (Q(1, 2), Q(2, 3), Q(3, 4), Q(4, 5), Q(1))) +def test_independent_convolution_agrees_with_closed_form(q, m): + alpha = independent_majority_accuracy(q, m) + assert heldout_success(q, m) == (1-q)+(2*q-1)*alpha + + +@pytest.mark.parametrize("t", (1, 2, 3, 4, 7, 8, 15, 16, 31, 32, 63, 64, 127, 128)) +def test_schedule_and_all_single_epoch_certificates(t): + stage = epoch_metrics(t) + assert label_budget(t) == 5*t.bit_length() + assert stage["calibration_labels"] == label_budget(t) + assert stage["independent_heldout_trials"] == t+1 + assert all(stage["certificate"].values()) + assert stage["net_baseline_gain"] > 0 + + +def test_first_epoch_receipt_and_cost_control(): + a = epoch_metrics(1) + assert a["polarity_recovery"] == Q(459, 512) + assert a["polarity_error"] == Q(53, 512) + assert a["heldout_success"] == Q(715, 1024) + assert a["net_baseline_gain"] == Q(123, 512) + assert epoch_metrics(2)["net_baseline_gain"] > 0 + # Worst-case analytic net lower bound becomes positive from t=3 onward. + assert a["net_lower_bound"] < 0 + assert epoch_metrics(3)["net_lower_bound"] == Q(3, 16) + + +def test_margin_monotonicity_for_all_larger_integer_epochs(): + # Exact induction: at each t->t+1, bit_length rises by at most one, + # hence 8(t-1)-5 bit_length(t) increases by at least three. + def margin(t): + return 8*(t-1)-5*t.bit_length() + assert margin(3) == 6 + for t in range(3, 1024): + assert margin(t+1)-margin(t) >= 3 + assert margin(1024) > 0 + + +@pytest.mark.parametrize("T", (1, 2, 3, 4, 8, 16, 32, 64)) +def test_horizon_aggregation_and_rate_certificates(T): + report = horizon_metrics(T) + assert all(report["certificates"].values()) + assert report["heldout_trials"] == T*(T+3)//2 + assert report["scheduled_calibration_labels"] <= 5*T*T.bit_length() + assert report["schedule_avg_oracle_regret"] <= Q(1, T+3) + assert report["optimized_avg_oracle_regret"] <= report["optimized_regret_bound_per_trial"] + assert report["optimized_net_gain_over_chance"] >= report["schedule_net_gain_over_chance"] + + +@pytest.mark.parametrize("t", (1, 2, 3, 4, 8, 16, 32, 64)) +def test_exact_cost_optimization(t): + chosen = optimal_epoch(t) + cap = label_budget(t) + assert chosen["selected_labels"] <= cap + assert chosen["selected_labels"] == min(chosen["equally_optimal_label_counts"]) + # Independent brute-force utility calculation from held-out probabilities. + for m in range(cap+1): + alternative = (t+1)*(heldout_success(Q_SIGNAL, m)-Q(1, 2))-m*C_LABEL + assert chosen["net_baseline_gain"] >= alternative + assert all(chosen["certificate"].values()) + # With a positive price, even label counts are dominated by previous odd. + assert chosen["selected_labels"] % 2 == 1 + + +@pytest.mark.parametrize("q", (Q(2, 3), Q(3, 4), Q(4, 5))) +@pytest.mark.parametrize("cap", (0, 1, 2, 4, 8, 16)) +def test_fixed_label_cap_has_strict_oracle_regret_floor(q, cap): + floor = fixed_label_regret_floor(q, cap) + assert floor > 0 + assert all(q-heldout_success(q, m) >= floor for m in range(cap+1)) + + +def test_transfer_control_and_feedback_sealing(): + assert prior_epoch_transfer(Q_SIGNAL, 1, True) == Q(5, 8) + assert prior_epoch_transfer(Q_SIGNAL, 1, False) == Q(1, 2) + assert prior_epoch_transfer(Q_SIGNAL, 0, True) == Q(1, 2) + assert prior_epoch_transfer(Q_SIGNAL, 8, False) == Q(1, 2) + assert heldout_success(Q(1, 2), 99) == Q(1, 2) + + +@pytest.mark.parametrize("bad", (0, -2, 1.5, True, False)) +def test_bad_epoch_rejected(bad): + with pytest.raises(ValueError): + label_budget(bad) + with pytest.raises(ValueError): + horizon_metrics(bad) + + +@pytest.mark.parametrize("bad", (Q(-1), Q(1, 2), Q(1), Q(3, 2), .75)) +def test_fixed_floor_domain_rejected(bad): + with pytest.raises(ValueError): + fixed_label_regret_floor(bad, 3) + + +@pytest.mark.parametrize("bad", (-1, True, 2.5)) +def test_bad_label_cap_rejected(bad): + with pytest.raises(ValueError): + fixed_label_regret_floor(Q_SIGNAL, bad) + + +def test_cost_and_type_controls(): + with pytest.raises(ValueError): + epoch_metrics(1, Q(-1)) + with pytest.raises(TypeError): + optimal_epoch(1, .01) + with pytest.raises(ValueError): + horizon_metrics(1, Q(-1)) + with pytest.raises(TypeError): + prior_epoch_transfer(Q_SIGNAL, 1, 0) + # Costs are accounted for: high costs can rationally suppress calibration. + assert optimal_epoch(1, Q(1))["selected_labels"] == 0 + assert optimal_epoch(1, Q(1))["net_baseline_gain"] == 0 + + +def test_fixture_metadata_and_exact_checks(): + report = fixture() + assert report["all_passed"] + assert all(report["checks"].values()) + assert report["theological_hypothesis_identified"] is False + assert report["empirical_agents_evaluated"] is False + assert report["public_key_cryptography_assumed"] is False + assert report["lean_formalized"] is False diff --git a/tests/test_agency_unknown.py b/tests/test_agency_unknown.py new file mode 100644 index 00000000..ac2cd28d --- /dev/null +++ b/tests/test_agency_unknown.py @@ -0,0 +1,217 @@ +"""Independent exact Bayes, policy enumeration, and impossibility tests for FAW-03.""" + +from fractions import Fraction as Q +from itertools import product + +import pytest + +from spiral_ln.agency_unknown import ( + DEFAULT_PRIOR, agreement_probability, after_pairs, fixed_budget_value, + fixture, identification_chebyshev_bound, identification_success, + one_label_posterior_invariant, solve_epochs, state, validate_prior, +) + +ALT_PRIOR = ((Q(1, 2), Q(1, 3)), (Q(3, 4), Q(1, 3)), (Q(1), Q(1, 3))) + + +def reference_mass(prior, observations): + """Weight each latent world by multiplying independent sample factors.""" + weights = {} + for q, prior_q in prior: + for theta in (0, 1): + w = prior_q/2 + for z in observations: + w *= q if z == theta else (1-q) + weights[q, theta] = w + evidence = sum(weights.values(), Q(0)) + return weights, evidence + + +def reference_prediction(prior, observations): + """Independent Bayes action using joint world enumeration, not state().""" + masses, evidence = reference_mass(prior, observations) + if evidence == 0: + return None + correct_if_equal = sum((w*(q if theta == 0 else 1-q) + for (q, theta), w in masses.items()), Q(0)) + return correct_if_equal >= evidence/2 + + +def reference_policy_expected_value(prior, trials, cap, cost, actions): + """Brute-force policies using full observation sequences and latent worlds. + + This deliberately evaluates every fixed-length noise path, even after the + policy stops; the unconsumed suffix marginalizes to one. This contrasts + with the normalized posterior Bellman recurrence in the module. + """ + expected = Q(0) + for (q, w_q), theta, observations in product(prior, (0, 1), product((0, 1), repeat=cap)): + w = w_q/2 + for z in observations: + w *= q if z == theta else (1-q) + depth = 0 + while depth < cap and actions.get(tuple(observations[:depth]), False): + depth += 1 + predict_equal = reference_prediction(prior, tuple(observations[:depth])) + assert predict_equal is not None + fresh_correct = (q if theta == 0 else 1-q) if predict_equal else ( + (1-q) if theta == 0 else q) + expected += w*(trials*(fresh_correct-Q(1, 2))-cost*depth) + return expected + + +@pytest.mark.parametrize("prior", (DEFAULT_PRIOR, ALT_PRIOR, ((Q(3, 4), Q(1)),))) +@pytest.mark.parametrize("observations", ((), (0,), (1,), (0,0), (0,1), (1,0), (1,1), (1,0,1))) +def test_joint_posteriors_agree_with_latent_world_enumeration(prior, observations): + weights, evidence = reference_mass(prior, observations) + if evidence == 0: + with pytest.raises(ValueError, match="probability zero"): + state(prior, observations.count(0), observations.count(1)) + return + learned = state(prior, observations.count(0), observations.count(1)) + for q, prob in learned["q_posterior"]: + expected = sum((weights[q, theta] for theta in (0, 1)), Q(0))/evidence + assert prob == expected + p0 = sum((w*(q if theta == 0 else 1-q) + for (q, theta), w in weights.items()), Q(0))/evidence + assert learned["next_zero_probability"] == p0 + assert learned["fresh_accuracy"] == max(p0, 1-p0) + assert learned["predict_flip"] == (p0 < Q(1, 2)) + assert learned["oracle_gap"] >= 0 + + +@pytest.mark.parametrize("prior", (DEFAULT_PRIOR, ALT_PRIOR, ((Q(1, 2),Q(1, 2)),(Q(3, 4),Q(1, 2))))) +def test_one_label_carries_zero_reliability_information(prior): + assert one_label_posterior_invariant(prior) + assert state(prior, 0, 0)["q_posterior"] == prior + + +@pytest.mark.parametrize("q", (Q(1, 2), Q(2, 3), Q(3, 4), Q(1))) +def test_pair_agreement_from_independent_noises(q): + exhaustive = sum((Q(1, 2)* + (q if z0 == theta else 1-q)* + (q if z1 == theta else 1-q) + for theta, z0, z1 in product((0, 1), repeat=3) if z0 == z1), Q(0)) + assert exhaustive == agreement_probability(q) + + +def test_two_labels_are_necessary_for_reliability_identification(): + assert state(DEFAULT_PRIOR, 1, 0)["q_posterior"] == DEFAULT_PRIOR + assert after_pairs(DEFAULT_PRIOR, 1, 0) == ( + (Q(1, 2), Q(1, 3)), (Q(1), Q(2, 3))) + assert after_pairs(DEFAULT_PRIOR, 0, 1) == ( + (Q(1, 2), Q(1)),) + assert state(DEFAULT_PRIOR, 1, 1)["q_posterior"][-1][1] == 0 + + +@pytest.mark.parametrize("trials", (0, 1, 2, 5, 12)) +@pytest.mark.parametrize("cost", (Q(0), Q(1, 16), Q(1, 4), Q(1))) +@pytest.mark.parametrize("prior", (DEFAULT_PRIOR, ALT_PRIOR)) +def test_bellman_matches_complete_binary_policy_enumeration(trials, cost, prior): + cap = 2 + root = solve_epochs(prior, (trials,), (cap,), (cost,)) + candidates = [] + for b_root, b0, b1 in product((False, True), repeat=3): + policy = {(): b_root, (0,): b0, (1,): b1} + candidates.append(reference_policy_expected_value(prior, trials, cap, cost, policy)) + assert root["value_over_chance"] == max(candidates) + assert root["value_identity"] + assert root["expected_oracle_regret"] >= 0 + + +@pytest.mark.parametrize("m", range(5)) +@pytest.mark.parametrize("prior", (DEFAULT_PRIOR, ALT_PRIOR)) +def test_fixed_budget_matches_direct_exhaustive_policy(prior, m): + always_buy = {obs: True for n in range(m) for obs in product((0, 1), repeat=n)} + expected = reference_policy_expected_value(prior, 7, m, Q(1, 8), always_buy) + assert expected == fixed_budget_value(prior, 7, m, Q(1, 8)) + + +def test_exploration_value_across_fresh_polarities(): + trials = (0,)+(6,)*12 + caps = (2,)+(1,)*12 + costs = (Q(1),)*13 + r = solve_epochs(DEFAULT_PRIOR, trials, caps, costs) + assert r["value_over_chance"] == 7 + assert r["first_stop_value"] == 6 + assert r["first_buy_value"] == 7 + assert r["first_action"] == "buy" + assert r["expected_gold_labels"] == 11 + assert r["expected_heldout_correct"] == 54 + assert r["expected_oracle_correct"] == 54 + assert r["expected_label_cost"] == 11 + assert r["value_identity"] + # With only one label in the preliminary epoch, q is unlearnable. + single = solve_epochs(DEFAULT_PRIOR, trials, (1,)+(1,)*12, costs) + assert single["first_action"] == "stop" + assert single["value_over_chance"] == 6 + # Removing future episodes also removes the reason to experiment. + only_audit = solve_epochs(DEFAULT_PRIOR, (0,), (2,), (Q(1),)) + assert only_audit["first_action"] == "stop" + assert only_audit["value_over_chance"] == 0 + + +@pytest.mark.parametrize("true_q", (Q(1, 2), Q(1))) +@pytest.mark.parametrize("pairs", (1, 2, 3, 4, 8, 16, 32)) +def test_reliability_identification_and_exact_chebyshev(true_q, pairs): + success = identification_success(DEFAULT_PRIOR, true_q, pairs) + upper = identification_chebyshev_bound(DEFAULT_PRIOR, true_q, pairs) + assert 0 <= success <= 1 + assert 1-success <= upper + if true_q == 1: + assert success == 1 + + +def test_identification_consistency_and_zero_one_boundaries(): + assert identification_success(DEFAULT_PRIOR, Q(1, 2), 2) == Q(3, 4) + assert identification_success(DEFAULT_PRIOR, Q(1, 2), 3) == Q(7, 8) + assert identification_success(DEFAULT_PRIOR, Q(1, 2), 16) > Q(98, 100) + assert agreement_probability(Q(1, 2)) == Q(1, 2) + assert agreement_probability(Q(1)) == 1 + assert fixed_budget_value(DEFAULT_PRIOR, 0, 0, Q(1)) == 0 + + +@pytest.mark.parametrize("bad", ((), ((Q(1, 2),Q(1, 4)),), + ((Q(1), Q(1, 2)),(Q(1, 2),Q(1, 2))), + ((Q(1, 4), Q(1)),), + ((Q(3, 4), Q(0)),(Q(1),Q(1))), + ((Q(3, 4), Q(1, 2)),(Q(3, 4),Q(1, 2))))) +def test_invalid_priors_rejected(bad): + with pytest.raises(ValueError): + validate_prior(bad) + + +def test_input_failures_and_impossible_observations(): + with pytest.raises(TypeError): + validate_prior(((Q(3, 4), 1.0),)) + with pytest.raises(ValueError): + state(((Q(1), Q(1)),), 1, 1) + with pytest.raises(ValueError): + solve_epochs(DEFAULT_PRIOR, (), (), ()) + with pytest.raises(ValueError): + solve_epochs(DEFAULT_PRIOR, (1, 2), (1,), (Q(1),Q(1))) + with pytest.raises(ValueError): + solve_epochs(DEFAULT_PRIOR, (2,), (-1,), (Q(1),)) + with pytest.raises(ValueError): + solve_epochs(DEFAULT_PRIOR, (2,), (1,), (Q(-1),)) + with pytest.raises(TypeError): + solve_epochs(DEFAULT_PRIOR, (2,), (1,), (0.1,)) + with pytest.raises(ValueError): + after_pairs(((Q(1), Q(1)),), 0, 1) + with pytest.raises(ValueError): + identification_chebyshev_bound(DEFAULT_PRIOR, Q(1), 0) + with pytest.raises(ValueError): + identification_success(DEFAULT_PRIOR, Q(3, 4), 2) + with pytest.raises(ValueError): + identification_chebyshev_bound(((Q(3,4),Q(1)),), Q(3,4), 2) + + +def test_fixture_all_claims_exact(): + r = fixture() + assert r["all_passed"] + assert all(r["checks"].values()) + assert len(r["checks"]) >= 14 + assert r["real_agent_evidence"] is False + assert r["theological_hypothesis_identified"] is False + assert r["cryptographic_world_identified"] is False + assert r["lean_formalized"] is False diff --git a/tests/test_agency_worlds.py b/tests/test_agency_worlds.py new file mode 100644 index 00000000..d2bffade --- /dev/null +++ b/tests/test_agency_worlds.py @@ -0,0 +1,79 @@ +"""Exact tests of the finite agency witness; no empirical model invocation.""" + +from fractions import Fraction as Q + +import pytest + +from spiral_ln.agency_worlds import ( + calibration_accuracy, enumerate_heldout_success, fixture, + heldout_success, net_value, optimal_calibration, +) + + +@pytest.mark.parametrize("q", (Q(1, 2), Q(2, 3), Q(3, 4), Q(1))) +@pytest.mark.parametrize("samples", range(9)) +def test_formula_matches_independent_enumeration(q, samples): + assert heldout_success(q, samples) == enumerate_heldout_success(q, samples) + + +def test_heldout_learning_and_always_holdout(): + assert [heldout_success(Q(3, 4), n) for n in range(6)] == [ + Q(1, 2), Q(5, 8), Q(5, 8), Q(43, 64), Q(43, 64), Q(715, 1024), + ] + assert calibration_accuracy(Q(3, 4), 0) == Q(1, 2) + assert calibration_accuracy(Q(3, 4), 1) == Q(3, 4) + assert calibration_accuracy(Q(3, 4), 3) == Q(27, 32) + + +def test_degenerate_channels(): + for samples in range(11): + assert heldout_success(Q(1, 2), samples) == Q(1, 2) + assert heldout_success(Q(1), samples) == (Q(1, 2) if samples == 0 else Q(1)) + + +def test_agent_choice_is_cost_sensitive(): + q = Q(3, 4) + costly = optimal_calibration(q, 5, Q(1, 32)) + assert costly["optimal_sample_counts"] == (1,) + assert costly["optimal_value"] == Q(19, 32) + free = optimal_calibration(q, 5, Q(0)) + assert free["optimal_sample_counts"] == (5,) + assert free["optimal_value"] == Q(715, 1024) + assert net_value(q, 1, Q(1, 32)) > net_value(q, 0, Q(1, 32)) + + +def test_ties_and_zero_budget(): + assert optimal_calibration(Q(1, 2), 3, Q(0))["optimal_sample_counts"] == (0, 1, 2, 3) + assert optimal_calibration(Q(3, 4), 0, Q(1, 32))["optimal_sample_counts"] == (0,) + + +@pytest.mark.parametrize("bad", (Q(-1), Q(0), Q(2, 5), Q(5, 4))) +def test_probability_validation(bad): + with pytest.raises(ValueError): + heldout_success(bad, 1) + + +@pytest.mark.parametrize("bad", (-1, 1.0, True)) +def test_sample_validation(bad): + with pytest.raises(ValueError): + calibration_accuracy(Q(3, 4), bad) + + +def test_requires_rational_inputs(): + with pytest.raises(TypeError): + heldout_success(.75, 1) + with pytest.raises(TypeError): + net_value(Q(3, 4), 1, .1) + with pytest.raises(ValueError): + optimal_calibration(Q(3, 4), 3, Q(-1)) + + +def test_receipt_fixture_has_all_checks_true(): + report = fixture() + assert report["all_passed"] + assert all(value is True for value in report["checks"].values()) + assert report["memorized_training_label_score"] == Q(1) + assert report["training_vs_heldout_gap_at_one_label"] == Q(3, 8) + assert report["real_agent_evidence"] is False + assert report["cryptographic_world_identified"] is False + assert report["theological_hypothesis_identified"] is False