Files
ClaudeandClaude Opus 5.5 04f9e20f92 feat(annual): saving a chart pre-computes the three report years' continuous motion in a low-priority background worker, so the first report no longer waits for it (BUG-2321)
One daemon thread, bounded queue (drop oldest), coalesced per chart, pauses
whenever the heavy-compute gate or a consult warm is busy, and scans each year
in 15-day sub-ranges merged exactly into the whole-year result. Same cache keys
as the report (verified: a report after prewarm scans nothing).
JYOTISH_ANNUAL_MOTION_PREWARM=0 turns it off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXp2U3BH1SxwAGyhhbe1
2026-11-24 17:14:37 +08:00

292 lines
14 KiB
Python

"""BUG-2321: after a chart save, pre-compute the three report years' continuous motion in the background.
The first report for a chart used to spend about 17 s on the motion scans (BUG-2315). A chart save already
asks the engine to warm the consult packet (``consult_full_data_cache.warm_consult_packet``); that call now
also hands the chart to this module, which fills exactly the cache entries the report will look up.
Same keys as the report: the report's own argument builder (``professional_report_reference._export_args``)
with the birth fields the report sends and "today"'s year as the target year, the frozen engine's own
``_copy_call_namespace`` / ``_annual_payload_from_args`` for each of the three years, the shared
``build_annual_tajika_pack`` for the year's profile and request, the engine's ``_annual_series_surface``
snapshot and delivery sanitizer the report reads through, and ``annual_motion.cache_key`` /
``annual_motion._context`` for the key. The scan result goes through ``annual_motion.cached_timeline``,
so the file is the one the report reads.
Production (2 vCPU, one API process, threads share the GIL):
* one daemon worker thread, started on first use, at the lowest OS priority it can set (nice 19 for the
thread on Linux); a deploy restart drops the queue, only finished cache files remain;
* a bounded queue (``MAX_PENDING``; the oldest pending chart is dropped first), coalesced per chart: a chart
already queued, running, or finished in this process is not queued again;
* never on the save request path: ``submit`` only puts the chart on the queue;
* the worker does nothing while the API is busy: any heavy-compute permit held or waited for
(``api_heavy_compute_gate``: reports, consultations, rectification scans …) or a consult-packet warm in
flight. It checks before every step and waits while busy;
* steps are small: each year's scan runs as ``CHUNK_DAYS``-day sub-ranges merged into exactly the whole-year
result (see ``chunked_scan``). A request that arrives mid-step shares the GIL with the worker for at
most one step (one sub-range, about 0.2 s of CPU at 15 days, or one year's pack build), then the worker
pauses until the API is idle again. CPython cannot preempt a running step, so this is the bound.
* ``JYOTISH_ANNUAL_MOTION_PREWARM=0`` switches it off (default on).
"""
from __future__ import annotations
import logging
import os
import threading
import time
from collections import OrderedDict
from datetime import datetime, timedelta
from typing import Any, Callable
_LOG = logging.getLogger("jyotish.annual_motion_prewarm")
ENV_SWITCH = "JYOTISH_ANNUAL_MOTION_PREWARM"
MAX_PENDING = 8
DONE_MEMORY = 256
CHUNK_DAYS = 15
IDLE_POLL_SECONDS = 1.0
# A chart whose step waits longer than this for an idle API is given up; the report computes it.
MAX_IDLE_WAIT_SECONDS = 15 * 60
BIRTH_KEYS = ("year", "month", "day", "hour", "minute", "second", "lat", "lon", "tz", "ayanamsa")
def enabled() -> bool:
return os.environ.get(ENV_SWITCH, "1").strip().lower() not in {"0", "false", "no", "off"}
class GaveUp(RuntimeError):
"""The API stayed busy past MAX_IDLE_WAIT_SECONDS."""
def api_busy() -> bool:
"""True while the API runs heavy work: a heavy-compute permit held or awaited, or a consult warm."""
try:
from scripts.api_heavy_compute_gate import heavy_compute_status, heavy_compute_waiter_count
from scripts import consult_full_data_cache as consult
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from api_heavy_compute_gate import heavy_compute_status, heavy_compute_waiter_count
import consult_full_data_cache as consult
if heavy_compute_status().get("in_use", 0) > 0 or heavy_compute_waiter_count() > 0:
return True
return getattr(consult, "_warm_inflight", 0) > 0
def report_birth(body: dict[str, Any]) -> dict[str, Any]:
"""The birth fields the report request carries, with today's year as the target year (as the report)."""
try:
from scripts.consult_full_data_cache import reference_date_from_body
except ModuleNotFoundError: # pragma: no cover
from consult_full_data_cache import reference_date_from_body
today = reference_date_from_body(body)
birth = {key: body[key] for key in BIRTH_KEYS if body.get(key) is not None}
for key in ("year", "month", "day", "lat", "lon", "tz"):
if key not in birth:
raise KeyError(key)
birth["ayanamsa"] = birth.get("ayanamsa") or "lahiri"
birth.update(today=today, target_year=int(today[:4]), age=int(today[:4]) - int(birth["year"]))
return birth
def year_requests(birth: dict[str, Any]) -> list[tuple[int, dict | None, dict, dict]]:
"""[(year, request or None, context, request_status)] for the three report years, built by the report's code."""
try:
from scripts import jyotish_engine as engine
from scripts.annual_tajika_pack import build_annual_tajika_pack
from scripts.calculation_profile_contract import attach_calculation_profile
from scripts.professional_report_reference import _export_args
from scripts.report_render.annual_motion import MAX_YEARS, _context
except ModuleNotFoundError: # pragma: no cover
import jyotish_engine as engine
from annual_tajika_pack import build_annual_tajika_pack
from calculation_profile_contract import attach_calculation_profile
from professional_report_reference import _export_args
from report_render.annual_motion import MAX_YEARS, _context
args = _export_args(birth)
profile = attach_calculation_profile({}, args)["calculation_profile"]
out = []
for offset in range(MAX_YEARS):
year_args = engine._copy_call_namespace(args)
year_args.target_year = int(args.target_year) + offset
year_args.age = year_args.target_year - int(args.year)
# The report reads each year from the frozen engine's series surface after the packet's delivery
# sanitizer (which, for example, leaves out None values); build the key from that same shape.
pack = engine.sanitize_professional_report_reference(engine._annual_series_surface(
build_annual_tajika_pack(engine._annual_payload_from_args(year_args, profile))))
motion = (pack.get("solar_return") or {}).get("tajika_motion") or {}
out.append((year_args.target_year, motion.get("request"), _context(pack), motion.get("request_status") or {}))
return out
def chunked_scan(request: dict, *, between: Callable[[], None] = lambda: None,
chunk_days: int = CHUNK_DAYS) -> dict:
"""Her whole-window ``build_tajika_motion_timeline``, as ``chunk_days``-day sub-ranges merged exactly.
Her scan samples every six hours from its start and searches roots per sample interval. Sub-ranges start
on that same grid (whole days from the year's start), so every sub-range has the same sample points and
root brackets as the whole-year scan; each root falls in exactly one half-open sub-range. Events are
merged in her sort order, and each exact contact's ``prior_motion_changes`` is rebuilt over the merged
list by her rule. A test checks the merge against a single whole-window scan.
"""
try:
from scripts.transit_search import build_tajika_motion_timeline
from scripts.report_render.annual_motion import _prior_changes
except ModuleNotFoundError: # pragma: no cover
from transit_search import build_tajika_motion_timeline
from report_render.annual_motion import _prior_changes
start = datetime.fromisoformat(request["reference_date"])
end = (datetime.fromisoformat(request["end_exclusive"]) if request.get("end_exclusive")
else start + timedelta(days=int(request["days"])))
options = {key: request[key] for key in ("position_mode",) if key in request}
parts = []
cursor = start
while cursor < end:
between()
stop = min(cursor + timedelta(days=chunk_days), end)
days = max(1, -(-int((stop - cursor).total_seconds()) // 86400))
parts.append(build_tajika_motion_timeline(cursor.isoformat(), days, request["tz"], request["ayanamsa"],
end_exclusive=stop.isoformat(), **options))
cursor = stop
first = parts[0]
events = [{key: value for key, value in event.items() if key != "prior_motion_changes"}
for part in parts for event in part["events"]]
events.sort(key=lambda row: (row["timestamp_local"], row["kind"], row["planets"]))
for position, event in enumerate(events):
if event["kind"] == "exact_contact":
event["prior_motion_changes"] = _prior_changes(events, position)
return {**first, "events": events, "range": {"start": start.isoformat(), "end_exclusive": end.isoformat()}}
class Prewarmer:
def __init__(self, *, busy: Callable[[], bool] = api_busy, requests: Callable[[dict], list] = year_requests,
sleep: Callable[[float], None] = time.sleep, clock: Callable[[], float] = time.monotonic,
max_pending: int = MAX_PENDING, chunk_days: int = CHUNK_DAYS, start_thread: bool = True):
self._busy, self._requests, self._sleep, self._clock = busy, requests, sleep, clock
self.max_pending, self.chunk_days, self._start_thread = max_pending, chunk_days, start_thread
self._pending: "OrderedDict[str, dict]" = OrderedDict()
self._done: "OrderedDict[str, None]" = OrderedDict()
self._running: str | None = None
self._cond = threading.Condition()
self._thread: threading.Thread | None = None
self.stats = {"queued": 0, "coalesced": 0, "dropped": 0, "scanned_years": 0, "cached_years": 0, "gave_up": 0, "failed": 0}
@staticmethod
def chart_key(birth: dict) -> str:
return "|".join(str(birth.get(key)) for key in (*BIRTH_KEYS, "target_year"))
def submit(self, body: dict[str, Any]) -> str:
"""Queue one chart. Returns quickly; never computes on the caller's thread."""
if not enabled():
return "disabled"
try:
birth = report_birth(dict(body or {}))
except (KeyError, TypeError, ValueError):
return "invalid"
key = self.chart_key(birth)
with self._cond:
if key in self._pending or key == self._running or key in self._done:
self.stats["coalesced"] += 1
return "coalesced"
while len(self._pending) >= self.max_pending:
self._pending.popitem(last=False)
self.stats["dropped"] += 1
self._pending[key] = birth
self.stats["queued"] += 1
self._cond.notify()
if self._start_thread:
self._ensure_thread()
return "queued"
def pending_keys(self) -> list[str]:
with self._cond:
return list(self._pending)
def _ensure_thread(self) -> None:
with self._cond:
if self._thread is not None and self._thread.is_alive():
return
self._thread = threading.Thread(target=self._loop, name="annual-motion-prewarm", daemon=True)
self._thread.start()
def _loop(self) -> None:
try: # lowest priority for this thread only (Linux per-thread nice); best effort
os.setpriority(os.PRIO_PROCESS, threading.get_native_id(), 19)
except (AttributeError, OSError):
_LOG.debug("annual motion prewarm: thread priority unchanged")
while True:
with self._cond:
while not self._pending:
self._cond.wait()
self.run_once()
def wait_idle(self) -> None:
waited_from = self._clock()
while self._busy():
if self._clock() - waited_from > MAX_IDLE_WAIT_SECONDS:
raise GaveUp("api_busy")
self._sleep(IDLE_POLL_SECONDS)
self._sleep(0) # hand the GIL over once between steps
def run_once(self) -> bool:
"""Process the oldest pending chart. False when nothing was pending."""
with self._cond:
if not self._pending:
return False
key, birth = self._pending.popitem(last=False)
self._running = key
try:
self._prewarm(birth)
with self._cond:
self._done[key] = None
while len(self._done) > DONE_MEMORY:
self._done.popitem(last=False)
except GaveUp:
self.stats["gave_up"] += 1
except Exception: # noqa: BLE001 - background best effort; the report computes what is missing
self.stats["failed"] += 1
_LOG.warning("annual motion prewarm failed", exc_info=True)
finally:
with self._cond:
self._running = None
return True
def _prewarm(self, birth: dict) -> None:
try:
from scripts.report_render.annual_motion import cache_dir, cache_key, cached_timeline
except ModuleNotFoundError: # pragma: no cover
from report_render.annual_motion import cache_dir, cache_key, cached_timeline
self.wait_idle()
for _year, request, context, _status in self._requests(birth):
if not isinstance(request, dict):
continue
if (cache_dir() / f"{cache_key(request, context)}.json").is_file():
self.stats["cached_years"] += 1
continue
self.wait_idle()
_timeline, info = cached_timeline(
request, context, scan=lambda req: chunked_scan(req, between=self.wait_idle, chunk_days=self.chunk_days))
if info.get("cache") == "miss":
self.stats["scanned_years"] += 1
_shared: Prewarmer | None = None
_shared_guard = threading.Lock()
def shared() -> Prewarmer:
global _shared
with _shared_guard:
if _shared is None:
_shared = Prewarmer()
return _shared
def schedule_prewarm(body: dict[str, Any] | None) -> str:
"""Called after a consult warm (chart save). Never raises."""
try:
return shared().submit(dict(body or {}))
except Exception: # noqa: BLE001 - the save's warm must never fail because of this
_LOG.warning("annual motion prewarm not scheduled", exc_info=True)
return "error"
__all__ = ["Prewarmer", "api_busy", "chunked_scan", "enabled", "report_birth", "schedule_prewarm", "year_requests"]