Files
Jyotisha/tests/test_rectification_purpose_coverage.py

222 lines
9.1 KiB
Python

"""Boundary proof and per-second comparisons for the offline purpose scan."""
from datetime import datetime, timedelta, timezone
from functools import cache
from itertools import pairwise
import json
from pathlib import Path
import pytest
from scripts.rectification_purpose_gate.native import native_scope_compute
from scripts.rectification_purpose_gate.providers import GRAHAS, native_boundary_providers
from scripts.rectification_purpose_gate.scope import SECOND, build_scope_request, range_limits, stamp
from scripts.rectification_purpose_gate.timing import period_signature
START = datetime(2000, 1, 1, tzinfo=timezone.utc)
BRANCH = "synthetic"
FIXTURE = Path(__file__).with_name("fixtures") / "rectification_purpose_scan_20261116.json"
ARUDHAS = ("A1", "A7", "A10", "UL")
def _scope(layers, midpoint=START, half=120, *, through=None):
original = json.loads(FIXTURE.read_text(encoding="utf-8"))["vimshottari_date"]["input"]
question = {**original["question"], "granularity": "month"}
if through:
question["forecast_end"] = through
ranges = [{"start": (midpoint - SECOND * half).isoformat(),
"end": (midpoint + SECOND * half).isoformat()}]
scope = build_scope_request(question, original["original_input"], ranges,
original["profiles"], original["evaluated_at"])
# Isolate the tested provider, including A1 which the current route does not request.
scope["policy"]["required_layers"] = list(layers)
return scope
def _value(value, **extra):
return {"status": "executed", "value": value, **extra}
def _period(start, end, key="md"):
return {"period_id": key, "start": start.isoformat(), "end": end.isoformat(),
"lord": key, "level": "MD", "parent_period_id": None}
def _synthetic(asc=lambda _: 15.0, planets=None, outputs=None):
def sample(at, _):
offset = int((at - START) / SECOND)
longitudes = {name: 30 * i + 1 + i * 1.6 for i, name in enumerate(GRAHAS)}
speeds = dict.fromkeys(GRAHAS, 0)
longitudes["Moon"] += offset * 0.0002
speeds["Moon"] = 17.28
if planets:
planets(offset, longitudes, speeds)
layer_values = {"moon_nakshatra": _value(int(longitudes["Moon"] / (360 / 27)))}
if outputs:
layer_values.update(outputs(offset))
return {"outputs": layer_values, "raw": {"ascendant_longitude": asc(offset),
"moon_longitude": longitudes["Moon"], "planet_longitudes": longitudes,
"planet_speeds": speeds}}
return sample
def _scan(scope, layer, sample):
return native_boundary_providers(scope)[layer](scope["plausible_ranges"][0], sample)
def test_arudha_rejects_internal_change_without_a_sign_cut():
scope = _scope(["A1"], START + SECOND * 120, half=119)
sample = _synthetic(outputs=lambda t: {"A1": _value("B" if t == 120 else "A")})
result = _scan(scope, "A1", sample)
assert result["state"] == "sampled_only"
assert "basis" not in result
def _window_with(*layers):
return _scope(layers, START + SECOND * 120)
@pytest.mark.parametrize("with_ascendant", [False, True])
def test_arudha_retrograde_wrap_and_simultaneous_cut(with_ascendant):
def planets(t, longitudes, speeds):
# At t=30 Mercury is exactly on 0° and still in the same sign.
longitudes["Mercury"] = ((30 - t) * 0.00001) % 360
speeds["Mercury"] = -0.864
def asc(t):
return 30 + (t - 31) * 0.003 if with_ascendant else 15
sample = _synthetic(asc, planets, lambda t: {"A1": _value(t >= 31)})
result = _scan(_window_with("A1"), "A1", sample)
assert result["state"] == "policy_covered"
assert result["boundaries"] == [START + SECOND * 31]
assert result["max_unchecked_gap_seconds"] == 60
@pytest.mark.parametrize("kind", ["missing", "station", "high-latitude"])
def test_arudha_keeps_sampling_when_sign_inputs_are_uncertain(kind):
def planets(t, longitudes, speeds):
if kind == "missing":
del longitudes["Mercury"]
if kind == "station":
longitudes["Mercury"] += abs(t - 30) * 0.00001
speeds["Mercury"] = -1 if t < 30 else 1
scope = _window_with("A1")
if kind == "high-latitude":
scope["profiles"][BRANCH]["lat"] = 65
sample = _synthetic(planets=planets, outputs=lambda _: {"A1": _value("A")})
assert _scan(scope, "A1", sample)["state"] == "sampled_only"
def test_vimshottari_rejects_a_b_a_and_nonmonotone_dates():
scope = _window_with("Vimshottari")
q = scope["purpose_scope"]["forecast_window"]
target = stamp(q["start"]) + timedelta(days=2)
q["target_boundaries"] = [target.isoformat()]
def outputs(t):
date = target + timedelta(days=1 if 25 <= t < 35 else -1)
return {"Vimshottari": _value("periods", periods=[_period(date, date + timedelta(days=15))])}
result = _scan(scope, "Vimshottari", _synthetic(outputs=outputs))
assert result["state"] == "sampled_only"
assert "basis" not in result
def test_vimshottari_splits_at_nakshatra_and_verifies_each_segment():
scope = _window_with("Vimshottari")
q = scope["purpose_scope"]["forecast_window"]
mid = stamp(q["start"]) + timedelta(days=2)
def planets(t, longitudes, speeds):
longitudes["Moon"] = 40 + (t - 31) * 0.0001
def outputs(t):
shift = timedelta(hours=1 if t >= 31 else 0, seconds=-t)
return {"Vimshottari": _value("periods", periods=[
_period(mid + shift, mid + shift + timedelta(days=15), "next" if t >= 31 else "first")])}
result = _scan(scope, "Vimshottari", _synthetic(planets=planets, outputs=outputs))
assert result["state"] == "policy_covered"
assert result["boundaries"] == [START + SECOND * 31]
def test_narayana_rejects_internal_period_reorder():
q = _window_with("Narayana")["purpose_scope"]["forecast_window"]
date = stamp(q["start"]) + timedelta(days=2)
def outputs(t):
start = date + SECOND * t
key = "other" if 25 <= t < 35 else "md"
return {"Narayana": _value("periods", periods=[_period(start, start + timedelta(days=40), key)])}
result = _scan(_window_with("Narayana"), "Narayana", _synthetic(outputs=outputs))
assert result["state"] == "sampled_only"
assert "basis" not in result
def test_narayana_rejects_degree_order_change_inside_one_sign():
date = stamp(_window_with("Narayana")["purpose_scope"]["forecast_window"]["start"])
def planets(t, longitudes, speeds):
longitudes["Mercury"] = 90 + 1 + (31 - t) * 0.00001
speeds["Mercury"] = -0.864
def outputs(t):
return {"Narayana": _value("periods", periods=[
_period(date + SECOND * t, date + SECOND * t + timedelta(days=40))])}
result = _scan(_window_with("Narayana"), "Narayana", _synthetic(planets=planets, outputs=outputs))
assert (result["state"], result["reason"]) == ("sampled_only", "degree_order_unresolved")
def test_narayana_splits_at_an_ascendant_flip():
scope = _window_with("Narayana")
q = scope["purpose_scope"]["forecast_window"]
date = stamp(q["start"]) + timedelta(days=1)
def outputs(t):
start = date + SECOND * t
key = "other" if t >= 31 else "md"
return {"Narayana": _value("periods", periods=[_period(start, start + timedelta(days=40), key)])}
sample = _synthetic(lambda t: 30 + (t - 31) * 0.003, outputs=outputs)
result = _scan(scope, "Narayana", sample)
assert result["state"] == "policy_covered"
assert result["boundaries"] == [START + SECOND * 31]
@pytest.mark.parametrize("group", ["Arudha", "Vimshottari", "Narayana"])
def test_native_coverage_matches_per_second_oracle(group):
if group == "Arudha":
scope = _scope(ARUDHAS, START + timedelta(hours=1, minutes=37, seconds=25))
elif group == "Vimshottari":
scope = _scope([group])
else:
scope = _scope([group], through="2027-01-01T00:00:00Z")
q = scope["purpose_scope"]["forecast_window"]
midpoint_output = native_scope_compute(scope)(START, BRANCH)["outputs"][group]
assert midpoint_output["status"] == "executed"
q["target_boundaries"] = [next(row["start"] for row in midpoint_output["periods"]
if stamp(q["start"]) < stamp(row["start"]) < stamp(q["end"]))]
sample = cache(native_scope_compute(scope))
item = scope["plausible_ranges"][0]
start, end = range_limits(item)
forecast = scope["purpose_scope"]["forecast_window"]
saw_boundary = False
for layer, provider in native_boundary_providers(scope).items():
result = provider(item, sample)
assert result["state"] == "policy_covered"
values = []
times = [start + SECOND * i for i in range(int((end - start) / SECOND) + 1)]
for at in times:
row = sample(at, BRANCH)["outputs"][layer]
assert row["status"] == "executed"
values.append(row["value"] if group == "Arudha" else period_signature(row, forecast, "month"))
expected = [at for at, (left, right) in zip(times[1:], pairwise(values)) if left != right]
assert result["boundaries"] == expected
saw_boundary |= bool(expected)
assert saw_boundary