Files
Jyotisha/tests/test_bug_2427_external_engine_switch_off.py
T
ClaudeandClaude 4b8a645357
Independent Staging Quality Gate / validate-python (push) Successful in 5m2s
Independent Staging Quality Gate / validate-frontend (push) Successful in 5m44s
Independent Staging Quality Gate / publish (push) Successful in 12m12s
fix(vedastro): one switch, off by default; an official chart replaces the local one only on a matching echo (BUG-2427, #327)
Owner decision 2026-11-26: the product stops using VedAstro.
- scripts/vedastro_switch: VEDASTRO_ENABLED=1 turns it on; default off.
- Adapter, gateway, foreground session, consult gate, orchestrator,
  user entrypoint, REST/MCP/SDK bridges answer "disabled" at once:
  no network, no subprocess, no wait, no cache writes.
- vedastro_priority: a disabled snapshot leaves the local chart as is;
  an official chart replaces it only when every chart/house answer
  echoes the requested time, place and ayanamsa.
- Model input drops VedAstro audit rows, cross-check and must-use layer;
  privacy policy drops the VedAstro data line.
- VEDASTRO_API_KEY optional and unused; env examples, deploy/README,
  AGENTS.md updated. Frozen files untouched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-26 23:33:41 +08:00

251 lines
11 KiB
Python

"""BUG-2427 (issue #327): VedAstro is off unless VEDASTRO_ENABLED is set.
Owner decision 2026-11-26. With the switch off nothing may reach the network or
start a bridge subprocess, nothing waits, and no negative-cache entry is written.
Independently of the switch, an official chart may replace the local chart only
when every answer echoes the requested birth time, place and ayanamsa.
(Named without "vedastro" so tests/conftest.py keeps the product default: off.)
"""
from __future__ import annotations
import json
import subprocess
import time
import urllib.request
from pathlib import Path
import pytest
from scripts import vedastro_switch
BIRTH = {"year": 1990, "month": 6, "day": 15, "hour": 10, "minute": 20, "second": 0,
"lat": 31.2, "lon": 121.5, "tz": 8}
@pytest.fixture
def no_outside_calls(monkeypatch):
"""Any network or VedAstro subprocess call fails the test."""
calls: list[str] = []
def refuse_urlopen(*args, **kwargs):
calls.append("urlopen")
raise AssertionError("VedAstro switch is off: no network call allowed")
real_run = subprocess.run
def guard_run(cmd, *args, **kwargs):
if "vedastro" in json.dumps(cmd, default=str).lower():
calls.append("subprocess")
raise AssertionError("VedAstro switch is off: no bridge subprocess allowed")
return real_run(cmd, *args, **kwargs)
monkeypatch.setattr(urllib.request, "urlopen", refuse_urlopen)
monkeypatch.setattr(subprocess, "run", guard_run)
import scripts.vedastro_service_adapter as adapter
monkeypatch.setattr(adapter.request, "urlopen", refuse_urlopen)
return calls
def _no_files(directory: str | None) -> bool:
if not directory:
return True
path = Path(directory)
return not path.exists() or not any(path.rglob("*.json"))
def test_the_switch_is_off_by_default_and_needs_no_key(monkeypatch):
monkeypatch.delenv("VEDASTRO_ENABLED", raising=False)
monkeypatch.delenv("VEDASTRO_API_KEY", raising=False)
assert vedastro_switch.vedastro_enabled() is False
for value in ("0", "false", "", "no"):
monkeypatch.setenv("VEDASTRO_ENABLED", value)
assert vedastro_switch.vedastro_enabled() is False
monkeypatch.setenv("VEDASTRO_ENABLED", "1")
assert vedastro_switch.vedastro_enabled() is True
def test_every_entry_point_answers_disabled_without_network_or_subprocess(no_outside_calls, monkeypatch):
# The old production env still carries these; they must not turn anything on.
monkeypatch.setenv("VEDASTRO_ENABLE_NETWORK", "1")
monkeypatch.setenv("VEDASTRO_API_ENDPOINT", "https://api.vedastro.org/api")
monkeypatch.setenv("VEDASTRO_API_KEY", "not-a-real-key")
import scripts.vedastro_service_adapter as adapter
from scripts.vedastro_evidence_orchestrator import orchestrate_vedastro_evidence
from scripts.vedastro_gateway import enqueue_gateway_job, gateway_status, probe_official_rest_health, run_gateway_packet
from scripts.vedastro_python_bridge import call_method
from scripts.vedastro_rest_bridge import call, probe_calculate_health
started = time.perf_counter()
results = [
adapter.run_official_full_snapshot_for_case(dict(BIRTH)),
adapter.run_range_scan_for_case(dict(BIRTH), "career", "2026-11-26", "2026-11-26"),
adapter.run_rectification_minute_snapshot_for_case(dict(BIRTH)),
orchestrate_vedastro_evidence(dict(BIRTH), route="career", reference_date="2026-11-26"),
run_gateway_packet(dict(BIRTH), question="事业", themes=["career"], reference_date="2026-11-26"),
enqueue_gateway_job(dict(BIRTH)),
gateway_status(),
probe_official_rest_health(force_refresh=True),
probe_calculate_health(),
call("HoroscopePredictions", {"time": {}}),
call_method("AllPlanetData", {}),
]
assert time.perf_counter() - started < 2.0, "a switched-off VedAstro must not wait on anything"
assert no_outside_calls == []
for result in results:
assert result["official_closure_reason"] == vedastro_switch.DISABLED_REASON, result
assert result["status"] in {"disabled"}, result
assert "not-a-real-key" not in json.dumps(results, ensure_ascii=False)
def test_the_low_level_transport_refuses_even_if_reached(no_outside_calls):
from urllib import error
import scripts.vedastro_service_adapter as adapter
with pytest.raises(error.URLError):
adapter._post_json("https://api.vedastro.org/api", {"operation": "official_full_snapshot"})
assert no_outside_calls == []
def test_foreground_session_never_runs_the_gateway_or_touches_the_caches(no_outside_calls, monkeypatch):
import os
from scripts import vedastro_foreground
from scripts.vedastro_consultation_snapshot import consult_rectification_vedastro_gateway
class Handler:
calls = 0
def _compute_vedastro_gateway_run(self, body):
Handler.calls += 1
raise AssertionError("gateway must not run while VedAstro is off")
for defer in (True, False):
body = {**BIRTH, "vedastro_evidence_budget": "report"} if defer else dict(BIRTH)
session = vedastro_foreground.start_foreground_vedastro(Handler(), body, defer_optional_external_evidence=defer)
assert session.future is None
result = vedastro_foreground.finish_foreground_vedastro(session)
assert result["official_closure_reason"] == vedastro_switch.DISABLED_REASON
gate = consult_rectification_vedastro_gateway(dict(BIRTH))
assert gate["official_closure_reason"] == vedastro_switch.DISABLED_REASON
assert Handler.calls == 0
assert _no_files(os.environ.get("JYOTISH_VEDASTRO_SNAPSHOT_NEGATIVE_CACHE_DIR"))
assert _no_files(os.environ.get("JYOTISH_VEDASTRO_SNAPSHOT_CACHE_DIR"))
def test_consultation_and_report_workflows_make_zero_vedastro_calls(no_outside_calls, monkeypatch):
monkeypatch.setenv("JYOTISH_API_CHART_CACHE_TTL_SECONDS", "0")
from scripts.jyotish_api_server import JyotishComputeService
import scripts.vedastro_gateway as gateway
def refuse(*args, **kwargs):
raise AssertionError("gateway packet must not be built while VedAstro is off")
monkeypatch.setattr(gateway, "_entrypoint_args", refuse)
service = JyotishComputeService()
for extra in ({"defer_optional_external_evidence": True}, {"vedastro_evidence_budget": "report"}):
body = {**BIRTH, "question": "我的事业怎么样", "theme": ["career"], "entry_mode": "direct_chart", **extra}
started = time.perf_counter()
result = service._compute_consultation_workflow(dict(body))
assert result["success"] is True
assert time.perf_counter() - started < 60
assert result["vedastro_gateway"]["status"] == "disabled"
assert result["consumer_context"]["user_facing_limitation"] is None
chart = result["chart"]
assert chart.get("source") != "vedastro_official_primary"
assert no_outside_calls == []
def test_health_diagnostics_report_disabled_not_broken(no_outside_calls):
from scripts.diagnose_external_engine_adapters import build_report as build_adapters
from scripts.diagnose_vedastro_mode import build_report
report = build_report()
assert report["enabled"] is False
assert report["mode"] == "disabled"
assert "premium_key_missing" not in report["readiness_blockers"]
try:
adapters = build_adapters()
except Exception: # other engines may be absent locally; only the VedAstro row matters here
return
engines = adapters.get("engines") if isinstance(adapters, dict) else None
if isinstance(engines, dict) and "VedAstro" in engines:
assert engines["VedAstro"]["status"] == "disabled"
# ---- the official chart never replaces the local one without a matching echo ----
LOCAL_BIRTH_INFO = {"date": "1990-06-15", "hour": 10, "minute": 20, "lat": 31.2, "lon": 121.5,
"tz": "UTC+8", "ayanamsa_name": "lahiri"}
def _answer(std_time="10:20 15/06/1990 +08:00", lat=31.2, lon=121.5, ayanamsa=1, status="Pass"):
return {"Status": status, "Input": {"time": {"StdTime": std_time, "Location": {"Latitude": lat, "Longitude": lon}},
"Ayanamsa": ayanamsa}}
def _report_and_snapshot(answer, birth_info=LOCAL_BIRTH_INFO):
local = {"source": "local_engine", "planets": {"Sun": {"sign": "Gemini"}}, "ascendant": {"sign": "Leo"},
"houses": {"House1": {"sign": "Leo"}}, "birth_info": dict(birth_info) if birth_info else {}}
report = {"chart": local, "modules": {"chart": local}}
snapshot = {
"status": "ok",
"available": True,
"snapshot_sections": {"chart_core": {"Sun": answer}, "house_core": {"House1": answer}},
"official_chart": {"planets": {"Sun": {"sign": "Libra"}}, "ascendant": {"sign": "Aquarius"},
"houses": {"House1": {"sign": "Aquarius"}}},
}
return report, snapshot
@pytest.mark.parametrize("answer, reason", [
# The API's own sample chart (1992 Mumbai, Raman) answered with "Pass".
(_answer("14:30 25/10/1992 +05:30", 18.97, 72.82, 3), "echo_time_or_place_differs"),
(_answer(ayanamsa=3), "echo_ayanamsa_differs"),
(_answer(lat=19.0), "echo_time_or_place_differs"),
(_answer("10:20 15/06/1990 +05:30"), "echo_time_or_place_differs"),
({"Status": "Pass"}, "echo_input_missing"),
(_answer(status="Fail"), "chart_core_not_pass"),
])
def test_a_mismatched_echo_never_replaces_the_local_chart(answer, reason):
from scripts.vedastro_priority import apply_vedastro_source_priority
report, snapshot = _report_and_snapshot(answer)
apply_vedastro_source_priority(report, official_snapshot=snapshot)
assert report["chart"]["planets"]["Sun"]["sign"] == "Gemini"
assert report["chart"]["ascendant"]["sign"] == "Leo"
assert report["modules"]["source_priority"]["mode"] != "vedastro_official_primary"
assert report["modules"]["vedastro_official_echo_check"] == {"status": "mismatch", "reason": reason}
def test_without_a_requested_birth_the_official_chart_is_not_used():
from scripts.vedastro_priority import apply_vedastro_source_priority
report, snapshot = _report_and_snapshot(_answer(), birth_info=None)
apply_vedastro_source_priority(report, official_snapshot=snapshot)
assert report["chart"]["planets"]["Sun"]["sign"] == "Gemini"
assert report["modules"]["vedastro_official_echo_check"]["reason"] == "requested_birth_missing"
def test_a_matching_echo_may_replace_the_local_chart():
from scripts.vedastro_priority import apply_vedastro_source_priority
report, snapshot = _report_and_snapshot(_answer())
apply_vedastro_source_priority(report, official_snapshot=snapshot)
assert report["chart"]["planets"]["Sun"]["sign"] == "Libra"
assert report["modules"]["source_priority"]["mode"] == "vedastro_official_primary"
assert report["modules"]["vedastro_official_echo_check"]["status"] == "matched"
def test_a_disabled_snapshot_leaves_the_local_chart_untouched():
from scripts.vedastro_priority import apply_vedastro_source_priority
report, _ = _report_and_snapshot(_answer())
before = json.dumps(report["chart"], sort_keys=True)
apply_vedastro_source_priority(report, official_snapshot=vedastro_switch.disabled_packet("vedastro_service_adapter"))
assert json.dumps(report["chart"], sort_keys=True) == before
assert "fallback_reason" not in report["chart"]
assert report["modules"]["source_priority"]["mode"] == "local_engine_vedastro_disabled"