Files
Jyotisha/tests/test_annual_motion_cache_2315.py
2026-11-24 15:44:33 +08:00

157 lines
8.4 KiB
Python

"""BUG-2315: the report's per-year continuous motion is cached, bounded and never copied across years."""
import json
import os
import stat
import time
import pytest
from scripts.report_render import annual_motion
from scripts.transit_search import build_tajika_motion_timeline
def _request(year):
return {'reference_date': f'{year}-02-01T00:00:00', 'end_exclusive': f'{year + 1}-02-01T00:00:00',
'days': 366, 'tz': 0, 'ayanamsa': 'lahiri', 'position_mode': 'apparent'}
def _pack(year, request=True, status='ready'):
motion = {'request_status': {'status': status, **({'reason': 'next_solar_return_epoch_unavailable'} if status == 'blocked' else {})}}
if request:
motion['request'] = _request(year)
return {'profile': {'target_year': year, 'input_hash': 'h', 'profile_hash': 'p'},
'solar_return': {'data': {'annual_location': {'utc_offset': 0}}, 'tajika_motion': motion}}
def _packet(packs):
return {'worksheets': {'timing_and_predictive_systems': {
'annual_tajika_pack': packs[0], 'annual_tajika_series': {'years': {str(p['profile']['target_year']): p for p in packs}}}}}
class Scan:
def __init__(self):
self.calls = []
def __call__(self, request):
self.calls.append(request['reference_date'])
return {'execution_status': 'executed', 'initial_positions': {},
'range': {'start': request['reference_date'], 'end_exclusive': request['end_exclusive']},
'profile': {'ayanamsa': request['ayanamsa']}, 'claim_boundary': annual_motion.CLAIM_BOUNDARY,
'events': [{'kind': 'station', 'planets': ['Mars'], 'timestamp_local': request['reference_date']}]}
@pytest.fixture(autouse=True)
def _isolated(monkeypatch, tmp_path):
monkeypatch.setenv('JYOTISH_ANNUAL_MOTION_CACHE_DIR', str(tmp_path / 'motion'))
monkeypatch.delenv('JYOTISH_ANNUAL_MOTION_BUDGET_SECONDS', raising=False)
def test_each_year_is_scanned_once_then_read_from_the_private_cache(tmp_path):
scan = Scan()
first = annual_motion.attach_annual_motion(_packet([_pack(2026), _pack(2027), _pack(2028)]), scan=scan)
assert scan.calls == ['2026-02-01T00:00:00', '2027-02-01T00:00:00', '2028-02-01T00:00:00']
assert {row['cache'] for row in first['years'].values()} == {'miss'}
files = sorted((tmp_path / 'motion').glob('*.json'))
assert len(files) == 3
assert all(stat.S_IMODE(os.stat(path).st_mode) == 0o600 for path in files)
assert all(len(path.stem) == 64 for path in files)
second = annual_motion.attach_annual_motion(_packet([_pack(2026), _pack(2027), _pack(2028)]), scan=scan)
assert len(scan.calls) == 3
assert {row['cache'] for row in second['years'].values()} == {'hit'}
def test_key_covers_request_birth_hash_place_and_rule_version():
base = annual_motion.cache_key(_request(2026), {'input_hash': 'h', 'target_year': 2026})
assert base != annual_motion.cache_key(_request(2027), {'input_hash': 'h', 'target_year': 2026})
assert base != annual_motion.cache_key(_request(2026), {'input_hash': 'other', 'target_year': 2026})
assert base != annual_motion.cache_key(dict(_request(2026), ayanamsa='raman'), {'input_hash': 'h', 'target_year': 2026})
assert base != annual_motion.cache_key(dict(_request(2026), position_mode='mean'), {'input_hash': 'h', 'target_year': 2026})
assert annual_motion.rule_version().startswith(annual_motion.WIRING_VERSION)
def test_at_most_three_years_and_the_budget_blocks_a_year_cleanly(monkeypatch):
monkeypatch.setenv('JYOTISH_ANNUAL_MOTION_BUDGET_SECONDS', '10')
ticks = iter(range(0, 1000, 6)) # every clock read advances six seconds
scan = Scan()
packet = _packet([_pack(2026), _pack(2027), _pack(2028), _pack(2029)])
run = annual_motion.attach_annual_motion(packet, scan=scan, clock=lambda: next(ticks))
years = packet['worksheets']['timing_and_predictive_systems']['annual_tajika_series']['years']
assert '2029' not in run['years'] and 'tajika_condition_status_pack' not in years['2029']
blocked = [y for y in ('2026', '2027', '2028')
if years[y]['tajika_condition_status_pack']['motion_timeline']['execution_status'] == 'blocked']
assert blocked, run
for year in blocked:
motion = years[year]['tajika_condition_status_pack']['motion_timeline']
assert motion['reason'] == 'time_budget_exceeded'
assert 'events' not in motion
# Nothing was cached for a skipped year: a later report computes it.
monkeypatch.setenv('JYOTISH_ANNUAL_MOTION_BUDGET_SECONDS', '1000')
again = annual_motion.attach_annual_motion(_packet([_pack(2026), _pack(2027), _pack(2028)]), scan=scan)
assert all(again['years'][y]['cache'] == 'miss' for y in blocked)
def test_blocked_or_missing_request_is_recorded_not_invented():
scan = Scan()
packet = _packet([_pack(2026, request=False, status='blocked'), _pack(2027, request=False, status='ready')])
annual_motion.attach_annual_motion(packet, scan=scan)
years = packet['worksheets']['timing_and_predictive_systems']['annual_tajika_series']['years']
assert scan.calls == []
assert years['2026']['tajika_condition_status_pack']['motion_timeline'] == {
'execution_status': 'blocked', 'reason': 'next_solar_return_epoch_unavailable',
'claim_boundary': 'Annual motion request unavailable; static structure is retained.'}
assert years['2027']['tajika_condition_status_pack']['motion_timeline']['execution_status'] == 'not_requested'
def test_storage_is_lossless_against_the_upstream_shape():
upstream = build_tajika_motion_timeline('2026-11-01', 20, 8, 'Raman')
stored = annual_motion.compact_timeline(upstream)
assert all('prior_motion_changes' not in event for event in stored['events'])
assert len(json.dumps(stored)) < len(json.dumps(upstream))
assert annual_motion.expand_prior_motion_changes(stored) == upstream
def test_chat_annual_field_does_not_run_the_scan_and_the_year_carries_its_request():
from scripts.annual_tajika_pack import (_attach_motion_inputs, _field_from_report, _tajika_yogas_field,
_without_motion_inputs)
import solar_return
report = solar_return.solar_return_full_report(1990, 1, 1, 12, 0, 20., 75., 5.5, 2026, ayanamsa_name='lahiri')
assert _tajika_yogas_field(_without_motion_inputs(report)) == _field_from_report(report, 'tajika_yogas', 'Tajika Yogas')
field = _field_from_report(report, 'solar_return', 'Solar Return')
_attach_motion_inputs(field, report)
assert field['tajika_motion']['request'] == report['tajika_motion_request']
assert set(field['tajika_motion']['named_yoga_inputs']) == {'Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn'}
def test_retention_prunes_old_motion_files(monkeypatch, tmp_path):
from scripts import api_scratch_retention as retention
folder = tmp_path / 'motion'
folder.mkdir(parents=True, exist_ok=True)
old, young = folder / ('a' * 64 + '.json'), folder / ('b' * 64 + '.json')
for path in (old, young):
path.write_text('{}', encoding='utf-8')
now = time.time()
os.utime(old, (now - 8 * 86400, now - 8 * 86400))
stats = retention._prune_annual_motion(now)
assert stats['removed'] == 1 and not old.exists() and young.exists()
assert 'annual_motion_timeline' in retention.REGISTERED_DIR_NAMES
def test_shared_annual_pack_never_runs_the_scan(monkeypatch):
"""The chat card, the annual service and the audit rows all build this pack; only the report scans."""
import scripts.transit_search as transit_search
from scripts.annual_tajika_pack import build_annual_tajika_pack
def forbidden(*args, **kwargs):
raise AssertionError("the shared annual pack must not run the motion scan")
monkeypatch.setattr(transit_search, "build_tajika_motion_timeline", forbidden)
import transit_search as direct
monkeypatch.setattr(direct, "build_tajika_motion_timeline", forbidden)
pack = build_annual_tajika_pack({
"birth": {"date": "1990-01-01", "time": "12:00:00", "latitude": 20.0, "longitude": 75.0, "utc_offset": "+05:30"},
"settings": {"ayanamsa": "lahiri"}, "target_year": 2026})
motion = pack["solar_return"]["tajika_motion"]
assert motion["request_status"]["status"] == "ready" and motion["request"]["position_mode"] == "apparent"
assert "motion_timeline" not in (pack["tajika_yogas"].get("data") or {})
assert pack["tajika_named_yogas"]["data"]["motion_timeline"] == {"execution_status": "not_requested"}