fix(consult): date the full-data cache and slim the model card

The cache key now includes the request date, and files older than two days are removed. The model card keeps values only. Parashari aspects are copied from the engine. Saving a chart warms the packet without blocking the response.

Biography severe conflicts rose from 1 to 3, so this is not accepted for merge. Not pushed.
This commit is contained in:
jesse-ux
2026-10-09 10:00:45 +08:00
parent 3874a328a5
commit 16f9f86843
20 changed files with 976 additions and 23 deletions
+80 -10
View File
@@ -1,7 +1,9 @@
"""Cache the full-data report packet for the consult card.
The key is chart identity + ayanamsa + node mode + engine version.
The key is chart identity + ayanamsa + node mode + engine version
+ the reference date used for current dasha, transits and the year chart.
The file name is a hash. Birth data stays inside the scratch file.
Files older than two days are removed.
"""
from __future__ import annotations
@@ -9,13 +11,15 @@ from __future__ import annotations
import hashlib
import json
import time
from datetime import date
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Callable
ROOT = Path(__file__).resolve().parents[1]
CACHE_SCHEMA = "consult-full-data-cache-v1"
CACHE_SCHEMA = "consult-full-data-cache-v2"
SLOW_MISS_SECONDS = 20.0
KEEP_SECONDS = 2 * 24 * 60 * 60
PacketBuilder = Callable[[dict[str, Any]], dict[str, Any]]
@@ -41,7 +45,19 @@ def _number(value: Any) -> int | float:
return number
def identity_from_body(body: dict[str, Any]) -> dict[str, Any]:
def reference_date_from_body(body: dict[str, Any], *, today: date | None = None) -> str:
"""One date for dasha, transits and the year chart. Request first, else the server day."""
for key in ("today", "transit_date"):
raw = body.get(key)
if isinstance(raw, str) and len(raw) >= 10:
try:
return date.fromisoformat(raw[:10]).isoformat()
except ValueError:
continue
return (today or date.today()).isoformat()
def identity_from_body(body: dict[str, Any], *, today: date | None = None) -> dict[str, Any]:
"""Birth fields are required. Missing keys raise KeyError so the caller can gap."""
node = body.get("node_mode", body.get("nodeMode", "mean"))
ayanamsa = body.get("ayanamsa", "lahiri")
@@ -60,6 +76,7 @@ def identity_from_body(body: dict[str, Any]) -> dict[str, Any]:
"ayanamsa": str(ayanamsa),
"node_mode": str(node or "mean"),
"engine_version": engine_version(),
"reference_date": reference_date_from_body(body, today=today),
}
@@ -72,6 +89,21 @@ def _cache_path(identity: dict[str, Any]) -> Path:
return cache_dir() / f"{cache_key(identity)}.json"
def prune_cache(now: float | None = None) -> int:
"""Drop cache files last written more than two days ago."""
cutoff = (time.time() if now is None else now) - KEEP_SECONDS
removed = 0
folder = cache_dir()
for path in folder.glob("*.json"):
try:
if path.stat().st_mtime < cutoff:
path.unlink()
removed += 1
except OSError:
continue
return removed
def get_or_build(
identity: dict[str, Any],
builder: PacketBuilder | None = None,
@@ -79,6 +111,7 @@ def get_or_build(
clock: Callable[[], float] | None = None,
) -> dict[str, Any]:
"""Return the packet. A miss calls builder once and stores the packet."""
prune_cache()
now = clock or time.perf_counter
started = now()
path = _cache_path(identity)
@@ -101,14 +134,29 @@ def get_or_build(
}
def _attach_graha_drishti(packet: dict[str, Any], reading: dict[str, Any]) -> dict[str, Any]:
"""Copy the engine's whole-sign aspects onto the consult packet. Do not recompute."""
modules = reading.get("modules") if isinstance(reading, dict) else None
aspects = modules.get("aspects") if isinstance(modules, dict) else None
rows = aspects.get("house_aspects") if isinstance(aspects, dict) else None
worksheets = packet.get("worksheets")
if not isinstance(rows, list) or not isinstance(worksheets, dict):
return packet
if "graha_drishti" not in worksheets:
worksheets["graha_drishti"] = {
"source": "modules.aspects.house_aspects",
"citation": "references/signs-and-houses.md",
"house_aspects": rows,
}
return packet
def build_full_data_packet(identity: dict[str, Any]) -> dict[str, Any]:
"""Packet-only build. No markdown render and no sanitized rewrite."""
from datetime import date
from calculation_profile_contract import attach_calculation_profile
from jyotish_engine import build_pl9_style_export_packet, cmd_full_reading
today = date.today()
ref = date.fromisoformat(str(identity["reference_date"]))
args = SimpleNamespace(
year=int(identity["year"]),
month=int(identity["month"]),
@@ -121,19 +169,41 @@ def build_full_data_packet(identity: dict[str, Any]) -> dict[str, Any]:
tz=float(identity["tz"]),
ayanamsa=identity["ayanamsa"],
node_mode=identity["node_mode"],
today=today.isoformat(),
target_year=today.year,
age=today.year - int(identity["year"]),
transit_date=today.isoformat(),
today=ref.isoformat(),
target_year=ref.year,
age=ref.year - int(identity["year"]),
transit_date=ref.isoformat(),
birth_time_accuracy="confirmed",
)
reading = cmd_full_reading(args)
if not isinstance(reading, dict) or reading.get("error"):
raise RuntimeError("full_reading_unavailable")
packet = build_pl9_style_export_packet(reading)
if not isinstance(packet, dict):
raise RuntimeError("full_reading_unavailable")
_attach_graha_drishti(packet, reading)
return attach_calculation_profile(packet, args)
def warm_consult_packet(body: dict[str, Any] | None) -> dict[str, Any]:
"""Build today's packet after a chart save. The response stays small."""
try:
cached = get_or_build(identity_from_body(dict(body or {})))
except Exception as exc:
return {
"success": False,
"endpoint": "consult_card_warm",
"error_type": type(exc).__name__,
}
return {
"success": True,
"endpoint": "consult_card_warm",
"hit": bool(cached["hit"]),
"elapsed_s": cached["elapsed_s"],
"slow": bool(cached["slow"]),
}
def _requested_domains(body: dict[str, Any]) -> list[str]:
# Card domains (parents, children) are not the engine theme (family).
raw = body.get("consult_card_domains")