Files
Jyotisha/tests/test_rectification_purpose_scan.py
T

245 lines
12 KiB
Python

"""Scope-scan contracts, including native fixture replay."""
from datetime import datetime, timedelta, timezone
import json
from pathlib import Path
import pytest
from scripts.rectification_purpose_gate import assess_use
from scripts.rectification_purpose_gate.__main__ import evaluate_scope
from scripts.rectification_purpose_gate.scan import scan_scope
from scripts.rectification_purpose_gate.scope import SECOND, build_scope_request, range_limits
ANCHOR = datetime(2000, 1, 1, tzinfo=timezone.utc)
PROFILE = {"lat": 57.0, "lon": 0, "tz": 0, "ayanamsa": "raman", "node_mode": "mean"}
FORECAST = {"forecast_start": "2026-01-01T00:00:00Z", "forecast_end": "2026-04-01T00:00:00Z",
"target_boundaries": ["2026-02-01T00:00:00Z"]}
FIXTURE = Path(__file__).with_name("fixtures") / "rectification_purpose_scan_20261116.json"
def _at(offset):
return (ANCHOR + timedelta(seconds=offset)).isoformat()
def _scope(*, ranges=None, timing=False, profiles=None, **question):
if timing:
options = {"domains": ["career"], "granularity": "day", **FORECAST}
else:
options = {"domains": ["structure"], "granularity": "structure"}
return build_scope_request(
{"question": "Synthetic scope", **options, **question},
{"input_revision": "synthetic"},
[{"start": _at(0), "end": _at(60)}] if ranges is None else ranges,
{"engine_version": "synthetic-native", "branches": {"s": PROFILE} if profiles is None else profiles},
"2026-01-01T00:00:00Z",
)
def _value(value):
return {"value": value, "status": "executed", "method_id": "synthetic-calculation", "result_ref": "synthetic",
"dependencies": ["test_input"]}
def _dasha(start, end):
return {**_value("native_periods"), "periods": [
{"period_id": "MD:fixture/AD:fixture", "level": "AD", "lord": "fixture",
"parent_period_id": "MD:fixture", "start": start, "end": end}
]}
def _compute(scope, overrides=None, observed=None):
def run(at, branch):
if observed is not None:
observed.append(at)
outputs = {layer: _value("A") for layer in scope["policy"]["required_layers"]}
if overrides is not None:
outputs.update(overrides(int((at - ANCHOR).total_seconds()), branch))
return {"candidate_at": at, "branch_id": branch, "profile": scope["profiles"][branch], "outputs": outputs}
return run
def _provider(*offsets, resolution=1):
def cover(item, sample):
start, end = range_limits(item)
return {
"state": "policy_covered", "method_id": "synthetic_known_breakpoints",
"boundaries": [datetime.fromisoformat(_at(offset)) for offset in offsets if start < datetime.fromisoformat(_at(offset)) <= end],
"resolution_seconds": resolution, "max_unchecked_gap_seconds": 0, "boundary_error_seconds": 0,
}
return cover
def _providers(scope, **overrides):
return {layer: overrides.get(layer, _provider()) for layer in scope["policy"]["required_layers"]}
def _decision(scope, result):
return assess_use(result, scope["binding"])["status"]
def test_u01_twenty_minutes_complete_for_structure_can_stop_without_events():
scope = _scope(ranges=[{"start": _at(0), "end": _at(1200)}])
result = scan_scope(scope, _compute(scope), _providers(scope))
assert _decision(scope, result) == "scope_ready"
assert result["historical_evidence_state"] == "not_evaluated"
assert not assess_use(result, scope["binding"])["can_modify_birth_record"]
def test_u02_twenty_seconds_can_cross_a_relevant_varga():
scope = _scope(ranges=[{"start": _at(0), "end": _at(20)}])
result = scan_scope(scope, _compute(scope, lambda s, _: {"D9": _value(s >= 10 and "B" or "A")}),
_providers(scope, D9=_provider(10)))
assert _decision(scope, result) == "needs_refinement"
assert result["material_differences"][0]["layer"] == "D9"
def test_u03_aba_requires_actual_internal_bounds_not_equal_endpoints():
scope = _scope()
compute = _compute(scope, lambda s, _: {"D9": _value("B" if 25 <= s < 35 else "A")})
endpoints = scan_scope(scope, compute, {})
assert endpoints["scan_state"] == "sampled_only"
assert not endpoints["domain_complete"] and not endpoints["stable_claim_ids"]
assert _decision(scope, endpoints) == "conditional"
proved = scan_scope(scope, compute, _providers(scope, D9=_provider(25, 35)))
assert _decision(scope, proved) == "needs_refinement"
assert [(i["range"]["start"], i["range"]["end"]) for i in proved["interval_results"]] == [
(_at(0), _at(24)), (_at(25), _at(34)), (_at(35), _at(60)),
]
def test_u05_missing_narayana_ad_and_empty_or_blocked_values_are_not_stable():
scope = _scope(timing=True)
overrides = lambda _, branch: {
"Narayana": {"status": "blocked", "reason": "method_unresolved"},
"Vimshottari": _value(None), "D1": _value([]), "D10": _value("A"),
}
result = scan_scope(scope, _compute(scope, overrides), _providers(scope))
for layer in ("Narayana", "Vimshottari", "D1"):
assert result["layer_coverage"][layer] == "blocked"
assert all(not claim.startswith(layer + ":") for claim in result["stable_claim_ids"])
assert _decision(scope, result) == "conditional"
def test_u07_irrelevant_d60_change_remains_observed_only():
scope = _scope()
compute = _compute(scope, lambda s, _: {"D60": _value(s)})
result = scan_scope(scope, compute, _providers(scope))
assert _decision(scope, result) == "scope_ready"
assert not result["material_differences"]
assert any(row["layer"] == "D60" and not row["relevant"] for row in result["observed_differences"])
def test_u08_same_lord_period_crosses_target_date_and_keeps_parent_identity():
scope = _scope(timing=True)
result = scan_scope(scope, _compute(scope, lambda s, _: {
"Vimshottari": _dasha("2026-01-31T12:00:00Z" if s < 30 else "2026-02-01T12:00:00Z", "2026-03-03T00:00:00Z")
}), _providers(scope, Vimshottari=_provider(30)))
assert _decision(scope, result) == "needs_refinement"
assert any(row["layer"] == "Vimshottari" for row in result["material_differences"])
window = result["output_envelopes"]["Vimshottari"][0]
assert window["earliest_start"] == "2026-01-31T12:00:00+00:00"
assert window["latest_start"] == "2026-02-01T12:00:00+00:00"
assert window["by_candidate"][0]["period"]["parent_period_id"] == "MD:fixture"
def test_u09_disjoint_possible_period_windows_have_no_common_window():
scope = _scope(timing=True)
result = scan_scope(scope, _compute(scope, lambda s, _: {
"Vimshottari": _dasha("2026-01-10T00:00:00Z", "2026-01-20T00:00:00Z") if s < 30 else
_dasha("2026-02-10T00:00:00Z", "2026-02-20T00:00:00Z")
}), _providers(scope, Vimshottari=_provider(30)))
period = result["output_envelopes"]["Vimshottari"][0]
assert len(period["possible_windows"]) == 2 and period["common_window"] is None
assert result["material_change"]
def test_u11_noncontiguous_ranges_never_sample_the_gap():
scope = _scope(ranges=[{"start": _at(0), "end": _at(20)}, {"start": _at(40), "end": _at(60)}])
observed = []
result = scan_scope(scope, _compute(scope, lambda s, _: {"D9": _value("A" if s < 30 else "B")}, observed),
_providers(scope))
assert [row["range_id"] for row in result["interval_results"]] == ["r1", "r2"]
assert _decision(scope, result) == "needs_refinement"
assert all(not 20 < (at - ANCHOR).total_seconds() < 40 for at in observed)
def test_u12_cross_midnight_differs_from_dst_ambiguity_and_coarse_resolution():
scope = _scope(ranges=[{"start": "2000-01-01T23:59:59Z", "end": "2000-01-02T00:00:01Z"}])
result = scan_scope(scope, _compute(scope), _providers(scope, D9=_provider(resolution=60)))
assert scope["plausible_ranges"][0]["duration_seconds"] == 2
assert result["scan_state"] == "sampled_only" and _decision(scope, result) == "conditional"
local = {key: value for key, value in PROFILE.items() if key != "tz"}
with pytest.raises(ValueError, match="ambiguous_or_missing_local_time"):
_scope(ranges=[{"start": "2026-11-01T01:15:00", "end": "2026-11-01T01:30:00"}],
profiles={"s": {**local, "timezone": "America/New_York"}})
branches = {"early": {**local, "timezone": "America/New_York"}, "late": {**local, "timezone": "America/New_York"}}
explicit = _scope(profiles=branches, ranges=[
{"branch_id": "early", "start": "2026-11-01T01:15:00-04:00", "end": "2026-11-01T01:30:00-04:00"},
{"branch_id": "late", "start": "2026-11-01T01:15:00-05:00", "end": "2026-11-01T01:30:00-05:00"},
])
assert explicit["plausible_ranges"][0]["start"] != explicit["plausible_ranges"][1]["start"]
result = scan_scope(explicit, _compute(explicit, lambda _, b: {"D9": _value(b)}), _providers(explicit))
assert result["branch_state"] == "unresolved_material"
def test_u16_budget_exhaustion_leaves_explicit_uncovered_ranges():
scope = _scope()
def enumerate_all(item, sample):
start, end = range_limits(item)
at = start
while at <= end:
sample(at, item["branch_id"])
at += SECOND
return _provider()(item, sample)
result = scan_scope(scope, _compute(scope), _providers(scope, D1=enumerate_all), budget=5)
assert result["budget"] == {"candidate_limit": 5, "candidates_computed": 5, "exhausted": True}
assert result["scan_state"] == "incomplete" and result["domain_complete"] is False
assert any(row["uncovered"] and row["reason"] == "scan_incomplete" for row in result["per_layer_scan_receipts"])
assert _decision(scope, result) != "scope_ready"
def test_native_calculation_failure_does_not_produce_a_stable_claim():
scope = _scope()
def missing(at, branch):
raise RuntimeError("synthetic engine failure")
result = scan_scope(scope, missing, _providers(scope))
assert result["scan_state"] == "incomplete"
assert not result["stable_claim_ids"]
assert {"layer": "D1", "reason": "calculation_failure"} in result["limitations"]
def test_native_profile_not_supported_marks_method_unresolved_without_claims():
packet = json.loads(FIXTURE.read_text(encoding="utf-8"))["stable_structure"]["input"]
packet["profiles"]["branches"]["synthetic"]["house_system"] = "placidus"
result = evaluate_scope(packet)["purpose_assessment"]
assert result["decision"]["status"] == "insufficient_evidence"
assert not result["stable_claim_ids"]
assert all(receipt["reason"] == "method_unresolved" for receipt in result["per_layer_scan_receipts"])
@pytest.mark.parametrize("case", ["stable_structure", "crossing_d9", "vimshottari_date"])
def test_native_synthetic_birth_fixture(case):
reference = json.loads(FIXTURE.read_text(encoding="utf-8"))[case]
result = evaluate_scope(reference["input"])["purpose_assessment"]
assert result["decision"]["status"] == reference["status"]
assert result["scan_state"] == reference["scan_state"]
assert [row["layer"] for row in result["material_differences"]] == reference["changed_layers"]
by_at = {row["candidate_at"]: row for row in result["candidates"]}
for expected in reference["native_samples"]:
computed = by_at[expected["candidate_at"]]
assert computed["raw"]["ascendant_longitude"] == pytest.approx(expected["raw"]["ascendant_longitude"], abs=1e-6)
assert computed["raw"]["moon_longitude"] == pytest.approx(expected["raw"]["moon_longitude"], abs=1e-6)
assert computed["outputs"]["D9" if case != "vimshottari_date" else "D10"]["value"] == expected["outputs"]["D9" if case != "vimshottari_date" else "D10"]["value"]
if case == "crossing_d9":
d9 = next(row for row in result["per_layer_scan_receipts"] if row["layer"] == "D9")
assert d9["boundary_times"] == reference["d9_boundaries"]
assert d9["boundary_error_seconds"] <= 1
if case == "vimshottari_date":
assert "Vimshottari" in reference["changed_layers"]
windows = result["output_envelopes"]["Vimshottari"]
assert any(row["earliest_start"][:10] != row["latest_start"][:10] for row in windows)