276 lines
14 KiB
Python
276 lines
14 KiB
Python
"""Versioned claim-group and timing behavior for the offline purpose policy."""
|
|
|
|
from dataclasses import replace
|
|
from datetime import datetime, timedelta, timezone
|
|
from functools import cache
|
|
import json
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from scripts.rectification_purpose_gate import POLICY_VERSION, assess_use
|
|
from scripts.rectification_purpose_gate import scope as scope_module
|
|
from scripts.rectification_purpose_gate.native import native_scope_compute
|
|
from scripts.rectification_purpose_gate.providers import native_boundary_providers
|
|
from scripts.rectification_purpose_gate.scan import scan_scope
|
|
from scripts.rectification_purpose_gate.scope import EVENT_CLASSES, SECOND, build_scope_request, range_limits, stamp
|
|
from scripts.rectification_purpose_gate.timing import period_change_witnesses, period_observation
|
|
|
|
START = datetime(2000, 1, 1, tzinfo=timezone.utc)
|
|
BRANCH = "test"
|
|
PROFILE = {"lat": 57.0, "lon": 0, "tz": 0, "ayanamsa": "raman", "node_mode": "mean"}
|
|
WINDOW = {"forecast_start": "2026-01-01T00:00:00Z", "forecast_end": "2027-01-01T00:00:00Z"}
|
|
FIXTURE = Path(__file__).with_name("fixtures") / "rectification_purpose_scan_20261116.json"
|
|
|
|
|
|
def _scope(domain="career", granularity="structure", *, ranges=None, **overrides):
|
|
return build_scope_request(
|
|
{"question": "Synthetic scope", "domains": [domain], "granularity": granularity, **WINDOW, **overrides},
|
|
{"input_revision": "synthetic"},
|
|
ranges or [{"start": START.isoformat(), "end": (START + 60 * SECOND).isoformat()}],
|
|
{"engine_version": "synthetic", "branches": {BRANCH: PROFILE}},
|
|
"2026-01-01T00:00:00Z",
|
|
)
|
|
|
|
|
|
def _period(period_id, start, end, *, level="AD", lord="Jupiter", parent="md"):
|
|
return {"period_id": period_id, "lord": lord, "parent_period_id": parent, "level": level,
|
|
"start": start + "T00:00:00Z", "end": end + "T00:00:00Z"}
|
|
|
|
|
|
def _value(value="stable", periods=None):
|
|
return {"status": "executed", "value": value, "method_id": "synthetic", "result_ref": "synthetic",
|
|
**({"periods": periods} if periods is not None else {})}
|
|
|
|
|
|
def _evaluate(scope, output_at=None, overrides=None):
|
|
layers = scope["policy"]["required_layers"]
|
|
|
|
def compute(at, branch):
|
|
outputs = {layer: _value() for layer in layers}
|
|
for layer in ("Vimshottari", "Narayana"):
|
|
if layer in outputs:
|
|
outputs[layer] = _value("native_periods", [_period("md/ad", "2026-01-10", "2026-02-10")])
|
|
if output_at is not None:
|
|
outputs.update(output_at(at))
|
|
return {"candidate_at": at, "branch_id": branch, "profile": scope["profiles"][branch], "outputs": outputs}
|
|
|
|
def covered(item, sample):
|
|
left, right = range_limits(item)
|
|
midpoint = left + SECOND * (int((right - left) / SECOND) // 2)
|
|
sample(midpoint, item["branch_id"])
|
|
return {"state": "policy_covered", "method_id": "synthetic_known_boundaries",
|
|
"boundaries": [midpoint] if left < midpoint else [], "resolution_seconds": 1,
|
|
"max_unchecked_gap_seconds": 0, "boundary_error_seconds": 0}
|
|
|
|
assessment = scan_scope(scope, compute, {**dict.fromkeys(layers, covered), **(overrides or {})})
|
|
return assessment, assess_use(assessment, scope["binding"])
|
|
|
|
|
|
def _statuses(result):
|
|
return {row["group_id"]: row["status"] for row in result["claim_groups"]}
|
|
|
|
|
|
@pytest.mark.parametrize("domain", ["career", "wealth", "marriage", "structure"])
|
|
@pytest.mark.parametrize("granularity", ["structure", "day", "month", "year"])
|
|
def test_groups_cover_route_names_or_list_them_explicitly(domain, granularity):
|
|
policy = _scope(domain, granularity)["policy"]
|
|
assert policy["id"] == POLICY_VERSION
|
|
groups = policy["claim_groups"]
|
|
assert all(group["domain"] == domain for group in groups)
|
|
assert len({group["group_id"] for group in groups}) == len(groups)
|
|
assert set(policy["required_layers"]) == {layer for group in groups for layer in group["layers"]}
|
|
assert not policy["unmapped_route_layers"]
|
|
assert policy["vimshottari_depth"] == 3 and policy["narayana_depth"] == 2
|
|
assert all(not group["timing_only"] for group in groups) == (granularity == "structure" or domain == "structure")
|
|
|
|
|
|
def test_unknown_route_dependency_blocks_only_overall_readiness(monkeypatch):
|
|
original = scope_module.plan_route_contract
|
|
|
|
def route(domain):
|
|
contract = original(domain)
|
|
return replace(contract, required_layers=(*contract.required_layers, "unmapped_future_layer"))
|
|
|
|
monkeypatch.setattr(scope_module, "plan_route_contract", route)
|
|
_, decision = _evaluate(_scope())
|
|
assert decision["unmapped_route_layers"] == ["unmapped_future_layer"]
|
|
assert set(_statuses(decision).values()) == {"scope_ready"}
|
|
assert decision["status"] == "conditional"
|
|
assert not decision["can_use_interval"]
|
|
|
|
|
|
def test_d10_boundary_limits_career_direction_but_keeps_d9_ready():
|
|
scope = _scope()
|
|
assessment, decision = _evaluate(scope, lambda at: {"D10": _value("old" if at < START + 30 * SECOND else "new")})
|
|
statuses = _statuses(decision)
|
|
assert statuses["career_direction"] == "needs_refinement"
|
|
assert statuses["career_d9_support"] == "scope_ready"
|
|
assert decision["status"] == "needs_refinement" and not decision["can_use_interval"]
|
|
group = next(row for row in decision["claim_groups"] if row["group_id"] == "career_direction")
|
|
assert {"layer": "D10", "reason": "birth_time_sensitive", "boundary_times": [(START + 30 * SECOND).isoformat()],
|
|
"observed_at": [START.isoformat(), (START + 30 * SECOND).isoformat()]} in group["limited_by"]
|
|
assert any(claim["group_id"] == "career_d9_support" and claim["claim_id"] in decision["stable_claim_ids"]
|
|
for claim in assessment["claims"])
|
|
assert len({claim["claim_id"] for claim in assessment["claims"]}) == len(assessment["claims"])
|
|
|
|
|
|
@pytest.mark.parametrize("domain,strength_group", [
|
|
("career", "career_strength"), ("wealth", "wealth_strength"), ("marriage", "relationship_strength"),
|
|
("structure", "structure_strength"),
|
|
])
|
|
def test_method_unresolved_shadbala_only_limits_its_strength_group(domain, strength_group):
|
|
scope = _scope(domain)
|
|
shadbala = native_boundary_providers(scope)["strength_shadbala"]
|
|
_, decision = _evaluate(scope, lambda _: {
|
|
"strength_shadbala": {"status": "blocked", "reason": "method_unresolved"},
|
|
}, {"strength_shadbala": shadbala})
|
|
statuses = _statuses(decision)
|
|
assert statuses.pop(strength_group) == "conditional"
|
|
assert set(statuses.values()) == {"scope_ready"}
|
|
assert decision["status"] == "conditional"
|
|
|
|
|
|
def test_engine_failure_stays_in_affected_claim_group():
|
|
_, decision = _evaluate(_scope(), lambda _: {"D10": {"status": "error", "reason": "calculation_failure"}})
|
|
assert _statuses(decision)["career_direction"] == "insufficient_evidence"
|
|
assert _statuses(decision)["career_d9_support"] == "scope_ready"
|
|
assert decision["status"] == "insufficient_evidence"
|
|
|
|
|
|
def test_relationship_timing_requires_one_of_four_distinct_bound_event_classes():
|
|
missing = _scope("marriage", "month")
|
|
_, decision = _evaluate(missing)
|
|
states = _statuses(decision)
|
|
assert states.pop("relationship_timing") == "needs_input"
|
|
assert set(states.values()) == {"scope_ready"}
|
|
assert decision["status"] == "needs_input"
|
|
scopes = [_scope("marriage", "month", event_class=kind) for kind in sorted(EVENT_CLASSES)]
|
|
assert len({scope["binding"]["purpose_fingerprint"] for scope in scopes}) == 4
|
|
assessment, ready = _evaluate(scopes[0])
|
|
assert ready["status"] == "scope_ready" and ready["can_use_interval"]
|
|
assert f"relationship_timing:{scopes[0]['purpose_scope']['event_class']}" in _statuses(ready)
|
|
assert assess_use(assessment, scopes[-1]["binding"])["status"] == "stale"
|
|
with pytest.raises(ValueError, match="unsupported_event_class"):
|
|
_scope("marriage", "year", event_class="unspecified")
|
|
|
|
|
|
def _changes(before, after, *, granularity="month", target_boundaries=()):
|
|
forecast = {"start": WINDOW["forecast_start"], "end": WINDOW["forecast_end"],
|
|
"target_boundaries": list(target_boundaries), "comparison_offset_seconds": 0}
|
|
observations = [(at, period_observation(_value("native_periods", periods), forecast, granularity))
|
|
for at, periods in zip(("a", "b"), (before, after))]
|
|
return set(period_change_witnesses(observations, granularity))
|
|
|
|
|
|
def test_window_presence_is_material_even_if_one_candidate_has_no_period():
|
|
assert _changes([], [_period("one", "2026-01-05", "2026-01-20")]) == {"window_presence"}
|
|
|
|
|
|
def test_same_lord_with_a_different_parent_is_a_different_identity():
|
|
period = _period("one", "2026-01-05", "2026-01-20")
|
|
assert _changes([period], [{**period, "parent_period_id": "other"}]) == {"period_identity"}
|
|
|
|
|
|
def test_crossing_a_target_date_is_material_with_identical_month_and_duration():
|
|
before = _period("one", "2026-01-08", "2026-01-10")
|
|
after = _period("one", "2026-01-09", "2026-01-11")
|
|
assert _changes([before], [after], target_boundaries=["2026-01-08T18:00:00Z"]) == {"target_boundary_crossing"}
|
|
|
|
|
|
def test_separate_segments_are_material_with_same_ids_months_and_total_duration():
|
|
a = _period("one", "2026-01-08", "2026-01-10")
|
|
b = _period("two", "2026-01-10", "2026-01-12")
|
|
gap = _period("two", "2026-01-11", "2026-01-13")
|
|
assert _changes([a, b], [gap, a]) == {"window_segments_and_gaps"}
|
|
|
|
|
|
def test_window_duration_only_changes_outside_the_policy_tolerance():
|
|
before = _period("one", "2026-01-05", "2026-01-10")
|
|
limit = _period("one", "2026-01-05", "2026-01-17")
|
|
longer = _period("one", "2026-01-05", "2026-01-18")
|
|
assert _changes([before], [longer]) == {"window_total_duration"}
|
|
assert _changes([before], [limit]) == set()
|
|
assert _changes([before], [_period("one", "2026-01-08", "2026-01-13")]) == set()
|
|
|
|
|
|
def test_edges_outside_the_forecast_do_not_change_the_observed_window():
|
|
before = _period("one", "2025-11-05", "2026-01-15")
|
|
after = _period("one", "2025-12-05", "2026-01-15")
|
|
assert _changes([before], [after]) == set()
|
|
|
|
|
|
def test_duration_extrema_compares_entire_candidate_set_not_only_adjacent_pairs():
|
|
forecast = {"start": WINDOW["forecast_start"], "end": WINDOW["forecast_end"],
|
|
"target_boundaries": [], "comparison_offset_seconds": 0}
|
|
dates = ["2026-01-10", "2026-01-14", "2026-01-18"]
|
|
observations = [
|
|
(end, period_observation(_value("native_periods", [_period("one", "2026-01-05", end)]), forecast, "month"))
|
|
for end in dates
|
|
]
|
|
assert period_change_witnesses(observations, "month") == {"window_total_duration": [dates[0], dates[-1]]}
|
|
|
|
|
|
def test_year_scope_keeps_pd_and_surfaces_ad_switch_near_requested_boundary():
|
|
scope = _scope("career", "year", target_boundaries=["2026-05-15T00:00:00Z"])
|
|
_, decision = _evaluate(scope, lambda at: {
|
|
"Vimshottari": _value("native_periods", [
|
|
_period("one", "2026-05-01", "2026-05-14" if at == START else "2026-05-16"),
|
|
_period("two", "2026-05-14" if at == START else "2026-05-16", "2026-06-01"),
|
|
]),
|
|
})
|
|
group = next(row for row in decision["claim_groups"] if row["group_id"] == "career_timing")
|
|
assert group["status"] == "needs_refinement"
|
|
assert {"target_boundary_crossing", "birth_time_sensitive"} <= {row["reason"] for row in group["limited_by"]}
|
|
compute = native_scope_compute(scope)
|
|
rows = compute(START, BRANCH)["outputs"]["Vimshottari"]["periods"]
|
|
assert scope["policy"]["vimshottari_depth"] == 3
|
|
assert {"MD", "AD", "PD"} <= {row["level"] for row in rows}
|
|
|
|
|
|
def test_native_exact_lagna_contact_moves_and_provider_never_claims_coverage():
|
|
end = START + 120 * SECOND
|
|
scope = _scope("career", "month", ranges=[{"start": START.isoformat(), "end": end.isoformat()}])
|
|
scope["policy"]["required_layers"] = ["transit_natal_contacts"]
|
|
layer = "transit_natal_contacts"
|
|
compute = cache(native_scope_compute(scope))
|
|
item = scope["plausible_ranges"][0]
|
|
|
|
def periods(at):
|
|
value = compute(at, BRANCH)["outputs"][layer]["value"]
|
|
return {(row["body"], row["aspect_nth"]): [c["at"] for c in row["crossings"]]
|
|
for row in value["aspects"] if row["natal_point"] == "Lagna"}
|
|
|
|
before, after = periods(START), periods(end)
|
|
assert any(before[key] != after[key] for key in before.keys() & after.keys())
|
|
details = native_boundary_providers(scope)[layer](item, compute)
|
|
assert details["state"] == "sampled_only" and details["boundaries"]
|
|
for at in details["boundaries"]:
|
|
assert compute(at - SECOND, BRANCH)["outputs"][layer]["value"] != compute(at, BRANCH)["outputs"][layer]["value"]
|
|
|
|
|
|
def test_identical_transit_samples_still_leave_unknown_changes():
|
|
layer = "transit_natal_contacts"
|
|
scope = _scope("career", "month")
|
|
calls = []
|
|
|
|
def sample(at, branch):
|
|
calls.append(at)
|
|
return {"outputs": {layer: _value({"aspects": [], "conjunctions": []})}}
|
|
|
|
details = native_boundary_providers(scope)[layer](scope["plausible_ranges"][0], sample)
|
|
assert calls
|
|
assert details["state"] == "sampled_only" and "basis" not in details and not details["boundaries"]
|
|
|
|
|
|
def test_existing_fixtures_declare_v1_and_preserve_the_old_scope_binding():
|
|
fixtures = json.loads(FIXTURE.read_text(encoding="utf-8"))
|
|
for fixture in fixtures.values():
|
|
packet = fixture["input"]
|
|
question = packet["question"]
|
|
scope = build_scope_request(question, packet["original_input"], packet["remaining_ranges"],
|
|
packet["profiles"], packet["evaluated_at"])
|
|
assert scope["policy"]["id"] == "purpose_policy_v1"
|
|
assert "claim_groups" not in scope["policy"]
|
|
assert scope["policy"]["vimshottari_depth"] == (0 if question["granularity"] == "structure" else 3)
|