Fictional-chart facts grow 119,739 -> 126,181; budget unchanged at 140,000. Test sessions keep the motion cache in a temporary directory. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXp2U3BH1SxwAGyhhbe1
344 lines
19 KiB
Python
344 lines
19 KiB
Python
"""Reading facts for the model-written report reading (issue #113 R1).
|
||
|
||
Clearly fictional chart only. The facts must be copies of the report's own
|
||
packet (no new algorithm), the flag must default off with the response
|
||
unchanged, and the flag must be part of the report cache key.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import copy
|
||
import json
|
||
import os
|
||
|
||
import pytest
|
||
|
||
import scripts.professional_report_reference as reference
|
||
from scripts.consult_card_domain_facts import dig
|
||
from scripts.jyotish_engine import build_professional_report_reference_packet, cmd_full_reading
|
||
from scripts.professional_report_reference import _export_args, build_professional_report_reference
|
||
from scripts.report_render.reading_facts import READING_DOMAINS, build_report_reading_facts
|
||
from tests.test_report_reader_main import FICTIONAL
|
||
|
||
|
||
@pytest.fixture(scope="module")
|
||
def chart(tmp_path_factory):
|
||
case = dict(FICTIONAL)
|
||
reading = cmd_full_reading(type("Args", (), case)())
|
||
packet = dict(build_professional_report_reference_packet(reading, _export_args(case), []))
|
||
packet["report_version"] = "pl9_personal_long_report.v3"
|
||
# BUG-2318: as the report API does (BUG-2315), each year's continuous motion is on the packet, so the
|
||
# size budget below covers the motion summaries. Cache isolated to this module.
|
||
from scripts.report_render.annual_motion import attach_annual_motion
|
||
saved = os.environ.get("JYOTISH_ANNUAL_MOTION_CACHE_DIR")
|
||
os.environ["JYOTISH_ANNUAL_MOTION_CACHE_DIR"] = str(tmp_path_factory.mktemp("annual_motion"))
|
||
try:
|
||
attach_annual_motion(packet)
|
||
finally:
|
||
if saved is None:
|
||
os.environ.pop("JYOTISH_ANNUAL_MOTION_CACHE_DIR", None)
|
||
else:
|
||
os.environ["JYOTISH_ANNUAL_MOTION_CACHE_DIR"] = saved
|
||
return case, reading, packet
|
||
|
||
|
||
def test_reading_facts_are_packet_leaves(chart) -> None:
|
||
_case, reading, packet = chart
|
||
before = json.dumps(packet, ensure_ascii=False, sort_keys=True, default=str)
|
||
facts = build_report_reading_facts(packet, reading, minute_confirmed=True, today="2026-04-07")
|
||
# Building the facts never touches the report's packet.
|
||
assert json.dumps(packet, ensure_ascii=False, sort_keys=True, default=str) == before
|
||
# 原值:report-reading-facts-v2
|
||
# 新值:report-reading-facts-v3
|
||
# 原因:11-12 审核要求报告事实包提供模式、参与原因和计算边界。
|
||
assert facts["schema"] == "report-reading-facts-v3"
|
||
assert sorted(facts["domains"]) == sorted(READING_DOMAINS)
|
||
for name, planet in facts["planets"].items():
|
||
assert planet["d1_sign"] == dig(packet, f"core_chart.planets.{name}.sign")
|
||
assert planet["d1_house"] == dig(packet, f"core_chart.planets.{name}.house")
|
||
assert planet["d1_dignity"] == dig(packet, f"core_chart.planets.{name}.status")
|
||
for key in ("sign", "lord", "nakshatra"):
|
||
assert facts["ascendant"][key] == dig(packet, f"core_chart.ascendant.{key}")
|
||
current = dig(packet, "worksheets.timing_and_predictive_systems.dasha.current_dasha")
|
||
# 原值: {"lord", "start", "end"};新值: 另带 evidence_id(ev:dasha:vim:md:<主星>@<起始日>),与问答卡同号
|
||
# 原因: BUG-1976 证据包第一步(产品负责人 2026-11-18):统一证据编号
|
||
# 原值: ev:dasha:vim:md:<主星>@<起始日>;新值: ev:dasha:vim:md:<主星>(按主星链,不带日期)
|
||
# 原因: 证据编号定稿时大运一段按主星链标识(scripts/consult_facts/evidence_ids.py dasha_id,与前端
|
||
# dashaEvidenceId 同式),这条断言没有跟着改,此后一直失败(BUG-2028 修)。
|
||
assert facts["timing"]["mahadasha"] == {"evidence_id": f"ev:dasha:vim:md:{current['lord']}",
|
||
"lord": current["lord"], "start": current["start"], "end": current["end"]}
|
||
rows = current["antardasha_timeline"]
|
||
index = next(i for i, row in enumerate(rows) if row.get("is_current") is True)
|
||
assert facts["timing"]["antardasha"]["lord"] == rows[index]["lord"]
|
||
assert [row["lord"] for row in facts["timing"]["next_antardashas"]] == [row["lord"] for row in rows[index + 1:index + 3]]
|
||
# 原值:'"status"'、'"citation"'、"references/" 一律不进模型输入,总长 < 20000
|
||
# 新值:内部 leaf 的 path / check / citation 键仍不进;技法状态(executed / blocked / withheld)、
|
||
# 依据来源(references/ 条目)与证据路径进入契约;写作输入的紧凑 JSON 总长 < 80000
|
||
# 原因:产品 2026-11-07 占星师方案 item 10:reading_facts 契约要带证据路径、方法差异和阻塞状态
|
||
encoded = json.dumps(facts, ensure_ascii=False, separators=(",", ":"))
|
||
for marker in ('"path"', '"check"', '"citation"'):
|
||
assert marker not in encoded
|
||
# 原值:< 80000
|
||
# 新值:< 100000
|
||
# 原因:BUG-2036,产品负责人 2026-11-20 同意。事实包随 BUG-2013 / 2019 / 2021 / 2024(换座线依赖、
|
||
# 逐条依据、行运回到本命星座、Sade Sati 与 Kantaka)长到约 87,600;逐项查过没有明显冗余
|
||
# (domains 约 23,300、evidence_grades 约 17,500、yogas 约 8,700、planets 约 6,700)。
|
||
# BUG-2246 原值 < 100000;新值 < 120000;原因:产品负责人 2026-11-23 加「家人、学业与居住」一节,
|
||
# 事实包多四个领域(parents / children / education / migration 共约 9,100)和四类结论的依据表,约 113,400。
|
||
# BUG-2289–2296 原值 < 120000;新值 < 140000;原因:占星师 2026-11-23 信息密度交接,负责人 2026-11-24 同意分批补回
|
||
# 已算出的结构(完整定位链、Argala、年度格局参与星、每条格局的支持与限制,约 7,000)和她的作用路径(约 10,000),
|
||
# 这张虚构盘约 130,800。
|
||
# BUG-2318: with each year's motion summary (at most 20 events a year, about 2,100 per year) this chart is
|
||
# about 126,200; the budget is unchanged.
|
||
assert len(encoded) < 140_000
|
||
|
||
|
||
def test_each_annual_year_carries_a_bounded_motion_summary(chart) -> None:
|
||
"""BUG-2318: her §4 fields per year for the writer, bounded, with her claim boundary said once."""
|
||
_case, reading, packet = chart
|
||
facts = build_report_reading_facts(packet, reading, minute_confirmed=True, today="2026-04-07")
|
||
years = facts["annual"]["years"]
|
||
assert len(years) == 3
|
||
starts = []
|
||
for row in years:
|
||
motion = row["motion"]
|
||
assert motion["status"] == "computed"
|
||
assert 0 < len(motion["events"]) <= 20
|
||
assert [event["date"] for event in motion["events"]] == sorted(event["date"] for event in motion["events"])
|
||
assert set(motion["event_counts"]) == {"精确成相", "换座", "停滞"}
|
||
assert all(event["kind"] in {"精确成相", "换座", "停滞"} and event["planets"] for event in motion["events"])
|
||
starts.append(motion["range"]["start"])
|
||
assert len(set(starts)) == 3
|
||
assert "不是人生事件日期" in facts["annual"]["motion_boundary_zh"]
|
||
assert "已按传统完成兑现" in facts["annual"]["motion_boundary_zh"]
|
||
|
||
|
||
def test_reading_facts_carry_the_full_contract(chart) -> None:
|
||
"""产品 2026-11-07 占星师方案 item 10: every layer of the contract is present and packet-sourced."""
|
||
_case, reading, packet = chart
|
||
facts = build_report_reading_facts(packet, reading, minute_confirmed=True, today="2026-04-07")
|
||
for key in (
|
||
"birth_parameters", "functional", "houses", "domains", "special_points", "jaimini", "yogas",
|
||
"timing", "dasha_families", "transits", "strengths", "kp", "annual", "evidence",
|
||
"method_differences", "blocked_states", "shared_techniques",
|
||
):
|
||
assert facts[key], key
|
||
# No name and no coordinates in the birth parameters.
|
||
assert set(facts["birth_parameters"]) <= {
|
||
"date", "time", "tz", "ayanamsa", "node_mode", "house_system", "position_mode", "dasha_year_days", "minute_confirmed",
|
||
}
|
||
assert len(facts["houses"]) == 12
|
||
# Domain vargas per the adjudicators: wealth D2 + D11, career D10, marriage D9.
|
||
assert facts["domains"]["wealth"]["vargas"][:2] == ["D2", "D11"]
|
||
assert set(facts["domains"]["wealth"]["varga_charts"]) >= {"D2", "D11"}
|
||
wealth_ids = {row["id"] for row in facts["domains"]["wealth"]["participation"]}
|
||
assert {"A2", "A11", "A10", "D2", "D11"} <= wealth_ids
|
||
career_ids = {row["id"] for row in facts["domains"]["career"]["participation"]}
|
||
assert {"D10", "A10", "AK", "AmK", "Karakamsha"} <= career_ids
|
||
marriage = {row["id"]: row for row in facts["domains"]["marriage"]["participation"]}
|
||
assert {"UL", "A7", "DK"} <= set(marriage)
|
||
assert marriage["A7"]["state"] == "executed"
|
||
assert marriage["A7"]["value"] == dig(packet, "worksheets.advanced_systems.jaimini.arudha_padas.padas.A7.sign")
|
||
# Dual-track timing: Narayana carries dates (birth date + age), not only sign and lord.
|
||
narayana = facts["timing"]["narayana"]
|
||
md = dig(packet, "worksheets.timing_and_predictive_systems.narayana_dasha.current_dasha.md")
|
||
assert narayana["mahadasha"]["sign"] == md["sign"]
|
||
birth = packet["birth_info"]["date"]
|
||
# 原值:整岁落在生日(出生日期 + 年龄,365.2425 天年取整日),与咨询层 / 上游的 365.25 天年差 1 天。
|
||
# 新值:读引擎按未取整年龄算出的 start_date(出生时刻 + 年龄 × 365.25 天),各消费方同一日期。
|
||
# 原因:三方对照 2026-11-07:产品侧实现缺陷(取整后换日期)
|
||
assert narayana["mahadasha"]["start"] == md["start_date"]
|
||
assert abs(int(narayana["mahadasha"]["start"][:4]) - (int(birth[:4]) + int(md["start_age"]))) <= 1
|
||
assert "pratyantardasha" in facts["timing"]
|
||
# Transits: the four slow planets with houses from several reference points.
|
||
for planet in ("Jupiter", "Saturn", "Rahu", "Ketu"):
|
||
assert facts["transits"]["planets"][planet]["sign"] == dig(
|
||
packet, f"worksheets.timing_and_predictive_systems.transit_positions.planets.{planet}.sign"
|
||
)
|
||
assert "double_transit" in facts["transits"]
|
||
# Functional vs natural conflicts are stated, Yogas are candidates with their conditions.
|
||
functional = dig(packet, "worksheets.strengths_and_scores.functional_benefic_malefic")
|
||
assert facts["functional"]["functional_benefics"] == functional["functional_benefics"]
|
||
for row in facts["functional"]["natural_vs_functional_conflicts"]:
|
||
assert row["natural"] != row["functional"]
|
||
from scripts.report_render.yoga_status_words import report_yoga_table, yoga_status
|
||
|
||
_layer, yoga_rows, _observations = report_yoga_table(packet.copy())
|
||
expected = [(row["name"], *yoga_status(row)) for row, _display in yoga_rows]
|
||
assert [(row["name"], row["state"], row["state_text"]) for row in facts["yogas"]] == expected
|
||
assert any("conditions" in row for row in facts["yogas"])
|
||
# The audit rows the skill requires reach the writer.
|
||
techniques = {row["technique"] for row in facts["evidence"]["technique_audit"]}
|
||
assert {"Functional Benefic/Malefic", "MEVG / Global Web Evidence", "Real Case Calibration"} <= techniques
|
||
assert "audit:MEVG / Global Web Evidence" in facts["blocked_states"]["blocked"]
|
||
assert "kp" in facts["blocked_states"]["parameter_sensitive"]
|
||
assert facts["evidence"]["d1_d60_ledger"]["formal_traditional_division_count"] == 20
|
||
assert facts["evidence"]["d1_d60_ledger"]["research_generic_dn_division_count"] == 40
|
||
|
||
|
||
def test_withheld_varga_houses_stay_out_without_a_confirmed_minute(chart) -> None:
|
||
_case, reading, packet = chart
|
||
facts = build_report_reading_facts(packet, reading, minute_confirmed=False)
|
||
assert facts["minute_confirmed"] is False
|
||
# 原值:assert "出生时间精度不够" not in facts(被扣下的层整条不出现)
|
||
# 新值:被扣下的层仍不给数值,但以 withheld 状态和原因写明,模型据此说明这一层没有参与
|
||
# 原因:产品 2026-11-07 占星师方案 item 10:契约要带阻塞状态,不能静默跳过
|
||
health = facts["domains"]["health"]
|
||
assert health["varga_charts"]["D30"] == "出生时间精度不够,不参与"
|
||
d30 = next(row for row in health["participation"] if row["id"] == "D30")
|
||
assert d30 == {
|
||
"id": "D30", "state": "withheld", "reason": "出生时间精度不够,不参与", "source": d30["source"],
|
||
"execution_status": "blocked", "interpretation_usage": "not_used", "blocked_reason": "missing_input",
|
||
}
|
||
assert facts["special_points"]["Ghati_Lagna"] == "出生时间精度不够,不参与"
|
||
assert "health:D30" in facts["blocked_states"]["withheld"]
|
||
|
||
|
||
class _Handler:
|
||
def __init__(self, case: dict, reading: dict) -> None:
|
||
self.case = case
|
||
self.reading = reading
|
||
self.calls = 0
|
||
|
||
def _high_rigor_birth_payload(self, body: dict) -> dict:
|
||
payload = {key: value for key, value in self.case.items() if key != "name"}
|
||
if body.get("today"):
|
||
payload["today"] = body["today"]
|
||
return payload
|
||
|
||
def _compute_full_reading_for_thematic(self, _birth: dict, *, engine_context=None) -> dict:
|
||
self.calls += 1
|
||
return self.reading
|
||
|
||
|
||
@pytest.fixture
|
||
def stubbed(chart, monkeypatch, tmp_path):
|
||
import scripts.consult_full_data_cache as cache
|
||
|
||
case, reading, packet = chart
|
||
|
||
def _dir(name: str = "consult_full_data_cache"):
|
||
path = tmp_path / name
|
||
path.mkdir(parents=True, exist_ok=True)
|
||
return path
|
||
|
||
class _Engine:
|
||
def build_professional_report_reference_packet(self, _reading, _args, _packs, **_kwargs):
|
||
return copy.deepcopy(packet)
|
||
|
||
def render_pl9_markdown(self, _packet):
|
||
return "reference"
|
||
|
||
monkeypatch.setattr(cache, "cache_dir", _dir)
|
||
monkeypatch.setattr(reference, "render_full_data_markdown", lambda p: "en-body" if p.get("report_language") == "en" else "zh-body")
|
||
monkeypatch.setattr(reference, "report_density_packet", lambda _packet: {"facts": 1})
|
||
monkeypatch.setattr(reference, "render_dasha_applicability", lambda _packet, language="zh": f"app-{language}")
|
||
monkeypatch.setattr(reference, "clean_reader_appendix_markdown", lambda text: text)
|
||
monkeypatch.setenv("JYOTISH_REPORT_RENDER_FAST", "0")
|
||
monkeypatch.setenv("JYOTISH_REPORT_REFERENCE_CACHE", "0")
|
||
return _Handler(case, reading), _Engine()
|
||
|
||
|
||
def _body(**extra) -> dict:
|
||
body = {"format": "markdown", "edition": "full_data", "include_fact_tables": True, "languages": ["zh"], "today": "2026-04-07"}
|
||
body.update(extra)
|
||
return body
|
||
|
||
|
||
def _dumps(result: dict) -> str:
|
||
return json.dumps(result, ensure_ascii=False, sort_keys=True, default=str)
|
||
|
||
|
||
def test_flag_off_response_is_unchanged(stubbed) -> None:
|
||
handler, engine = stubbed
|
||
absent = build_professional_report_reference(handler, _body(), engine=engine)
|
||
off = build_professional_report_reference(handler, _body(include_reading_facts=False), engine=engine)
|
||
assert _dumps(absent) == _dumps(off)
|
||
assert "reading_facts" not in absent
|
||
assert sorted(absent) == ["edition", "fact_table_packet", "format", "markdown", "reader_dasha_applicability", "report_version"]
|
||
|
||
|
||
def test_report_fact_cache_separates_the_same_chart_by_gender(stubbed, monkeypatch) -> None:
|
||
handler, engine = stubbed
|
||
monkeypatch.setenv("JYOTISH_REPORT_REFERENCE_CACHE", "1")
|
||
monkeypatch.setenv("GITHUB_SHA", "report-facts-gender-test")
|
||
rendered_genders = []
|
||
render_yoga_conditions = reference.report_yoga_conditions
|
||
|
||
def capture_yoga_conditions(packet, *, gender):
|
||
rendered_genders.append(gender)
|
||
return render_yoga_conditions(packet, gender=gender)
|
||
|
||
monkeypatch.setattr(reference, "report_yoga_conditions", capture_yoga_conditions)
|
||
for provided, expected in [("female", "female"), ("male", "male"), (None, "unknown"), ("female", "female")]:
|
||
result = build_professional_report_reference(
|
||
handler, _body(include_reading_facts=True, gender=provided), engine=engine,
|
||
)
|
||
assert result["reading_facts"]["subject"]["gender"] == expected
|
||
assert handler.calls == 3
|
||
assert rendered_genders == ["female", "male"]
|
||
|
||
|
||
def test_flag_on_adds_reading_facts_and_keeps_the_report(stubbed) -> None:
|
||
handler, engine = stubbed
|
||
plain = build_professional_report_reference(handler, _body(), engine=engine)
|
||
with_facts = build_professional_report_reference(
|
||
handler, _body(include_reading_facts=True, birth_time_accuracy="confirmed", hour=9, minute=15), engine=engine,
|
||
)
|
||
facts = with_facts.pop("reading_facts")
|
||
assert _dumps(with_facts) == _dumps(plain)
|
||
# 原值:report-reading-facts-v2
|
||
# 新值:report-reading-facts-v3
|
||
# 原因:11-12 审核要求报告事实包提供模式、参与原因和计算边界。
|
||
assert facts["schema"] == "report-reading-facts-v3"
|
||
assert facts["minute_confirmed"] is True
|
||
# 原值:facts["today"]。新值:facts["observation_date"]。
|
||
# 原因:v3 更名为观察日期,请求仍用 today,传入的日期值保持相同。
|
||
assert facts["observation_date"] == "2026-04-07"
|
||
assert "gaps" not in facts
|
||
|
||
|
||
def test_reading_facts_failure_never_fails_the_report(stubbed, monkeypatch) -> None:
|
||
import scripts.report_render.reading_facts as module
|
||
|
||
handler, engine = stubbed
|
||
|
||
def broken(*_args, **_kwargs):
|
||
raise RuntimeError("boom")
|
||
|
||
monkeypatch.setattr(module, "build_report_reading_facts", broken)
|
||
result = build_professional_report_reference(handler, _body(include_reading_facts=True), engine=engine)
|
||
assert result["markdown"] == "zh-body"
|
||
assert result["reading_facts"]["gaps"] == ["reading_facts_unavailable"]
|
||
|
||
|
||
def test_reading_flag_is_part_of_the_report_cache_key(stubbed, monkeypatch) -> None:
|
||
handler, engine = stubbed
|
||
monkeypatch.setenv("JYOTISH_REPORT_REFERENCE_CACHE", "1")
|
||
monkeypatch.setenv("GITHUB_SHA", "reading-cache-test")
|
||
build_professional_report_reference(handler, _body(), engine=engine)
|
||
build_professional_report_reference(handler, _body(include_reading_facts=True), engine=engine)
|
||
assert handler.calls == 2
|
||
cached = build_professional_report_reference(handler, _body(include_reading_facts=True), engine=engine)
|
||
assert handler.calls == 2
|
||
assert "reading_facts" in cached
|
||
|
||
|
||
def test_reading_birth_window_is_part_of_the_report_cache_key(stubbed, monkeypatch) -> None:
|
||
handler, engine = stubbed
|
||
monkeypatch.setenv("JYOTISH_REPORT_REFERENCE_CACHE", "1")
|
||
monkeypatch.setenv("GITHUB_SHA", "reading-birth-window-cache-test")
|
||
body = _body(include_reading_facts=True, birth_time_accuracy="confirmed", hour=5, minute=40,
|
||
reading_minute_confirmed=False)
|
||
windows = [{"before_minutes": 40, "after_minutes": 79, "source": "shichen"},
|
||
{"before_minutes": 0, "after_minutes": 20, "source": "user_stated"}]
|
||
labels = ["按填写时给的范围(前 40 分钟、后 79 分钟)",
|
||
"按填写时给的范围(前 0 分钟、后 20 分钟)"]
|
||
for window, label in zip((*windows, windows[-1]), (*labels, labels[-1])):
|
||
result = build_professional_report_reference(handler, {**body, "birth_time_window": window}, engine=engine)
|
||
facts = result["reading_facts"]
|
||
assert facts["minute_confirmed"] is False
|
||
assert facts["birth_precision"]["window"] == {**window, "label_zh": label}
|
||
assert facts["evidence_grades"]["precision_policy"] == "birth_record_window_v1"
|
||
assert handler.calls == 2
|