Ports the astrologer's _row_motion_evidence (upstream 58f37ee5b). Stored as indexes into the year's event list, so rows do not repeat hundreds of events. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXp2U3BH1SxwAGyhhbe1
336 lines
17 KiB
Python
336 lines
17 KiB
Python
"""BUG-2315 / BUG-2316 (占星师 2026-11-23 信息密度交接 §2「年度连续运动」「年度多星作用」与 §4, 产品负责人
|
|
2026-11-24 同意第 4 批): each report year's continuous Tajika motion, computed once and cached.
|
|
|
|
The scan is the astrologer's ``transit_search.build_tajika_motion_timeline`` (copied verbatim from upstream
|
|
58f37ee5b). The request for each year is the one the solar-return producer built for that year (this return
|
|
-> the next actual return, UTC, the chart's own frame); it rides on the year's ``solar_return`` field because
|
|
the frozen engine's three-year series keeps only known keys.
|
|
|
|
Cost: about 5.6 s per year on the development box. So:
|
|
|
|
* one year is scanned at most once: the result is cached on disk per year (birth input hash, settings,
|
|
place, year, the request itself, and the rule version), under ``$JYOTISH_ANNUAL_MOTION_CACHE_DIR`` or
|
|
``$JYOTISH_CACHE_DIR/annual_motion_timeline`` (default ``scratch/local/annual_motion_timeline``), mode 0600;
|
|
* at most the three report years are scanned per report;
|
|
* the uncached scans share a time budget (``$JYOTISH_ANNUAL_MOTION_BUDGET_SECONDS``, default 30 s). A year
|
|
that would not fit is not started and is recorded as ``execution_status: blocked`` with
|
|
``reason: time_budget_exceeded``; nothing about it is cached, so a later report computes it.
|
|
|
|
Storage is lossless but compact (a year is about 5 MB in the upstream shape, mostly repeated lists): an exact
|
|
contact's ``prior_motion_changes`` (every earlier ingress or station of either planet in the window) is left
|
|
out and ``expand_prior_motion_changes`` rebuilds it from ``events``; a row's ``motion_evidence.contacts`` become
|
|
``contact_refs`` (indexes into the year's ``events``, ``row_contacts`` reads them) and its ``motion_changes``
|
|
(every ingress or station of either planet) become ``motion_change_count`` (``expanded_row_motion_changes``
|
|
rebuilds them).
|
|
|
|
Claim boundary (hers): an exact contact is computed motion, not a life-event date; ``motion_evidence`` is not
|
|
a completed traditional fulfilment of the named yoga.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import copy
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import time
|
|
from functools import lru_cache
|
|
from pathlib import Path
|
|
from typing import Any, Callable
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
WIRING_VERSION = "annual-motion-v1"
|
|
CACHE_DIR_NAME = "annual_motion_timeline"
|
|
CACHE_SCHEMA = "annual-motion-timeline-cache-v1"
|
|
DEFAULT_BUDGET_SECONDS = 30.0
|
|
# Used before any year has been timed in this request: the measured cold cost plus headroom.
|
|
DEFAULT_YEAR_ESTIMATE_SECONDS = 7.0
|
|
MAX_YEARS = 3
|
|
CLAIM_BOUNDARY = "Computed motion only; no automatic named-yoga perfection or life-event prediction."
|
|
|
|
|
|
def _dict(value: Any) -> dict:
|
|
return value if isinstance(value, dict) else {}
|
|
|
|
|
|
@lru_cache(maxsize=1)
|
|
def rule_version() -> str:
|
|
"""The scan's source text plus this wiring's version: any change to either is a cache miss."""
|
|
digest = hashlib.sha256(WIRING_VERSION.encode())
|
|
for name in ("transit_search.py", "tajika_named_yoga_governed_draft.py", "report_render/annual_motion.py"):
|
|
try:
|
|
digest.update((ROOT / "scripts" / name).read_bytes())
|
|
except OSError:
|
|
digest.update(name.encode())
|
|
return f"{WIRING_VERSION}:{digest.hexdigest()[:16]}"
|
|
|
|
|
|
def cache_dir() -> Path:
|
|
explicit = os.environ.get("JYOTISH_ANNUAL_MOTION_CACHE_DIR", "").strip()
|
|
if explicit:
|
|
return Path(explicit)
|
|
root = os.environ.get("JYOTISH_CACHE_DIR", "").strip()
|
|
return (Path(root) if root else ROOT / "scratch" / "local") / CACHE_DIR_NAME
|
|
|
|
|
|
def budget_seconds() -> float:
|
|
raw = os.environ.get("JYOTISH_ANNUAL_MOTION_BUDGET_SECONDS", "").strip()
|
|
try:
|
|
value = float(raw) if raw else DEFAULT_BUDGET_SECONDS
|
|
except ValueError:
|
|
value = DEFAULT_BUDGET_SECONDS
|
|
return max(0.0, value)
|
|
|
|
|
|
def cache_key(request: dict, context: dict) -> str:
|
|
material = {"schema": CACHE_SCHEMA, "rule_version": rule_version(), "request": request, "context": context}
|
|
canonical = json.dumps(material, ensure_ascii=True, sort_keys=True, separators=(",", ":"), default=str)
|
|
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
|
|
|
|
PRIOR_RULE = ("prior_motion_changes omitted in storage: for each exact contact they are every earlier ingress or "
|
|
"station in events that shares a planet with it (upstream rule); expand_prior_motion_changes rebuilds them")
|
|
|
|
|
|
def _prior_changes(events: list[dict], position: int) -> list[dict]:
|
|
event = events[position]
|
|
planets = set(event.get("planets") or [])
|
|
return [{"kind": earlier["kind"], "planets": earlier["planets"], "timestamp_local": earlier["timestamp_local"]}
|
|
for earlier in events
|
|
if earlier["timestamp_local"] < event["timestamp_local"]
|
|
and earlier.get("kind") in ("ingress", "station") and planets & set(earlier.get("planets") or [])]
|
|
|
|
|
|
def compact_timeline(timeline: dict) -> dict:
|
|
"""Drop the derivable ``prior_motion_changes`` (about 70% of a year's bytes). Lossless."""
|
|
out = dict(timeline)
|
|
out["events"] = [{key: value for key, value in event.items() if key != "prior_motion_changes"}
|
|
for event in timeline.get("events") or []]
|
|
if any("prior_motion_changes" in event for event in timeline.get("events") or []):
|
|
out["storage"] = PRIOR_RULE
|
|
return out
|
|
|
|
|
|
def expand_prior_motion_changes(timeline: dict) -> dict:
|
|
"""Inverse of ``compact_timeline``: the upstream event shape."""
|
|
events = [dict(event) for event in timeline.get("events") or []]
|
|
out = {key: value for key, value in timeline.items() if key != "storage"}
|
|
if "storage" in timeline:
|
|
for position, event in enumerate(events):
|
|
if event.get("kind") == "exact_contact":
|
|
event["prior_motion_changes"] = _prior_changes(events, position)
|
|
out["events"] = events
|
|
return out
|
|
|
|
|
|
def _read(path: Path, key: str) -> dict | None:
|
|
try:
|
|
stored = json.loads(path.read_text(encoding="utf-8"))
|
|
except (OSError, ValueError):
|
|
return None
|
|
if not isinstance(stored, dict) or stored.get("key") != key or stored.get("rule_version") != rule_version():
|
|
return None
|
|
timeline = stored.get("timeline")
|
|
return timeline if isinstance(timeline, dict) and timeline.get("execution_status") == "executed" else None
|
|
|
|
|
|
def _write(path: Path, key: str, timeline: dict) -> None:
|
|
try:
|
|
from scripts.api_scratch_retention import write_private_json
|
|
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
|
|
from api_scratch_retention import write_private_json
|
|
try:
|
|
write_private_json(path, {"key": key, "rule_version": rule_version(), "timeline": timeline})
|
|
except OSError:
|
|
pass # an unwritable cache only costs the next report a rescan
|
|
|
|
|
|
def _scan(request: dict) -> dict:
|
|
try:
|
|
from scripts.transit_search import build_tajika_motion_timeline
|
|
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
|
|
from transit_search import build_tajika_motion_timeline
|
|
return build_tajika_motion_timeline(**request)
|
|
|
|
|
|
def cached_timeline(request: dict, context: dict, *, may_compute: Callable[[], bool] = lambda: True,
|
|
scan: Callable[[dict], dict] = _scan) -> tuple[dict, dict]:
|
|
"""(compact timeline or a blocked record, {cache: hit|miss|skipped, seconds})."""
|
|
key = cache_key(request, context)
|
|
path = cache_dir() / f"{key}.json"
|
|
started = time.monotonic()
|
|
found = _read(path, key)
|
|
if found is not None:
|
|
return found, {"cache": "hit", "seconds": round(time.monotonic() - started, 3)}
|
|
if not may_compute():
|
|
return ({"execution_status": "blocked", "reason": "time_budget_exceeded",
|
|
"claim_boundary": "Continuous motion for this year was not computed within this report's time budget; "
|
|
"nothing is inferred from its absence."},
|
|
{"cache": "skipped", "seconds": 0.0})
|
|
try:
|
|
timeline = compact_timeline(scan(dict(request)))
|
|
except (ValueError, TypeError, KeyError, OverflowError) as exc:
|
|
return ({"execution_status": "blocked", "reason": f"motion_scan_failed:{type(exc).__name__}",
|
|
"claim_boundary": CLAIM_BOUNDARY}, {"cache": "miss", "seconds": round(time.monotonic() - started, 3)})
|
|
_write(path, key, timeline)
|
|
return timeline, {"cache": "miss", "seconds": round(time.monotonic() - started, 3)}
|
|
|
|
|
|
def _year_packs(packet: dict) -> tuple[dict, list[tuple[str, dict]]]:
|
|
timing = _dict(_dict(packet.get("worksheets")).get("timing_and_predictive_systems"))
|
|
years = _dict(_dict(timing.get("annual_tajika_series")).get("years"))
|
|
packs = [(str(year), pack) for year, pack in sorted(years.items(), key=lambda item: str(item[0])) if isinstance(pack, dict)]
|
|
primary = _dict(timing.get("annual_tajika_pack"))
|
|
if not packs and primary:
|
|
packs = [(str(_dict(primary.get("profile")).get("target_year") or ""), primary)]
|
|
return primary, packs[:MAX_YEARS]
|
|
|
|
|
|
def _context(pack: dict) -> dict:
|
|
profile = _dict(pack.get("profile"))
|
|
data = _dict(_dict(pack.get("solar_return")).get("data"))
|
|
return {
|
|
"input_hash": profile.get("input_hash"),
|
|
"profile_hash": profile.get("profile_hash"),
|
|
"target_year": profile.get("target_year"),
|
|
"annual_location": data.get("annual_location"),
|
|
}
|
|
|
|
|
|
ROW_CHANGES_RULE = ("motion_changes omitted in storage: every ingress or station in the year's events of either "
|
|
"planet of the row (upstream rule), rebuilt by expanded_row_motion_changes; contacts stored as "
|
|
"contact_refs, indexes into the year's motion_timeline.events")
|
|
|
|
|
|
def _event_key(event: dict) -> tuple:
|
|
return (event.get("kind"), tuple(event.get("planets") or ()), event.get("timestamp_local"))
|
|
|
|
|
|
def _compact_row_evidence(evidence: Any, index: dict) -> Any:
|
|
"""A row's contacts as indexes into the year's events, its derivable motion changes as a count. Lossless."""
|
|
if not isinstance(evidence, dict) or "motion_changes" not in evidence:
|
|
return evidence
|
|
out = {key: value for key, value in evidence.items() if key not in ("motion_changes", "contacts")}
|
|
out["contact_refs"] = [index[_event_key(item)] for item in evidence.get("contacts") or []]
|
|
out["contact_count"] = len(out["contact_refs"])
|
|
out["motion_change_count"] = len(evidence.get("motion_changes") or [])
|
|
out["storage"] = ROW_CHANGES_RULE
|
|
if isinstance(evidence.get("first_contact"), dict):
|
|
out["first_contact"] = {k: v for k, v in evidence["first_contact"].items() if k != "prior_motion_changes"}
|
|
return out
|
|
|
|
|
|
def row_contacts(evidence: dict, timeline: dict) -> list[dict]:
|
|
"""A row's contacts in time order, from its refs."""
|
|
events = timeline.get("events") or []
|
|
return [events[i] for i in _dict(evidence).get("contact_refs") or [] if isinstance(i, int) and 0 <= i < len(events)]
|
|
|
|
|
|
def timeline_pointer(timeline: dict) -> dict:
|
|
"""What the named-yoga field keeps: the scan's identity, not a second copy of its events."""
|
|
out = {key: timeline[key] for key in ("execution_status", "reason", "range", "profile", "method", "claim_boundary") if key in timeline}
|
|
if isinstance(timeline.get("events"), list):
|
|
out["event_count"] = len(timeline["events"])
|
|
out["events_at"] = "tajika_condition_status_pack.motion_timeline.events"
|
|
return out
|
|
|
|
|
|
def _year_condition_pack(pack: dict, timeline: dict | None, request: dict | None) -> tuple[dict, dict | None]:
|
|
"""(condition status pack, named-yoga field with motion) for one year."""
|
|
try:
|
|
from scripts.annual_tajika_pack import _tajika_condition_status_pack
|
|
from scripts.tajika_named_yoga_authority import build_tajika_named_yoga_authority
|
|
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
|
|
from annual_tajika_pack import _tajika_condition_status_pack
|
|
from tajika_named_yoga_authority import build_tajika_named_yoga_authority
|
|
motion = _dict(_dict(pack.get("solar_return")).get("tajika_motion"))
|
|
inputs = motion.get("named_yoga_inputs")
|
|
authority = None
|
|
if isinstance(inputs, dict) and inputs:
|
|
executed = isinstance(timeline, dict) and timeline.get("execution_status") == "executed"
|
|
try:
|
|
authority = build_tajika_named_yoga_authority(
|
|
inputs, **({"motion_request": request, "motion_timeline": timeline} if executed else {}))
|
|
except ValueError as exc: # epoch / profile mismatch: keep the static rows, say why
|
|
authority = build_tajika_named_yoga_authority(inputs)
|
|
timeline = {"execution_status": "blocked", "reason": f"epoch_profile_mismatch:{exc}", "claim_boundary": CLAIM_BOUNDARY}
|
|
if not executed or authority.get("motion_timeline", {}).get("execution_status") != "executed":
|
|
authority["motion_timeline"] = timeline or {"execution_status": "not_requested"}
|
|
field = ({"status": "partial_verified" if authority.get("status") == "authority_ready" else authority.get("status", "blocked"),
|
|
"producer": "Tajika Named Yoga Authority", "data": authority,
|
|
"data_contract": "governed_named_yoga_authority_surface",
|
|
"input_contract": "upstream_motion_house_strength_relation_role_inputs"}
|
|
if isinstance(authority, dict) else {"data": {"motion_timeline": timeline or {"execution_status": "not_requested"}}})
|
|
condition = _tajika_condition_status_pack(field)
|
|
index = {_event_key(event): i for i, event in enumerate(_dict(condition.get("motion_timeline")).get("events") or [])}
|
|
for row in condition.get("rows") or []:
|
|
if isinstance(row, dict) and "motion_evidence" in row:
|
|
row["motion_evidence"] = _compact_row_evidence(row["motion_evidence"], index)
|
|
if isinstance(authority, dict):
|
|
data = field["data"]
|
|
data["motion_timeline"] = timeline_pointer(_dict(data.get("motion_timeline")))
|
|
for row in data.get("rows") or []:
|
|
if isinstance(row, dict) and "motion_evidence" in row:
|
|
row["motion_evidence"] = _compact_row_evidence(row["motion_evidence"], index)
|
|
return condition, field
|
|
return condition, None
|
|
|
|
|
|
def attach_annual_motion(packet: dict, *, clock: Callable[[], float] = time.monotonic,
|
|
scan: Callable[[dict], dict] = _scan) -> dict:
|
|
"""Per report year: ``tajika_condition_status_pack`` with that year's own ``motion_timeline``.
|
|
|
|
Returns a small run record (also stored on the series as ``motion_run``). Never raises for a
|
|
missing or blocked year; the report renders without it.
|
|
"""
|
|
primary, packs = _year_packs(packet)
|
|
budget = budget_seconds()
|
|
started = clock()
|
|
durations: list[float] = []
|
|
run: dict[str, Any] = {"budget_seconds": budget, "rule_version": rule_version(), "years": {}}
|
|
|
|
def may_compute() -> bool:
|
|
estimate = max(durations) if durations else DEFAULT_YEAR_ESTIMATE_SECONDS
|
|
return clock() - started + estimate <= budget
|
|
|
|
primary_year = str(_dict(primary.get("profile")).get("target_year") or "")
|
|
for year, pack in packs:
|
|
motion = _dict(_dict(pack.get("solar_return")).get("tajika_motion"))
|
|
request = motion.get("request") if isinstance(motion.get("request"), dict) else None
|
|
status = _dict(motion.get("request_status"))
|
|
if pack.get("status") == "blocked":
|
|
timeline, info = {"execution_status": "blocked", "reason": "annual_year_blocked"}, {"cache": "none", "seconds": 0.0}
|
|
elif request is None:
|
|
reason = status.get("reason") if status.get("status") == "blocked" else "motion_request_missing"
|
|
timeline = {"execution_status": "blocked" if status.get("status") == "blocked" else "not_requested",
|
|
"reason": reason, "claim_boundary": "Annual motion request unavailable; static structure is retained."}
|
|
info = {"cache": "none", "seconds": 0.0}
|
|
else:
|
|
timeline, info = cached_timeline(request, _context(pack), may_compute=may_compute, scan=scan)
|
|
if info["cache"] == "miss":
|
|
durations.append(info["seconds"])
|
|
condition, field = _year_condition_pack(pack, timeline, request)
|
|
pack["tajika_condition_status_pack"] = condition
|
|
if year == primary_year and primary is not pack and primary:
|
|
primary["tajika_condition_status_pack"] = condition
|
|
if field is not None:
|
|
primary["tajika_named_yogas"] = field
|
|
elif pack is primary and field is not None:
|
|
primary["tajika_named_yogas"] = field
|
|
run["years"][year] = {"execution_status": _dict(condition.get("motion_timeline")).get("execution_status"), **info}
|
|
run["seconds"] = round(clock() - started, 3)
|
|
timing = _dict(_dict(packet.get("worksheets")).get("timing_and_predictive_systems"))
|
|
if isinstance(timing.get("annual_tajika_series"), dict):
|
|
timing["annual_tajika_series"]["motion_run"] = run
|
|
return run
|
|
|
|
|
|
def year_condition_pack(pack: Any) -> dict:
|
|
return _dict(_dict(pack).get("tajika_condition_status_pack"))
|
|
|
|
|
|
def expanded_row_motion_changes(row: dict, timeline: dict) -> list[dict]:
|
|
"""A row's ``motion_evidence.motion_changes`` in the upstream shape, rebuilt from the year's events."""
|
|
planets = set(_dict(row).get("planets") or [])
|
|
return [dict(event) for event in timeline.get("events") or []
|
|
if event.get("kind") in ("ingress", "station") and planets & set(event.get("planets") or [])]
|