diff --git a/output/evaluation_scouting_value/scout01_dev_v1.json b/output/evaluation_scouting_value/scout01_dev_v1.json new file mode 100644 index 00000000..f1203b3f --- /dev/null +++ b/output/evaluation_scouting_value/scout01_dev_v1.json @@ -0,0 +1,543 @@ +{ + "case_records_sha256": "c6700f9b65b98b383bfe4cf1b340d40f557a7a3486a839433c1a2e084da93675", + "cases": [ + { + "case_id": "cheap", + "grader": { + "action_values": { + "commit_left": "1/2", + "commit_right": "1/2", + "scout": "7/10" + }, + "case_id": "cheap", + "gross_information_value": "3/10", + "optimal_actions": [ + "scout" + ], + "policies": { + "always_commit": { + "action": "commit_left", + "regret": "1/5" + }, + "always_scout": { + "action": "scout", + "regret": "0" + }, + "cue_following": { + "action": "commit_left", + "regret": "1/5" + }, + "double_count_relays": { + "action": "scout", + "regret": "0" + }, + "exact": { + "action": "scout", + "regret": "0" + } + }, + "posterior_right": "1/2", + "root_id": "scout-cost-001" + }, + "public_task_sha256": "c1986650deb625427b20fb751c55fa9476a13da85996aacaa93bb91f51f0e62b", + "root_id": "scout-cost-001", + "split": "dev" + }, + { + "case_id": "break_even", + "grader": { + "action_values": { + "commit_left": "1/2", + "commit_right": "1/2", + "scout": "1/2" + }, + "case_id": "break_even", + "gross_information_value": "3/10", + "optimal_actions": [ + "commit_left", + "commit_right", + "scout" + ], + "policies": { + "always_commit": { + "action": "commit_left", + "regret": "0" + }, + "always_scout": { + "action": "scout", + "regret": "0" + }, + "cue_following": { + "action": "commit_left", + "regret": "0" + }, + "double_count_relays": { + "action": "commit_left", + "regret": "0" + }, + "exact": { + "action": "commit_left", + "regret": "0" + } + }, + "posterior_right": "1/2", + "root_id": "scout-cost-001" + }, + "public_task_sha256": "89b32b7c2ee322f5679eab72dd48976deda124193894c2961e3bd1b433af6d6a", + "root_id": "scout-cost-001", + "split": "dev" + }, + { + "case_id": "expensive", + "grader": { + "action_values": { + "commit_left": "1/2", + "commit_right": "1/2", + "scout": "2/5" + }, + "case_id": "expensive", + "gross_information_value": "3/10", + "optimal_actions": [ + "commit_left", + "commit_right" + ], + "policies": { + "always_commit": { + "action": "commit_left", + "regret": "0" + }, + "always_scout": { + "action": "scout", + "regret": "1/10" + }, + "cue_following": { + "action": "commit_left", + "regret": "0" + }, + "double_count_relays": { + "action": "commit_left", + "regret": "0" + }, + "exact": { + "action": "commit_left", + "regret": "0" + } + }, + "posterior_right": "1/2", + "root_id": "scout-cost-001" + }, + "public_task_sha256": "85edca0a11abd88e9195728a02b3f581f9f36917d372bb19659738fea362f86c", + "root_id": "scout-cost-001", + "split": "dev" + }, + { + "case_id": "cue_conflict", + "grader": { + "action_values": { + "commit_left": "1/5", + "commit_right": "4/5", + "scout": "7/10" + }, + "case_id": "cue_conflict", + "gross_information_value": "0", + "optimal_actions": [ + "commit_right" + ], + "policies": { + "always_commit": { + "action": "commit_right", + "regret": "0" + }, + "always_scout": { + "action": "scout", + "regret": "1/10" + }, + "cue_following": { + "action": "commit_left", + "regret": "3/5" + }, + "double_count_relays": { + "action": "commit_right", + "regret": "0" + }, + "exact": { + "action": "commit_right", + "regret": "0" + } + }, + "posterior_right": "4/5", + "root_id": "cue-trap-002" + }, + "public_task_sha256": "0c30cc6316cf9322457234a594b1ef1ba6ff737a0a17c91804565bc78b9ad3ad", + "root_id": "cue-trap-002", + "split": "dev" + }, + { + "case_id": "cosmetic_cue", + "grader": { + "action_values": { + "commit_left": "1/5", + "commit_right": "4/5", + "scout": "7/10" + }, + "case_id": "cosmetic_cue", + "gross_information_value": "0", + "optimal_actions": [ + "commit_right" + ], + "policies": { + "always_commit": { + "action": "commit_right", + "regret": "0" + }, + "always_scout": { + "action": "scout", + "regret": "1/10" + }, + "cue_following": { + "action": "commit_right", + "regret": "0" + }, + "double_count_relays": { + "action": "commit_right", + "regret": "0" + }, + "exact": { + "action": "commit_right", + "regret": "0" + } + }, + "posterior_right": "4/5", + "root_id": "cue-trap-002" + }, + "public_task_sha256": "0a1e42c1f18274c6df09d7a5808e6b490efaf3a7cc2c6e567503d5e1cdc61332", + "root_id": "cue-trap-002", + "split": "dev" + }, + { + "case_id": "shared_relays", + "grader": { + "action_values": { + "commit_left": "3/5", + "commit_right": "2/5", + "scout": "7/10" + }, + "case_id": "shared_relays", + "gross_information_value": "1/5", + "optimal_actions": [ + "scout" + ], + "policies": { + "always_commit": { + "action": "commit_left", + "regret": "1/10" + }, + "always_scout": { + "action": "scout", + "regret": "0" + }, + "cue_following": { + "action": "commit_left", + "regret": "1/10" + }, + "double_count_relays": { + "action": "commit_left", + "regret": "1/10" + }, + "exact": { + "action": "scout", + "regret": "0" + } + }, + "posterior_right": "2/5", + "root_id": "provenance-003" + }, + "public_task_sha256": "f4ca67efdb835ec311d856309df84a3bbb4d814ca591ca9a1fde8c19a196221b", + "root_id": "provenance-003", + "split": "dev" + }, + { + "case_id": "cosmetic_cue", + "grader": { + "action_values": { + "commit_left": "3/5", + "commit_right": "2/5", + "scout": "7/10" + }, + "case_id": "cosmetic_cue", + "gross_information_value": "1/5", + "optimal_actions": [ + "scout" + ], + "policies": { + "always_commit": { + "action": "commit_left", + "regret": "1/10" + }, + "always_scout": { + "action": "scout", + "regret": "0" + }, + "cue_following": { + "action": "commit_right", + "regret": "3/10" + }, + "double_count_relays": { + "action": "commit_left", + "regret": "1/10" + }, + "exact": { + "action": "scout", + "regret": "0" + } + }, + "posterior_right": "2/5", + "root_id": "provenance-003" + }, + "public_task_sha256": "ca139e67213d2b118e9507f2178063f8b24fb1695fdf941fd991b1037ec30b9c", + "root_id": "provenance-003", + "split": "dev" + }, + { + "case_id": "independent_witnesses", + "grader": { + "action_values": { + "commit_left": "27/35", + "commit_right": "8/35", + "scout": "7/10" + }, + "case_id": "independent_witnesses", + "gross_information_value": "1/35", + "optimal_actions": [ + "commit_left" + ], + "policies": { + "always_commit": { + "action": "commit_left", + "regret": "0" + }, + "always_scout": { + "action": "scout", + "regret": "1/14" + }, + "cue_following": { + "action": "commit_left", + "regret": "0" + }, + "double_count_relays": { + "action": "commit_left", + "regret": "0" + }, + "exact": { + "action": "commit_left", + "regret": "0" + } + }, + "posterior_right": "8/35", + "root_id": "provenance-003" + }, + "public_task_sha256": "b0fc40faa4ff72be74934dcaff91d395b81d8db06238cb19c992eca9e33a2dc3", + "root_id": "provenance-003", + "split": "dev" + }, + { + "case_id": "scout_available", + "grader": { + "action_values": { + "commit_left": "1/2", + "commit_right": "1/2", + "scout": "7/10" + }, + "case_id": "scout_available", + "gross_information_value": "3/10", + "optimal_actions": [ + "scout" + ], + "policies": { + "always_commit": { + "action": "commit_left", + "regret": "1/5" + }, + "always_scout": { + "action": "scout", + "regret": "0" + }, + "cue_following": { + "action": "commit_left", + "regret": "1/5" + }, + "double_count_relays": { + "action": "scout", + "regret": "0" + }, + "exact": { + "action": "scout", + "regret": "0" + } + }, + "posterior_right": "1/2", + "root_id": "access-004" + }, + "public_task_sha256": "cd23fba21bb7f6d4576720643fb5a7d0e354e4c5268d7a677f1a7527f9f5923e", + "root_id": "access-004", + "split": "dev" + }, + { + "case_id": "scout_unavailable", + "grader": { + "action_values": { + "commit_left": "1/2", + "commit_right": "1/2" + }, + "case_id": "scout_unavailable", + "gross_information_value": "0", + "optimal_actions": [ + "commit_left", + "commit_right" + ], + "policies": { + "always_commit": { + "action": "commit_left", + "regret": "0" + }, + "always_scout": { + "action": "commit_left", + "regret": "0" + }, + "cue_following": { + "action": "commit_left", + "regret": "0" + }, + "double_count_relays": { + "action": "commit_left", + "regret": "0" + }, + "exact": { + "action": "commit_left", + "regret": "0" + } + }, + "posterior_right": "1/2", + "root_id": "access-004" + }, + "public_task_sha256": "10ca9d554d609d1098518ceeb9d8b3c84b7534e9667a12450e932307a5d9e085", + "root_id": "access-004", + "split": "dev" + }, + { + "case_id": "informative_scout", + "grader": { + "action_values": { + "commit_left": "1/2", + "commit_right": "1/2", + "scout": "7/10" + }, + "case_id": "informative_scout", + "gross_information_value": "3/10", + "optimal_actions": [ + "scout" + ], + "policies": { + "always_commit": { + "action": "commit_left", + "regret": "1/5" + }, + "always_scout": { + "action": "scout", + "regret": "0" + }, + "cue_following": { + "action": "commit_left", + "regret": "1/5" + }, + "double_count_relays": { + "action": "scout", + "regret": "0" + }, + "exact": { + "action": "scout", + "regret": "0" + } + }, + "posterior_right": "1/2", + "root_id": "signal-quality-005" + }, + "public_task_sha256": "c1986650deb625427b20fb751c55fa9476a13da85996aacaa93bb91f51f0e62b", + "root_id": "signal-quality-005", + "split": "dev" + }, + { + "case_id": "uninformative_scout", + "grader": { + "action_values": { + "commit_left": "1/2", + "commit_right": "1/2", + "scout": "2/5" + }, + "case_id": "uninformative_scout", + "gross_information_value": "0", + "optimal_actions": [ + "commit_left", + "commit_right" + ], + "policies": { + "always_commit": { + "action": "commit_left", + "regret": "0" + }, + "always_scout": { + "action": "scout", + "regret": "1/10" + }, + "cue_following": { + "action": "commit_left", + "regret": "0" + }, + "double_count_relays": { + "action": "commit_left", + "regret": "0" + }, + "exact": { + "action": "commit_left", + "regret": "0" + } + }, + "posterior_right": "1/2", + "root_id": "signal-quality-005" + }, + "public_task_sha256": "82532de12038d3b99a3c91720bd3986ef9382993852c10752ab1be82ff96ea43", + "root_id": "signal-quality-005", + "split": "dev" + } + ], + "checks": { + "always_scout_control_fails": true, + "cosmetic_sham_invariant": true, + "cost_point_four_commit": true, + "cost_point_one_scout": true, + "cost_point_three_exact_tie": true, + "cue_control_fails": true, + "distinct_root_count_five": true, + "double_count_control_fails": true, + "eight_views_two_roots": true, + "exact_policy_zero_regret": true, + "gross_value_three_tenths": true, + "independent_enumerator_agrees": true, + "independent_reports_commit": true, + "public_omits_oracle": true, + "shared_report_scout": true, + "twelve_development_cases": true + }, + "development_cases": 12, + "development_views": 8, + "evidence_level": "finite synthetic development; unsealed", + "heldout_sealed": false, + "independent_generator_roots": 5, + "schema": "scout01-dev-v1", + "source_sha256": { + "paper/scout01_information_purchase.md": "035f5a1c94d4c0dd84e19c9389300d4e5e9bdb761d5e03b373af082454d77651", + "scripts/verify_evaluation_scouting_value.py": "cfc1521fd6451cf9a42b8ab889695008bc04461a2a019ffd5f2a2ff504d9e504", + "src/spiral_ln/evaluation_scouting_value.py": "b2812f41fe9d98a58468ec42ae5ce7fc28def6a20b119829e68f998ecde1b286", + "tests/test_evaluation_scouting_value.py": "fb57f536bba9a40b862375083137f730289b857a8dc53bca3fa5fe1325707fc9" + } +} diff --git a/paper/scout01_information_purchase.md b/paper/scout01_information_purchase.md new file mode 100644 index 00000000..668df617 --- /dev/null +++ b/paper/scout01_information_purchase.md @@ -0,0 +1,57 @@ +# SCOUT-01: purchase information when it changes the decision + +**Evidence:** Exact rational algebra for the declared finite binary signal model, independently enumerated on development grids. Five hand-authored source roots and twelve development cases are **diagnostics only**. No student learning, native game transfer, sealed evaluation or neural mechanism result is asserted. + +## Game and value + +A hidden good route G in {left,right} has prior P(G=right)=p. A direct choice earns 1 for the good route and 0 otherwise. Before choosing, the actor may purchase one conditionally independent binary scout signal S with fidelity q, at nonnegative cost c. The scout arrives before the final route choice. The actor has enough turns for scouting only when `scout_available` is true. + +With p denoting the posterior **after existing public reports**, the first-action values are + +``` +V(commit_left) = 1 - p +V(commit_right) = p +V(scout) = max(p*q, (1-p)*(1-q)) + + max(p*(1-q), (1-p)*q) - c +``` + +The two maxima are the optimal decisions in the two mutually exclusive scout observation branches, with the joint observation probabilities already included. If scout is unavailable it is an illegal action. The gross value of information is V(scout at c=0) - max(p,1-p); the optimal first move is any action attaining the maximum value. Ties are preserved as valid optimal actions. For p=1/2 and q=4/5, the gross information value is 3/10; c=1/10 yields V(scout)=7/10 versus 1/2 for a commitment. At c=3/10 all three first moves tie. At c=2/5 either commitment is optimal, with scout worth 2/5. + +## Report ancestry and causal edits + +Every published report declares `source_root`, its direction, and exact reliability. Repeating a report from one root relays **one noisy draw**. Distinct roots correspond to conditionally independent draws given G. Conflicting reports or reliabilities under the same root are invalid input. This is the actor-visible observation model: the environment privately grades from the same public information and never exposes the hidden route or gold action in the actor task. + +Three identical left-favoring reports of reliability 3/5, all sourced from one witness, yield P(G=right)=2/5. Their posterior-optimal move is to scout at cost 1/10: V(scout)=7/10, V(commit_left)=3/5. Reassigning the reports to three independent witnesses changes P(G=right) to 8/35. Now V(commit_left)=27/35 exceeds V(scout)=7/10. A baseline that treats relays as independent suffers exact decision regret 1/10 on the shared-root case. + +`cue_favors_right` is an attractive surface clue with no specified information about G. Flipping it is a sham and must preserve the oracle values. A conflicting informative report of reliability 4/5 favoring right makes a cue-following left commitment suffer regret 3/5. Changing the scout's cost, fidelity or availability can change the legal optimal first action. + +## Playable state and integrity + +`realized_reward` is a small deterministic simulator. Its owner supplies a hidden route and, following the scout purchase, the actually sampled report; the second decision is made from the updated posterior. `enumerated_expected_reward` independently averages the true route and scout branches and must equal the first-action Bellman value for every legal action, including ties and impossible observations. All math uses `Fraction`. + +`development_cases` is a frozen 5-root / 12-case diagnostic grid. `development_views` emits play, causal revise, cosmetic hold-steady and repair views for two roots, with `parent_root` retained by the grader. These are **not** twelve or eight independent tasks. Training episodes built from the same source family, its alternative renderings, and all counterfactuals must share one train/dev/confirmation partition. These public development examples belong to `dev`. Future sealed task families remain outside the repository and should be registered before evaluation. + +A model reports its first action and belief about the right route. Score action regret from its public posterior-information state, and belief calibration separately against the ex ante public distribution or realized hidden draws. Regret is unaffected by whether a sound stochastic decision happens to lose on one play. Source-root custody belongs to the grader; provenance ids of reports must remain visible to the actor. `public_task` omits the oracle values and generator root id. A render adapter must pass only its `public_task` payload, never a whole linked-view or grader record. + +## Weak players and acceptance gates + +`cue_following` tracks the irrelevant surface cue. `always_scout` pays for a report even when it costs too much or provides redundant evidence. `double_count_relays` mistakes three retellings for three independent sources. `always_commit` never buys information. `exact` is a transparent structural ceiling; it is a privileged algorithmic controller, not a learned agent. Baseline failures and cosmetic invariances are explicit source-hashed verifier checks. + +This small preflight has 5 independent synthetic generator roots, 12 correlated cases and 8 linked views. Planned and actual trained-model comparisons are **zero**. Minimum meaningful downstream effect and matched neural sham floor are **unmeasured**. The evaluation therefore remains `PILOT_ONLY` under EvalMath's root-level power skill. Any proposed 50-family trained-student test requires independent family-level measurement, a preregistered meaningful performance improvement, a matched sham pilot, and a prospective sealed split. Match student initialization, tokens, verifier calls and frozen policies; account separately for advisory inference cost. Report native game returns when an exact oracle does not apply. Prevent cosmetic rewrites from earning independent-root credit. + +## DataGoblin integration contract + +- Export actor-visible `public_task` and separately store `private_grade`, `root_id`, `case_id`, `split`, and exact source hashes in the grader archive. `legal_actions` includes `scout` only when permitted. +- On `scout`, sample one fresh independent report from the declared signal law, expose it, debit the cost, and make the final commitment. Verify that action values and any training target use the **pre-action** information state. +- Retain all four linked views under the same parent root; preserve the bad move in repair. Train candidates must remain `training_ready=false` until source-rights, lineage and transfer checks finish. +- Later render the same math as a route-building game, a council witness hearing, and a cooperative message game. The current `cooperative` label is a narrative fixture only; no teammate message protocol or partner-policy transfer has been evaluated. + +### Reproduce + +```bash +PYTHONPATH=src python -m unittest discover -s tests -p 'test_evaluation_scouting_value.py' -q +PYTHONPATH=src python scripts/verify_evaluation_scouting_value.py --output /tmp/scout01_dev_v1.json +PYTHONPATH=src python scripts/check_receipts.py --only scouting_value +``` + +References: DataGoblin AGN-01 PR #50; GPTStoryworld HGW-05 causal benchmark; EvalMath HG-04 PR #41, HG-09 PR #48, and FSI-01. Exact development cases, source hashes and baseline regrets live in the generated receipt. diff --git a/scripts/check_receipts.py b/scripts/check_receipts.py index 69c5079f..f8ca1c88 100644 --- a/scripts/check_receipts.py +++ b/scripts/check_receipts.py @@ -29,6 +29,8 @@ "output/evaluation_frozen_evidence/fre01_v1.json", [], False), "finite_sample": ("scripts/verify_evaluation_finite_sample.py", "output/evaluation_finite_sample/fsi01_v0_1.json", [], False), + "scouting_value": ("scripts/verify_evaluation_scouting_value.py", + "output/evaluation_scouting_value/scout01_dev_v1.json", [], False), "bpd": ("scripts/verify_evaluation_bpd.py", "output/evaluation_bpd/bpd_01.json", [], False), "irc02": ("scripts/verify_interface_relative_compactification.py", diff --git a/scripts/verify_evaluation_scouting_value.py b/scripts/verify_evaluation_scouting_value.py new file mode 100644 index 00000000..edc41fa5 --- /dev/null +++ b/scripts/verify_evaluation_scouting_value.py @@ -0,0 +1,108 @@ +"""Recompute the source-hashed SCOUT-01 development receipt, without network/model calls.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import sys +from fractions import Fraction as F +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "src")) +from spiral_ln import evaluation_scouting_value as s # noqa: E402 + +SOURCES = ( + "src/spiral_ln/evaluation_scouting_value.py", + "tests/test_evaluation_scouting_value.py", + "scripts/verify_evaluation_scouting_value.py", + "paper/scout01_information_purchase.md", +) + + +def canonical_json(obj: object) -> bytes: + return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("utf-8") + + +def sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def receipt() -> dict: + worlds = s.development_cases() + cases = {(w.root_id, w.case_id): w for w in worlds} + views = s.development_views() + cheap = cases[("scout-cost-001", "cheap")] + tie = cases[("scout-cost-001", "break_even")] + expensive = cases[("scout-cost-001", "expensive")] + shared = cases[("provenance-003", "shared_relays")] + independent = cases[("provenance-003", "independent_witnesses")] + cue = cases[("cue-trap-002", "cue_conflict")] + checks = { + "distinct_root_count_five": len({w.root_id for w in worlds}) == 5, + "twelve_development_cases": len(worlds) == 12, + "eight_views_two_roots": len(views) == 8 and len({v["parent_root"] for v in views}) == 2, + "cost_point_one_scout": s.values(cheap)[s.SCOUT] == F(7, 10) + and s.optimal_actions(cheap) == (s.SCOUT,), + "cost_point_three_exact_tie": s.optimal_actions(tie) == s.ACTIONS, + "cost_point_four_commit": s.optimal_actions(expensive) == (s.LEFT, s.RIGHT), + "gross_value_three_tenths": s.information_value(cheap) == F(3, 10), + "shared_report_scout": s.posterior_right(shared) == F(2, 5) + and s.optimal_actions(shared) == (s.SCOUT,), + "independent_reports_commit": s.posterior_right(independent) == F(8, 35) + and s.optimal_actions(independent) == (s.LEFT,), + "double_count_control_fails": s.regret(shared, s.policy_action(shared, "double_count_relays")) == F(1, 10), + "cue_control_fails": s.regret(cue, s.policy_action(cue, "cue_following")) == F(3, 5), + "always_scout_control_fails": s.regret(expensive, s.SCOUT) == F(1, 10), + "cosmetic_sham_invariant": all( + s.values(cases[(root, original)]) == s.values(cases[(root, "cosmetic_cue")]) + for root, original in (("cue-trap-002", "cue_conflict"), + ("provenance-003", "shared_relays")) + ), + "independent_enumerator_agrees": all( + s.enumerated_expected_reward(w, a) == value + for w in worlds for a, value in s.values(w).items() + ), + "exact_policy_zero_regret": all(s.regret(w, s.policy_action(w, "exact")) == 0 for w in worlds), + "public_omits_oracle": all( + not {"root_id", "case_id", "posterior_right", "optimal_actions", "action_values"} + .intersection(s.public_task(w)) for w in worlds + ), + } + case_records = [] + for w in worlds: + grade = s.private_grade(w) + case_records.append({ + "root_id": w.root_id, "case_id": w.case_id, "split": "dev", + "public_task_sha256": sha256(canonical_json(s.public_task(w))), + "grader": grade, + }) + cases_hash = sha256(canonical_json(case_records)) + return { + "schema": "scout01-dev-v1", "evidence_level": "finite synthetic development; unsealed", + "heldout_sealed": False, + "independent_generator_roots": len({w.root_id for w in worlds}), + "development_cases": len(worlds), + "development_views": len(views), + "case_records_sha256": cases_hash, + "source_sha256": {path: sha256((ROOT / path).read_bytes()) for path in SOURCES}, + "checks": checks, + "cases": case_records, + } + + +def main() -> int: + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--output", type=Path, default=ROOT / "output/evaluation_scouting_value/scout01_dev_v1.json") + args = p.parse_args() + result = receipt() + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8") + print(f"SCOUT-01: {sum(result['checks'].values())}/{len(result['checks'])} checks, " + f"{result['independent_generator_roots']} development roots, " + f"{result['development_cases']} cases, {result['development_views']} linked views") + return 0 if all(result["checks"].values()) else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/spiral_ln/evaluation_scouting_value.py b/src/spiral_ln/evaluation_scouting_value.py new file mode 100644 index 00000000..76337442 --- /dev/null +++ b/src/spiral_ln/evaluation_scouting_value.py @@ -0,0 +1,269 @@ +"""SCOUT-01: exact, finite information-purchase decisions with source provenance. + +Development-only synthetic worlds. Signals with the same source_root are the SAME +conditional draw; distinct roots are independent conditional on the good route. +All expectations use rational arithmetic from the actor's information state. +""" +from __future__ import annotations + +from dataclasses import dataclass, replace +from fractions import Fraction +from typing import Iterable + +LEFT, RIGHT, SCOUT = "commit_left", "commit_right", "scout" +ACTIONS = (LEFT, RIGHT, SCOUT) + + +@dataclass(frozen=True) +class Report: + source_root: str + favors_right: bool + accuracy: Fraction + + def __post_init__(self) -> None: + if not self.source_root or type(self.favors_right) is not bool: + raise ValueError("a report needs a provenance root and binary signal") + if not isinstance(self.accuracy, Fraction) or not Fraction(1, 2) <= self.accuracy <= 1: + raise ValueError("accuracy must be a rational in [1/2, 1]") + + +@dataclass(frozen=True) +class World: + root_id: str + case_id: str + setting: str + cue_favors_right: bool + scout_cost: Fraction + scout_accuracy: Fraction = Fraction(4, 5) + prior_right: Fraction = Fraction(1, 2) + scout_available: bool = True + reports: tuple[Report, ...] = () + + def __post_init__(self) -> None: + if not self.root_id or not self.case_id or not self.setting: + raise ValueError("world requires root, case and setting") + if type(self.cue_favors_right) is not bool or type(self.scout_available) is not bool: + raise ValueError("binary cue and access are required") + if not isinstance(self.scout_cost, Fraction) or self.scout_cost < 0: + raise ValueError("scout cost must be a nonnegative rational") + if not isinstance(self.scout_accuracy, Fraction) or not Fraction(1, 2) <= self.scout_accuracy <= 1: + raise ValueError("scout accuracy must be a rational in [1/2, 1]") + if not isinstance(self.prior_right, Fraction) or not 0 <= self.prior_right <= 1: + raise ValueError("prior must be a rational probability") + if not isinstance(self.reports, tuple) or any(not isinstance(r, Report) for r in self.reports): + raise ValueError("reports must be a tuple of Report") + independent_reports(self.reports) + posterior_right(self) + + +def independent_reports(reports: Iterable[Report]) -> tuple[Report, ...]: + """Collapse relays; reject conflicting claims under one immutable source id.""" + seen: dict[str, Report] = {} + for report in reports: + prior = seen.get(report.source_root) + if prior is not None and prior != report: + raise ValueError("a source root cannot change its report or reliability") + seen[report.source_root] = report + return tuple(seen.values()) + + +def posterior_right(world: World, *, count_relays: bool = False) -> Fraction: + """Posterior with the independent-source assumption made explicit.""" + reports = world.reports if count_relays else independent_reports(world.reports) + right, left = world.prior_right, 1 - world.prior_right + for r in reports: + right *= r.accuracy if r.favors_right else 1 - r.accuracy + left *= 1 - r.accuracy if r.favors_right else r.accuracy + if right + left == 0: + raise ValueError("observations have zero probability under both routes") + return right / (right + left) + + +def action_values(belief_right: Fraction, cost: Fraction, accuracy: Fraction, + available: bool = True) -> dict[str, Fraction]: + if not 0 <= belief_right <= 1 or cost < 0 or not Fraction(1, 2) <= accuracy <= 1: + raise ValueError("invalid value-of-information inputs") + values = {LEFT: 1 - belief_right, RIGHT: belief_right} + if available: + # Marginalize the latent route, enumerate both possible scout reports, + # and make the optimal *second* choice after each report is observed. + values[SCOUT] = ( + max(belief_right * accuracy, (1 - belief_right) * (1 - accuracy)) + + max(belief_right * (1 - accuracy), (1 - belief_right) * accuracy) + - cost + ) + return values + + +def values(world: World) -> dict[str, Fraction]: + return action_values(posterior_right(world), world.scout_cost, + world.scout_accuracy, world.scout_available) + + +def optimal_actions(world: World) -> tuple[str, ...]: + payoffs = values(world) + optimum = max(payoffs.values()) + return tuple(a for a in ACTIONS if a in payoffs and payoffs[a] == optimum) + + +def information_value(world: World) -> Fraction: + """Gross value of a scout report before cost; 0 when scout is unavailable.""" + if not world.scout_available: + return Fraction(0) + p = posterior_right(world) + unconstrained = action_values(p, Fraction(0), world.scout_accuracy)[SCOUT] + return unconstrained - max(p, 1 - p) + + +def posterior_after_scout(p: Fraction, signal_right: bool, accuracy: Fraction) -> Fraction: + right = p * (accuracy if signal_right else 1 - accuracy) + left = (1 - p) * (1 - accuracy if signal_right else accuracy) + if right + left == 0: + raise ValueError("scout signal has zero probability") + return right / (right + left) + + +def second_choice(world: World, signal_right: bool) -> str: + belief = posterior_after_scout(posterior_right(world), signal_right, world.scout_accuracy) + return RIGHT if belief > Fraction(1, 2) else LEFT + + +def realized_reward(world: World, first_action: str, good_right: bool, + scout_signal_right: bool | None = None) -> Fraction: + """Deterministic simulator transition for an externally sampled hidden route/signal.""" + if type(good_right) is not bool: + raise ValueError("hidden route must be binary") + if first_action not in values(world): + raise ValueError("illegal first action") + if first_action == SCOUT: + if type(scout_signal_right) is not bool: + raise ValueError("a scout action requires the observed signal") + commit = second_choice(world, scout_signal_right) + return Fraction(int((commit == RIGHT) == good_right)) - world.scout_cost + if scout_signal_right is not None: + raise ValueError("a direct commit has no scout observation") + return Fraction(int((first_action == RIGHT) == good_right)) + + +def enumerated_expected_reward(world: World, first_action: str) -> Fraction: + """Independent brute-force oracle over latent route and scout signal.""" + p = posterior_right(world) + total = Fraction() + for good_right, mass in ((False, 1 - p), (True, p)): + if first_action == SCOUT: + for signal_right in (False, True): + likelihood = (world.scout_accuracy if signal_right == good_right + else 1 - world.scout_accuracy) + if mass * likelihood: + total += mass * likelihood * realized_reward(world, first_action, + good_right, signal_right) + else: + total += mass * realized_reward(world, first_action, good_right) + return total + + +def policy_action(world: World, policy: str) -> str: + if policy == "exact": + return optimal_actions(world)[0] + if policy == "cue_following": + return RIGHT if world.cue_favors_right else LEFT + if policy == "always_scout": + return SCOUT if world.scout_available else (RIGHT if world.cue_favors_right else LEFT) + if policy == "always_commit": + return RIGHT if posterior_right(world) > Fraction(1, 2) else LEFT + if policy == "double_count_relays": + p = posterior_right(world, count_relays=True) + payoffs = action_values(p, world.scout_cost, world.scout_accuracy, world.scout_available) + return next(a for a in ACTIONS if a in payoffs and payoffs[a] == max(payoffs.values())) + raise ValueError("unknown policy") + + +def regret(world: World, first_action: str) -> Fraction: + payoffs = values(world) + if first_action not in payoffs: + raise ValueError("illegal first action") + return max(payoffs.values()) - payoffs[first_action] + + +def public_task(world: World) -> dict: + """Actor-visible task: source lineage is visible; oracle/latent state omitted.""" + return { + "setting": world.setting, + "surface_cue_favors": "right" if world.cue_favors_right else "left", + "prior_good_route_right": str(world.prior_right), + "scout_cost": str(world.scout_cost), + "scout_accuracy": str(world.scout_accuracy), + "legal_actions": list(values(world)), + "reports": [ + {"source_root": r.source_root, + "favors": "right" if r.favors_right else "left", + "accuracy": str(r.accuracy)} for r in world.reports + ], + "decision": "Choose a first move. If scout, the game shows a fresh report before route commitment.", + } + + +def private_grade(world: World) -> dict: + payoffs = values(world) + return { + "root_id": world.root_id, + "case_id": world.case_id, + "posterior_right": str(posterior_right(world)), + "gross_information_value": str(information_value(world)), + "action_values": {k: str(v) for k, v in payoffs.items()}, + "optimal_actions": list(optimal_actions(world)), + "policies": {name: {"action": policy_action(world, name), + "regret": str(regret(world, policy_action(world, name)))} + for name in ("exact", "cue_following", "always_scout", + "always_commit", "double_count_relays")}, + } + + +def development_cases() -> tuple[World, ...]: + """Frozen tiny public development fixtures; five source roots, not N iid cases.""" + f = Fraction + cost = World("scout-cost-001", "cheap", "videogame", False, f(1, 10)) + cue = World("cue-trap-002", "cue_conflict", "videogame", False, f(1, 10), + reports=(Report("map-archive", True, f(4, 5)),)) + shared = World("provenance-003", "shared_relays", "storyworld", False, f(1, 10), + reports=tuple(Report("council-witness", False, f(3, 5)) for _ in range(3))) + independent = replace(shared, case_id="independent_witnesses", + reports=tuple(Report(f"witness-{i}", False, f(3, 5)) for i in range(3))) + access = World("access-004", "scout_available", "cooperative", False, f(1, 10)) + signal = World("signal-quality-005", "informative_scout", "videogame", False, f(1, 10)) + return ( + cost, + replace(cost, case_id="break_even", scout_cost=f(3, 10)), + replace(cost, case_id="expensive", scout_cost=f(2, 5)), + cue, + replace(cue, case_id="cosmetic_cue", cue_favors_right=True), + shared, + replace(shared, case_id="cosmetic_cue", cue_favors_right=True), + independent, + access, + replace(access, case_id="scout_unavailable", scout_available=False), + signal, + replace(signal, case_id="uninformative_scout", scout_accuracy=f(1, 2)), + ) + + +def development_views() -> list[dict]: + """Four linked training-design views; all stay development-only and root-joined.""" + cs = {w.case_id: w for w in development_cases() if w.root_id == "scout-cost-001"} + pr = {w.case_id: w for w in development_cases() if w.root_id == "provenance-003"} + packs = [ + (cs["cheap"], cs["expensive"], replace(cs["cheap"], case_id="cheap", + cue_favors_right=True), "cue_following"), + (pr["shared_relays"], pr["independent_witnesses"], pr["cosmetic_cue"], + "double_count_relays"), + ] + out = [] + for play, revision, sham, weak in packs: + for view, world in (("play", play), ("revise", revision), ("hold_steady", sham)): + out.append({"parent_root": play.root_id, "view": view, + "public_task": public_task(world), "grader_case_id": world.case_id}) + out.append({"parent_root": play.root_id, "view": "repair", + "public_task": public_task(play), + "recorded_bad_action": policy_action(play, weak), + "grader_case_id": play.case_id}) + return out diff --git a/tests/test_evaluation_scouting_value.py b/tests/test_evaluation_scouting_value.py new file mode 100644 index 00000000..f3bcb113 --- /dev/null +++ b/tests/test_evaluation_scouting_value.py @@ -0,0 +1,146 @@ +"""SCOUT-01 finite Bellman, provenance, weak-policy and custody checks.""" +from __future__ import annotations + +import unittest +from dataclasses import replace +from fractions import Fraction as F +from itertools import product + +from spiral_ln import evaluation_scouting_value as s + + +class ScoutingValueTests(unittest.TestCase): + def by_name(self, root, name): + return next(w for w in s.development_cases() if w.root_id == root and w.case_id == name) + + def test_cost_boundary_and_ties(self): + cheap = self.by_name("scout-cost-001", "cheap") + self.assertEqual(s.values(cheap), {s.LEFT: F(1, 2), s.RIGHT: F(1, 2), s.SCOUT: F(7, 10)}) + self.assertEqual(s.information_value(cheap), F(3, 10)) + self.assertEqual(s.optimal_actions(cheap), (s.SCOUT,)) + self.assertEqual(s.optimal_actions(self.by_name("scout-cost-001", "break_even")), s.ACTIONS) + expensive = self.by_name("scout-cost-001", "expensive") + self.assertEqual(s.optimal_actions(expensive), (s.LEFT, s.RIGHT)) + self.assertEqual(s.regret(expensive, s.SCOUT), F(1, 10)) + + def test_relay_collapse_and_independent_witness_flip(self): + repeated = self.by_name("provenance-003", "shared_relays") + separate = self.by_name("provenance-003", "independent_witnesses") + self.assertEqual(s.posterior_right(repeated), F(2, 5)) + self.assertEqual(s.posterior_right(separate), F(8, 35)) + self.assertEqual(s.posterior_right(repeated, count_relays=True), F(8, 35)) + self.assertEqual(s.optimal_actions(repeated), (s.SCOUT,)) + self.assertEqual(s.optimal_actions(separate), (s.LEFT,)) + self.assertEqual(s.policy_action(repeated, "double_count_relays"), s.LEFT) + self.assertEqual(s.regret(repeated, s.LEFT), F(1, 10)) + self.assertEqual(s.regret(separate, s.SCOUT), F(1, 14)) + + def test_cosmetic_sham_invariance(self): + for root, a, b in (("cue-trap-002", "cue_conflict", "cosmetic_cue"), + ("provenance-003", "shared_relays", "cosmetic_cue")): + x, y = self.by_name(root, a), self.by_name(root, b) + self.assertNotEqual(x.cue_favors_right, y.cue_favors_right) + self.assertEqual(s.values(x), s.values(y)) + self.assertEqual(s.optimal_actions(x), s.optimal_actions(y)) + cue = self.by_name("cue-trap-002", "cue_conflict") + self.assertEqual(s.optimal_actions(cue), (s.RIGHT,)) + self.assertEqual(s.regret(cue, s.policy_action(cue, "cue_following")), F(3, 5)) + + def test_information_access_and_signal_quality(self): + no_access = self.by_name("access-004", "scout_unavailable") + self.assertNotIn(s.SCOUT, s.values(no_access)) + self.assertEqual(s.information_value(no_access), 0) + with self.assertRaises(ValueError): + s.realized_reward(no_access, s.SCOUT, False, False) + no_info = self.by_name("signal-quality-005", "uninformative_scout") + self.assertEqual(s.information_value(no_info), 0) + self.assertEqual(s.values(no_info)[s.SCOUT], F(2, 5)) + + def test_bellman_independently_equals_latent_signal_enumeration(self): + for prior, accuracy, cost, signal, report_reliability in product( + (F(0), F(1, 4), F(1, 2), F(4, 5), F(1)), + (F(1, 2), F(3, 5), F(4, 5), F(1)), + (F(0), F(1, 10), F(3, 10), F(2)), + (False, True), (F(1, 2), F(3, 5), F(1))): + try: + world = s.World("enum", "grid", "game", False, cost, accuracy, prior, + True, (s.Report("x", signal, report_reliability),)) + except ValueError: # Zero-probability conditional report + continue + for action, v in s.values(world).items(): + self.assertEqual(v, s.enumerated_expected_reward(world, action)) + self.assertGreaterEqual(s.regret(world, action), 0) + self.assertEqual(s.regret(world, s.policy_action(world, "exact")), 0) + + def test_two_source_posterior_against_direct_joint_enumeration(self): + for a, b, rel in product((False, True), repeat=3): + accuracy = F(4, 5) if rel else F(3, 5) + world = s.World("brute", "two", "council", False, F(1, 10), + reports=(s.Report("source1", a, accuracy), + s.Report("source2", b, accuracy))) + likelihood_right = ((accuracy if a else 1-accuracy) + * (accuracy if b else 1-accuracy)) + likelihood_left = ((1-accuracy if a else accuracy) + * (1-accuracy if b else accuracy)) + self.assertEqual(s.posterior_right(world), likelihood_right/(likelihood_right+likelihood_left)) + + def test_invalid_provenance_and_impossible_histories(self): + with self.assertRaises(ValueError): + s.World("x", "x", "s", False, F(0), reports=( + s.Report("same", False, F(3, 5)), s.Report("same", True, F(3, 5)))) + with self.assertRaises(ValueError): + s.World("x", "x", "s", False, F(0), reports=( + s.Report("a", False, F(1)), s.Report("b", True, F(1)))) + with self.assertRaises(ValueError): + s.Report("", True, F(3, 4)) + with self.assertRaises(ValueError): + s.Report("valid", True, F(2, 5)) + with self.assertRaises(ValueError): + replace(self.by_name("scout-cost-001", "cheap"), scout_cost=F(-1)) + with self.assertRaises(ValueError): + s.posterior_after_scout(F(1), False, F(1)) + + def test_public_private_custody_and_four_linked_views(self): + worlds = s.development_cases() + self.assertEqual(len(worlds), 12) + self.assertEqual(len({w.root_id for w in worlds}), 5) + for w in worlds: + task = s.public_task(w) + self.assertNotIn("root_id", task) + self.assertNotIn("case_id", task) + self.assertNotIn("optimal_actions", task) + self.assertNotIn("posterior_right", task) + self.assertEqual(len(task["reports"]), len(w.reports)) + self.assertEqual(set(task["legal_actions"]), set(s.values(w))) + self.assertEqual(s.private_grade(w)["root_id"], w.root_id) + views = s.development_views() + self.assertEqual(len(views), 8) + self.assertEqual(len({v["parent_root"] for v in views}), 2) + for root in {v["parent_root"] for v in views}: + self.assertEqual({v["view"] for v in views if v["parent_root"] == root}, + {"play", "revise", "hold_steady", "repair"}) + for v in views: + world = next(w for w in worlds if w.root_id == v["parent_root"] + and w.case_id == v["grader_case_id"]) + if v["view"] == "hold_steady": + self.assertEqual(v["public_task"]["legal_actions"], list(s.values(world))) + if v["view"] == "repair": + self.assertGreater(s.regret(world, v["recorded_bad_action"]), 0) + + def test_development_baseline_failure_patterns(self): + worlds = s.development_cases() + expected = { + "cue_following": {"cheap", "cue_conflict", "shared_relays", "scout_available", "informative_scout"}, + "always_scout": {"expensive", "cue_conflict", "independent_witnesses", "uninformative_scout", "cosmetic_cue"}, + "double_count_relays": {"shared_relays"}, + } + for name in ("cue_following", "always_scout", "always_commit", "double_count_relays"): + failures = {w.case_id for w in worlds if s.regret(w, s.policy_action(w, name)) > 0} + if name in expected: + self.assertTrue(expected[name] <= failures if name != "always_scout" else + {"expensive", "cue_conflict", "independent_witnesses", "uninformative_scout"} <= failures) + self.assertTrue(all(s.regret(w, s.policy_action(w, "exact")) == 0 for w in worlds)) + + +if __name__ == "__main__": + unittest.main()