Files
Jyotisha/tests/test_evidence_contract_1978.py
ClaudeandClaude Opus 5.5 dd4eab82df fix: evidence ids name objects not values; snapshot v2 with subject, profile and times; four status fields; evidenced edges; dependency closure (BUG-1978)
Per the astrologer's 2026-11-18 review of the evidence-pack draft (§二 1-5, §五.3, §五.5):
logical_key / snapshot-scoped evidence_id / content_hash; birth-branch ids bound to the parent
range and intervals; snapshot over opaque subject, birth input revision, calculation profile,
rule versions, retractions, observation instant and coverage (calculation time recorded only);
execution / formation / interpretation / source status; base-level edges with type, scope,
conditions, method version, basis and review status (engineering dependencies only);
dependency_closure with visited set, cycle report and budget; interpretation_key; a parseable
synthetic fixture and the review's test list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-18 16:22:52 +08:00

261 lines
15 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""BUG-1978: the evidence identity / snapshot / status contract (占星师 2026-11-18 证据包草案审核 §二 1–5, §五.3, §五.5).
Synthetic fixture only (tests/fixtures/evidence_contract_synthetic.v1.json): invented values, not a real or
public chart.
"""
from __future__ import annotations
import copy
import json
import re
from pathlib import Path
import pytest
from scripts.consult_facts import evidence_ids as ev
FIXTURE = Path(__file__).resolve().parent / "fixtures" / "evidence_contract_synthetic.v1.json"
ID = re.compile(r"^(ev|lk):[A-Za-z0-9]+:[A-Za-z0-9_.:@/#~+>\-]*[A-Za-z0-9_]$")
VERSIONS = {"yoga_rules": "yoga_rules:synthetic", "shadbala": "synthetic"}
PROFILE = {"house_system": "whole_sign_from_lagna", "varga_methods": "synthetic", "engine": "synthetic"}
CALC_TIME = "2030-01-15T10:00:00Z"
@pytest.fixture(scope="module")
def data() -> dict:
return json.loads(FIXTURE.read_text(encoding="utf-8"))
def _base(data: dict, **overrides) -> dict:
view = copy.deepcopy(overrides.pop("view", data["view"]))
rows = copy.deepcopy(overrides.pop("rows", data["rows"]))
kwargs = {
"birth_input_revision": data["revision_a"],
"reference_date": data["observation"],
"yoga_layer": copy.deepcopy(data["yoga_layer"]),
"subject_ref": data["subject_a"],
"calculation_time": CALC_TIME,
**overrides,
}
base = ev.build_evidence_base(view, rows, **kwargs)
return base
def _snapshot(data: dict, **overrides) -> dict:
kwargs = {"subject_ref": data["subject_a"], "versions": VERSIONS, "profile": PROFILE,
"calculation_time": CALC_TIME, **overrides}
revision = kwargs.pop("revision", data["revision_a"])
observation = kwargs.pop("observation", data["observation"])
return ev.snapshot_record(revision, observation, **kwargs)
def _items(base: dict) -> dict[str, dict]:
return {item["evidence_id"]: item for item in base["items"]}
def test_every_family_is_present_with_value_free_ids_and_logical_keys(data):
base = _base(data)
items = _items(base)
kinds = {item["kind"] for item in items.values()}
assert kinds == {"placement", "varga_placement", "derived_house", "special_point", "strength", "dasha_period",
"transit", "double_transit", "yoga"}
for evidence, item in items.items():
assert ID.fullmatch(evidence) and evidence.isascii()
assert item["logical_key"] == "lk:" + evidence[3:]
# No value inside an id: a sign name only appears where the family names a sign by identity.
if item["kind"] in ("placement", "varga_placement", "derived_house", "special_point", "strength", "transit"):
assert not any(sign in evidence for sign in ev.SIGNS), evidence
assert re.fullmatch(r"[0-9a-f]{16}", item["content_hash"])
for evidence in ("ev:D1:Sun", "ev:D9:Sun", "ev:arudha:AL2", "ev:arudha:UL2", "ev:point:Gulika",
"ev:point:Navamsa64", "ev:shadbala:website_local_strength_v1:Saturn", "ev:dasha:vim:md:Venus",
"ev:dasha:vim:ad:Venus.Moon", "ev:dasha:vim:pd:Venus.Moon.Mars", "ev:dasha:nar:ad:Libra.Taurus",
"ev:transit:Saturn", "ev:dt:D1:house_7", "ev:yoga:syn_formed@D1"):
assert evidence in items, evidence
def test_birth_branches_bind_parent_range_and_their_own_intervals(data):
items = _items(_base(data))
main = items["ev:arudha:AL2"]
assert main["birth_branch"]["status"] == "branches"
assert main["birth_branch"]["parent_range_minutes"] == [-60.0, 60.0]
assert main["birth_branch"]["branch_ids"] == ["ev:arudha:AL2#br:-60_60:-60_17.78",
"ev:arudha:AL2#br:-60_60:17.8_60"]
assert items["ev:arudha:AL2#br:-60_60:17.8_60"]["value"]["sign"] == "Taurus"
# The same branch inside a wider parent range is another instance.
wider = copy.deepcopy(data["rows"])
wider[0]["participation"][0]["value"]["checked_window"] = {"before_minutes": 90, "after_minutes": 60}
ids = set(_items(_base(data, rows=wider)))
assert "ev:arudha:AL2#br:-90_60:-60_17.78" in ids and "ev:arudha:AL2#br:-60_60:-60_17.78" not in ids
assert items["ev:arudha:UL2"]["birth_branch"] == {"status": "stable", "parent_range_minutes": [-60.0, 60.0]}
def test_four_status_fields_cover_every_combination_the_fixture_holds(data):
items = _items(_base(data))
def status(evidence: str) -> tuple[str, str, str, str]:
item = items[evidence]
return (item["execution_status"], item["formation_status"], item["interpretation_status"], item["source_status"])
assert status("ev:D1:Sun") == ("executed", "not_applicable", "allowed", "computed")
assert status("ev:shadbala:website_local_strength_v1:Sun") == ("executed", "not_applicable", "allowed",
"pending_astrologer_review")
assert status("ev:shadbala:website_local_strength_v1:Saturn")[2] == "conditional"
assert items["ev:shadbala:website_local_strength_v1:Saturn"]["sensitivity"] == "parameter_sensitive"
assert status("ev:arudha:AL2") == ("executed", "not_applicable", "allowed", "cited")
assert status("ev:point:Gulika")[2:] == ("auxiliary", "cited")
assert status("ev:point:Pranapada")[2:] == ("auxiliary", "pending_original_check")
assert status("ev:point:Vighati")[2] == "blocked_source_rule"
assert status("ev:yoga:syn_formed@D1") == ("executed", "formed", "allowed", "cited")
assert status("ev:yoga:syn_candidate@D1") == ("executed", "candidate", "conditional", "pending_astrologer_review")
assert status("ev:yoga:syn_not_formed@D1")[:2] == ("executed", "not_formed")
assert status("ev:yoga:syn_not_executed@D1")[:3] == ("not_executed", "not_evaluated", "disabled")
assert status("ev:yoga:syn_disabled@D1") == ("not_executed", "not_evaluated", "disabled", "source_mismatch")
for item in items.values():
assert item["execution_status"] in ev.EXECUTION and item["formation_status"] in ev.FORMATION
assert item["interpretation_status"] in ev.INTERPRETATION and item["source_status"] in ev.SOURCE
if item["kind"] != "yoga":
assert item["formation_status"] == "not_applicable", "no fake 'formed' for values"
with pytest.raises(ValueError):
ev.status_record("executed", "formed", "maybe", "cited")
def test_edges_carry_type_scope_basis_and_review_and_only_stated_relations(data):
base = _base(data)
ids = set(_items(base))
assert base["edges"]
for edge in base["edges"]:
assert set(edge) == {"from", "to", "type", "scope", "conditions", "method_version", "basis", "review_status"}
assert edge["type"] == "depends_on", "today only engineering dependencies are stated"
assert edge["basis"]["kind"] == "engineering" and edge["review_status"] == "engineering"
assert edge["from"] in ids
pairs = {(edge["from"], edge["to"]) for edge in base["edges"]}
assert ("ev:dasha:vim:pd:Venus.Moon.Mars", "ev:dasha:vim:ad:Venus.Moon") in pairs
assert ("ev:yoga:syn_child@D1", "ev:yoga:syn_main@D1") in pairs
assert ("ev:arudha:AL2#br:-60_60:17.8_60", "ev:arudha:AL2") in pairs
# Parameter sensitivity is a status, never a `weakens` edge (§二.4).
assert not any(edge["to"].startswith("ev:shadbala:") or edge["type"] == "weakens" for edge in base["edges"])
for kind in ev.EDGE_TYPES:
record = ev.edge_record("ev:a:x", "ev:b:y", scope="test", basis_ref="test", kind=kind,
basis_kind="named_rule", review="pending")
assert record["type"] == kind and record["review_status"] == "pending"
with pytest.raises(ValueError):
ev.edge_record("ev:a:x", "ev:b:y", scope="test", basis_ref="test", kind="supports")
def test_dependency_closure_goes_deeper_than_one_level_stops_cycles_and_reports_budget(data):
edges = data["closure_edges"]
deep = ev.dependency_closure(edges, ["ev:yoga:syn_child@D1"], known={"ev:yoga:syn_child@D1", "ev:yoga:syn_main@D1",
"ev:D1:Sun"})
assert deep["status"] == "complete"
assert deep["ids"] == ["ev:yoga:syn_child@D1", "ev:yoga:syn_main@D1", "ev:D1:Sun", "ev:test:lagna"]
assert deep["missing"] == ["ev:test:lagna"], "an unheld dependency is listed, never treated as absent"
loop = ev.dependency_closure(edges, ["ev:test:loop_a"])
assert loop["status"] == "complete" and loop["ids"] == ["ev:test:loop_a", "ev:test:loop_b"]
assert loop["cycles"] == [["ev:test:loop_a", "ev:test:loop_b", "ev:test:loop_a"]]
capped = ev.dependency_closure(edges, ["ev:yoga:syn_child@D1"], budget=2)
assert capped["status"] == ev.CLOSURE_INCOMPLETE and len(capped["ids"]) == 2
# Only the requested relation types are followed.
assert ev.dependency_closure(edges, ["ev:yoga:syn_formed@D1"])["ids"] == ["ev:yoga:syn_formed@D1"]
assert ev.dependency_closure(edges, ["ev:yoga:syn_formed@D1"], types=("weakens",))["ids"] == [
"ev:yoga:syn_formed@D1", "ev:yoga:syn_candidate@D1"]
def test_snapshot_cases_from_the_review(data):
a = _snapshot(data)
assert re.fullmatch(r"snap:v2:[0-9a-f]{24}", a["snapshot_id"])
assert a["cacheable"] is True and a["subject_id"].startswith("subj:")
assert "synthetic-user-a" not in json.dumps(a), "the raw subject identifier is not kept"
# Cross-subject, same revision: no collision.
assert _snapshot(data, subject_ref=data["subject_b"])["snapshot_id"] != a["snapshot_id"]
# Same day, another observation instant: another snapshot.
later = _snapshot(data, observation=data["observation_later"])
assert later["observation_instant"] == "2030-01-15T21:45Z" and later["snapshot_id"] != a["snapshot_id"]
# Requested coverage is part of the snapshot; a non-time question has none.
covered = _snapshot(data, coverage={"start": "2030-01-15", "end": "2031-01-14"})
assert covered["snapshot_id"] != a["snapshot_id"] and a["coverage"] is None
# Calculation time is recorded but is not part of the id.
assert _snapshot(data, calculation_time="2031-01-01T00:00:00Z")["snapshot_id"] == a["snapshot_id"]
# Revision changes; a profile or version change too.
assert _snapshot(data, revision=data["revision_b"])["snapshot_id"] != a["snapshot_id"]
assert _snapshot(data, profile={**PROFILE, "varga_methods": "other"})["snapshot_id"] != a["snapshot_id"]
# No revision or no subject: the snapshot exists but must not key a cache.
assert _snapshot(data, revision=None)["cacheable"] is False
assert _snapshot(data, subject_ref=None)["cacheable"] is False
# Ayanamsa and node mode are inside the revision; they enter the profile only when it is missing.
profile = ev.calculation_profile({"ayanamsa": "raman", "node_mode": "mean"}, revision_present=True)
assert "birth_method_fields" not in profile
fallback = ev.calculation_profile({"ayanamsa": "raman", "node_mode": "mean"}, revision_present=False)
assert fallback["birth_method_fields"] == {"ayanamsa": "raman", "node_mode": "mean"}
pair = ev.pair_snapshot_record({"a": data["revision_a"], "b": data["revision_b"]}, data["observation"],
subjects={"a": data["subject_a"], "b": data["subject_b"]},
versions=VERSIONS, profile=PROFILE, calculation_time=CALC_TIME)
assert pair["cacheable"] and pair["sides"]["a"]["snapshot_id"] != pair["sides"]["b"]["snapshot_id"]
def test_parameters_change_but_sign_does_not_keeps_ids_and_hashes(data):
view = copy.deepcopy(data["view"])
view["core_chart"]["planets"]["Sun"]["degree"] = 12.5
a = _items(_base(data))
b = _items(_base(data, view=view))
assert set(a) == set(b)
assert a["ev:D1:Sun"]["content_hash"] == b["ev:D1:Sun"]["content_hash"], "the normalised result did not change"
moved = copy.deepcopy(data["view"])
moved["core_chart"]["planets"]["Sun"]["sign"] = "Taurus"
c = _items(_base(data, view=moved))
assert set(c) == set(a) and c["ev:D1:Sun"]["content_hash"] != a["ev:D1:Sun"]["content_hash"]
def test_a_retracted_rule_with_equal_values_invalidates_interpretations(data):
before = _base(data)
after = _base(data, retractions=["yoga_rules:syn_formed"])
item_before = _items(before)["ev:yoga:syn_formed@D1"]
item_after = _items(after)["ev:yoga:syn_formed@D1"]
assert item_before["content_hash"] == item_after["content_hash"], "values are equal"
assert before["snapshot_id"] != after["snapshot_id"]
assert ev.interpretation_key(before["snapshot_id"], item_before["evidence_id"], item_before["content_hash"]) != \
ev.interpretation_key(after["snapshot_id"], item_after["evidence_id"], item_after["content_hash"])
assert ev.instance_ref(before["snapshot_id"], "ev:D1:Sun") == f"{before['snapshot_id']}/ev:D1:Sun"
def test_feedback_history_pollution_changes_nothing(data):
# 占星师 2026-11-18 §一:反馈、经历、纠正、评分、历史、摘要、记忆都不进入预测证据。
plain = _base(data, body={})
polluted_rows = copy.deepcopy(data["rows"])
for row in polluted_rows:
row.update(copy.deepcopy(data["feedback_pollution"]))
polluted_view = copy.deepcopy(data["view"])
polluted_view.update(copy.deepcopy(data["feedback_pollution"]))
polluted = _base(data, rows=polluted_rows, view=polluted_view, body=copy.deepcopy(data["feedback_pollution"]))
assert json.dumps(plain, sort_keys=True, ensure_ascii=False) == json.dumps(polluted, sort_keys=True, ensure_ascii=False)
def test_page_failure_is_reported_not_hidden(data):
# Stub of a paged reader over the base (the pack's fetch tool comes later): a failed page is listed
# as missing, never read as an empty result.
base = _base(data)
pages = [base["items"][index:index + 10] for index in range(0, len(base["items"]), 10)]
def read(page: int) -> list[dict]:
if page == 1:
raise TimeoutError("page 1 failed")
return pages[page]
got, failed = [], []
for page in range(len(pages)):
try:
got.extend(read(page))
except TimeoutError:
failed.append(page)
assert failed == [1] and len(got) == len(base["items"]) - len(pages[1])
closure = ev.dependency_closure(base["edges"], [item["evidence_id"] for item in got],
known={item["evidence_id"] for item in got})
assert closure["missing"], "dependencies on the failed page are reported missing"
def test_derived_house_sources_are_per_field_and_cite_l2229(data):
item = _items(_base(data))["ev:arudha:AL2"]
fields = {source["field"] for source in item["sources"]}
assert {"start_sign", "sign", "natal_house", "occupants", "lord", "lord_natal", "reading"} <= fields
reading = next(source for source in item["sources"] if source["field"] == "reading")
assert "L2229" in reading["interpretation"] and "L2105" not in reading["interpretation"]