diff --git a/BLOCKED.md b/BLOCKED.md index 9971eba23..2430a2095 100644 --- a/BLOCKED.md +++ b/BLOCKED.md @@ -1,5 +1,9 @@ # BLOCKED +## #327 VedAstro 生产复核 + +- 本次生产发布后,需轮换供应商密钥,授权受控的公开盘调用,并提供只读历史证据以核查报告、问答和生时纠正是否采用过官方盘。现有替代证据包括公开仓库的真实回包、固定版 SDK 的离线请求核对和故障回退测试。见 [#327 进度](docs/tasks/PROGRESS-vedastro-request-verification-20261122.md)。 + ## #323 生时纠正停用预检 - Windows 碎片扫描和定向预检超时。远端可见性、外部适配器诊断与本机合成 HTTP 回归提供核对证据。见 [#323 进度](docs/tasks/PROGRESS-rect-cut-shadbala-scoring-20261117.md)。 diff --git a/CHANGELOG.md b/CHANGELOG.md index 12a17a9b8..3cc6d13bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # 印度占星 Skill 更新日志 +## 2026-11-22 · VedAstro 按请求回显核对外部结果 + +- 外部计算需要服务端凭据,且回显的时间、地点和岁差须与请求一致。凭据缺失或回显不符时继续用本地引擎。Skill 版本沿用(BUG-2171)。 + ## 2026-11-18 · 问答卡补充土星、木星同本命星座事实 - 年运、应期和综合卡标出同名星是否同座,日期只用已有换座记录,缺失照实标注。Skill 版本沿用(BUG-1995)。 diff --git a/docs/BUG_HISTORY.md b/docs/BUG_HISTORY.md index d8739da7a..aee03d844 100644 --- a/docs/BUG_HISTORY.md +++ b/docs/BUG_HISTORY.md @@ -29338,3 +29338,19 @@ - 防复发:上面的测试;格局说明里的「已满足落陷取消条件」(`main_yoga_detectors.NEECHA_BHANGA_NOTE_ZH`、`opening_guide.py:367`)未改,已作为问题 L 交占星师。 - 关联记录:BUG-2163、BUG-2165、BUG-2155、BUG-2030、BUG-2039、BUG-1987。 - 修复版本:`claude/neecha-card-2169`。 + +## BUG-2171 | VedAstro 凭据、请求格式与输入回显未闭环 + +- 状态:blocked(分支修复已离线验证,生产待复核)。 +- 首次发现:2026-11-22。 +- 最近更新:2026-11-22。 +- 影响面:VedAstro REST 健康探测和 CLI、Python SDK、官方快照与 SearchEvents。涉及报告、问答和生时纠正的外部取证。 +- 用户现象:官方印证长期不可用。供应商可对默认示例输入返回 Pass,旧成功判断存在让示例结果替换用户本地盘的风险。历史生产覆盖待查。 +- 触发条件:无供应商凭据、请求字段与现行接口不符,或返回的计算器、时间、地点、岁差、行星或宫位与请求不同。 +- 根因:REST 和 SDK 桥未传凭据,直接适配器沿用旧请求字段及对象形状。SDK 会在交付给调用方前丢弃 Input。缓存、探测和盘面来源选择只依据 Pass 或结果形状。 +- 修复:各正式路径从服务器环境取凭据,对齐固定 SDK 与官方 REST 字段,在拆封和缓存之前比较 Input。错误回包标 input_echo_mismatch 并从结果中剔除。旧缓存换版本。行星与宫位的回显全部通过后方可提升官方盘,秒精度和真交点请求保留本地盘。 +- 验证:真实历史回包和离线 HTTP 回归覆盖鉴权、示例盘拒收、没有成功缓存及本地降级。用固定版 SDK 离线核对六种方法的实际请求。受控生产 smoke 与自七月起的历史取证审计仍待执行。 +- 防复发:Python 快速门运行 test_vedastro_request_verification_2171.py;发布后只记录各端点回显验收状态和聚合审计数字。 +- 相关记录:Gitea #327、BUG-719、BUG-720、BUG-1504、ERR-107、ERR-108。 +- 复发自:无。 +- 修复版本:codex/vedastro-request-verification-20261122,待独立验收。 diff --git a/docs/research/pre_work_error_ledger.md b/docs/research/pre_work_error_ledger.md index 981bc7003..98efce1ba 100644 --- a/docs/research/pre_work_error_ledger.md +++ b/docs/research/pre_work_error_ledger.md @@ -719,3 +719,9 @@ Prevention: 开工作树前先看 `df -i /`;工作树用完、内容已推送 - 约 14:53(本机时间)所有工作树同时丢了被 git 跟踪的 `.gitea/actions/upload-artifact/dist/index.js`、`vendor/stem-branch/dist/cli.cjs`,共用依赖 `/workspace/wt-up-int/frontend/node_modules` 整个消失;没有窗口承认手动删除,像是会话重启时的清理按 `dist` / `node_modules` 目录批量删。 - 处理:负责人在会话里重跑 `npm ci`(58 秒,1000 个包;esbuild / unrs-resolver 的 postinstall 未批准但 tsx 可用);两个跟踪文件各自在要推的工作树里 `git checkout --` 恢复,不进提交。 - 再出现时:先 `ls /workspace/wt-up-int/frontend/node_modules` 和 `git status`,缺了就请负责人重装,不自行 `npm ci`;七政引擎测试缺 `vendor/stem-branch/dist/cli.cjs` 时同样先恢复文件。 + + +## 2026-11-22 · #327 Windows 预检与 VedAstro 回显边界 + +- 独立 worktree 的 Python、适配器诊断、Gitea 远端可见性通过。碎片扫描与定向预检用完各自的 90 秒、45 秒预算。未把碎片目录当主仓。 +- SDK 1.23.25 在计算调用返回前只取 Payload。正式使用时须在 HTTP 边界先验证 Input,再交给解析器和缓存。历史捕获只能提供请求合同的测试样本,不能证明线上服务已经验收。关联 ERR-107、BUG-2171。 diff --git a/docs/tasks/PROGRESS-vedastro-request-verification-20261122.md b/docs/tasks/PROGRESS-vedastro-request-verification-20261122.md new file mode 100644 index 000000000..ff62cead8 --- /dev/null +++ b/docs/tasks/PROGRESS-vedastro-request-verification-20261122.md @@ -0,0 +1,27 @@ +# #327 VedAstro 请求与回显验证 + +- 工单 [#327](https://git.copse.top/root/Jyotisha/issues/327) 指定 BUG-2171。基线是远端 staging 的 `1b2af85ba`。本轮按 2026-11-22 的执行请求在 `codex/vedastro-request-verification-20261122` 完成离线修复,发布候选冻结期间由独立分支承载。 +- REST 桥和适配器从运行环境读取凭据并通过请求头发送。固定版 Python SDK 走自身参数序列化,并使用 `Calculate.SetAPIKey` 和 SDK 所用的 `APIKey` 参数。每次 SDK 调用独立绑定凭据和岁差。缺少凭据的正式调用直接降级。 +- 线上协议按[官方 REST 文档](https://vedastro.github.io/guide/index.html)和 [SDK 1.23.25](https://pypi.org/project/VedAstro/1.23.25/)核对。REST 请求使用字符串行星和宫位名、单时点 `SearchEvents` 的小写开头字段以及规范化岁差。区间扫描沿用逐日期采样。生时的交点选择和秒精度超出已核对的供应商盘面请求口径时保留本地盘。 +- 从仓库 2026-07-23 捕获核对 `Input.CalculatorName`、`Input.Ayanamsa` 与 `Input.Parameters` 结构。适配器、REST 桥和 SDK 在提取业务数据前核对回包的计算器、各个时间参数及其经纬度、岁差和星体或宫位身份。`Pass` 回显缺失或不符返回 `input_echo_mismatch`。错误不进入成功缓存或官方盘。官方宫位和行星节各自完整通过后才能替换本地盘。提升请求、快照和排盘缓存版本隔离旧结果。 + +## 离线验收 + +- 定向测试覆盖 REST 请求、SDK 鉴权与不同岁差、真实历史回包、示例盘、缓存、限流、网络截断和源优先级。 +- 固定版 SDK 使用 PyPI 发布 wheel,禁用其自动更新,替换 HTTP 为离线响应。在该 SDK 上核对 `AllPlanetData`、`AllHouseData`、`AllPlanetStrength`、`AshtakvargaLifeMap`、`DasaAtTime` 和 `SearchEvents`。 +- 定向测试在 Windows 通过 162 项。唯一失败要求文件权限为 POSIX `0600`,远端 staging 基线同项同因失败。Linux 容器中复跑网关、鉴权回显和运行诊断,30 项通过。隐私与 API 增长合同共 71 项通过。 +- 开工预检的 Python、外部适配器和远端可见性通过。Windows 碎片扫描 90 秒、定向预检 45 秒超时,与历史同类预检缺口一致。 + +| 原值 | 新值 | 原因 | +| --- | --- | --- | +| REST 与 SearchEvents 测试使用大写开头字段、适配器在预览阶段描述多日 SearchEvents 请求 | 断言 SDK 字段拼写和实际发送的单时点请求;逐日采样日期仍逐个核对 | SDK 1.23.25 对应的是单时点签名 | +| 仅凭 `Pass` 的假响应可通过健康探测;旧 Python 快照的成功样例省略 `Status` | HTTP 桩提供按真实结构构造的回显;SDK 汇总样例按真实封装带 `Status: Pass` | 回显是成功的必要条件 | +| 无凭据时允许进入限流等待;超时与本地 HTTP 测试未统一配置测试凭据 | 无凭据测试断言传输、缓存和限流均未触发;传输故障测试显式配置虚构凭据 | 让网络故障测试继续覆盖传输阶段 | +| 未配置供应商凭据也显示官方已就绪 | 缺少凭据时报告本地降级,测试仍验证网关的状态和限制 | 对齐正式请求的鉴权前置条件 | +| 排盘缓存版本为 9;超时用例替换全局 `time.monotonic` | 缓存版本为 10;仅替换被测适配器的时钟 | 隔离旧盘与测试运行器的时钟 | + +## 发布后验收 + +1. 在供应商控制台撤销原凭据,经部署运行手册指定的密钥管理入口更新生产容器环境。核对新发布 SHA、健康状态和凭据是否存在。只记录布尔、状态或请求数量。 +2. 取得真实调用授权后,使用一张公开示例盘。分别执行 REST 健康探测、`AllPlanetData`(日)、`AllHouseData`(一宫)、`SearchEvents`(单日)、`DasaAtRange`,再经 SDK 桥调用 `AllPlanetStrength`、`AshtakvargaLifeMap` 和 `DasaAtTime`。每个端点只调用一次,不启用全量快照、重试或原始响应日志。核对回显通过状态后,再从正常应用入口确认报告、问答和生时纠正的外部取证与本地降级。 +3. 历史核查从 2026-07-01 开始按产品路径统计。排盘或报告检查 `vedastro_official_primary` 与来源快照,问答检查持久化的外部证据,生时纠正检查候选分钟快照及外部验证回执。历史仓库捕获只能证明回包结构。计数从受控只读环境输出,说明日志及短期缓存的覆盖范围。缺失时段记录为未核实。 diff --git a/docs/tasks/README.md b/docs/tasks/README.md index ee11d6b5f..4bb1276b0 100644 --- a/docs/tasks/README.md +++ b/docs/tasks/README.md @@ -7,6 +7,7 @@ - 被环境或依赖挡住的事项写进根目录 `BLOCKED.md`;Bug 事实写进 `docs/BUG_HISTORY.md`;两者不在这里重复。 - 纯文档改动不触发 staging 门禁(见 `deploy/gated-paths.txt`)。 +- [VedAstro 请求与回显验证(#327)](PROGRESS-vedastro-request-verification-20261122.md) — 服务端鉴权、回显校验和发布后验收。 - [行运同本命星座事实(#325)](PROGRESS-transit-natal-return-20261118.md) — 土星、木星位置比较与证据覆盖。 - [生时纠正评分停用(#323)](PROGRESS-rect-cut-shadbala-scoring-20261117.md) — Shadbala 评分、Python 暂停及旧缓存回归。 - [生时用途政策 v2(#320)](PROGRESS-rect-purpose-policy-v2-20261117.md) — 断言组、时间粒度和三份原生 CLI 对照。 diff --git a/scripts/diagnose_vedastro_mode.py b/scripts/diagnose_vedastro_mode.py index 7bd8da827..10dc2d41c 100644 --- a/scripts/diagnose_vedastro_mode.py +++ b/scripts/diagnose_vedastro_mode.py @@ -67,8 +67,10 @@ def build_report() -> dict: if timeout_seconds <= FAST_TIMEOUT_THRESHOLD_SECONDS: missing.append("VEDASTRO_TIMEOUT_SECONDS>5") readiness_blockers.append("timeout_too_low") - if endpoint and network_enabled and not has_api_key: - readiness_blockers.append("premium_key_missing") + if not has_api_key: + missing.append("VEDASTRO_API_KEY") + if endpoint and network_enabled: + readiness_blockers.append("premium_key_missing") official_ready = not missing mode = "official_extended" if official_ready else "fast_local_fallback" return { @@ -80,7 +82,7 @@ def build_report() -> dict: "has_api_key": has_api_key, "free_tier_queue_enabled": free_tier_queue_enabled, "deprecated_env_present": deprecated_env_present, - "free_tier_possible_with_cache_queue": bool(endpoint and network_enabled and timeout_seconds > FAST_TIMEOUT_THRESHOLD_SECONDS), + "free_tier_possible_with_cache_queue": False, "missing": missing, "readiness_blockers": readiness_blockers, "expected_fallback_status": ( @@ -97,10 +99,10 @@ def build_report() -> dict: "VEDASTRO_API_ENDPOINT": endpoint or "https://api.vedastro.org/api", "VEDASTRO_ENABLE_NETWORK": "1", "VEDASTRO_TIMEOUT_SECONDS": "20", - "VEDASTRO_API_KEY": "optional_but_recommended_for_stable_full_snapshot", + "VEDASTRO_API_KEY": "required_for_official_calculation", }, - "free_tier_policy": "Official REST Calculate is limited to 5 requests/minute. Queue/cache can reduce throttling, but free tier may still return blocked or partial snapshots.", - "premium_key_policy": "API key recommended for stable official full snapshot; free tier may still block or throttle.", + "free_tier_policy": "The application requires authentication before official calculation requests.", + "premium_key_policy": "A missing API key blocks official calculation requests.", "raw_response_acceptance": "vedastro_official.raw_response must be present before claiming official cloud closure.", "default_path": "REST bridge scripts/vedastro_rest_bridge.py against /api/Calculate. Official MCP tools/call is protocol-probe only.", }, diff --git a/scripts/jyotish_api_server.py b/scripts/jyotish_api_server.py index d9682f30b..36417172a 100644 --- a/scripts/jyotish_api_server.py +++ b/scripts/jyotish_api_server.py @@ -2822,7 +2822,7 @@ def _build_api_chart_cache_payload(body: dict) -> dict: # 原因:占星师 2026-11-08 第五轮逐项答复 K3:缓存须按 profile 键控并随 profile 变化失效。 # 原值 8;新值 9:缓存键再加 position_mode(交点口径本来就在 calculation.node_mode 里),旧缓存全部失效。 # 原因:BUG-1828:缓存键显式记录交点与位置口径 - 'cache_schema_version': 9, + 'cache_schema_version': 10, # BUG-2171: discard chart responses from the unverified provider contract. 'analysis_profiles': {key: profiles[key] for key in ('functional_profile', 'narayana_step_profiles')}, 'birth': retention.normalize_chart_cache_birth(body), 'calculation': { @@ -3356,7 +3356,7 @@ class JyotishComputeService(VedastroEvidenceMixin, SynastryMixin): elif not network_enabled: status = 'network_execution_disabled' else: - status = 'live_ready' + status = 'live_ready' if has_api_key else 'vedastro_api_key_missing' artifact_dir = getattr(adapter, 'ARTIFACT_DIR', None) latest_artifact = None if artifact_dir and os.path.isdir(artifact_dir): @@ -3378,7 +3378,7 @@ class JyotishComputeService(VedastroEvidenceMixin, SynastryMixin): 'required_env': { 'endpoint': 'VEDASTRO_API_ENDPOINT', 'network': 'VEDASTRO_ENABLE_NETWORK', - 'api_key_optional': 'VEDASTRO_API_KEY', + 'api_key_required': 'VEDASTRO_API_KEY', }, 'live_profile': 'vedastro-live', 'transport': 'http_json_service_boundary', diff --git a/scripts/run_quality_gate.py b/scripts/run_quality_gate.py index 519b73302..1694cf188 100644 --- a/scripts/run_quality_gate.py +++ b/scripts/run_quality_gate.py @@ -192,6 +192,7 @@ RUNTIME_TRUTH_PYTEST_TARGETS = [ "tests/test_api_server_security.py::test_high_rigor_vedastro_official_summary_exposes_top_reader_contract_from_full_snapshot", "tests/test_vedastro_external_technique_evidence.py::test_strict_workflow_uses_shared_consultation_executor", "tests/test_vedastro_runtime_mode_diagnostics.py", + "tests/test_vedastro_request_verification_2171.py", "tests/test_interpretation_source_inventory_gate.py::test_quality_gate_runs_interpretation_source_inventory_gate", "tests/test_interpretation_source_runtime_coverage.py", "tests/test_final_jhora_evidence_packet_acceptance.py", diff --git a/scripts/vedastro_consultation_snapshot.py b/scripts/vedastro_consultation_snapshot.py index 8fd2cf4a2..cf9f38011 100644 --- a/scripts/vedastro_consultation_snapshot.py +++ b/scripts/vedastro_consultation_snapshot.py @@ -42,7 +42,7 @@ except ModuleNotFoundError: # pragma: no cover - script execution path snapshot_cache_key, ) -NEGATIVE_CACHE_SCHEMA = "vedastro_snapshot_negative_cache.v1" +NEGATIVE_CACHE_SCHEMA = "vedastro_snapshot_negative_cache.v2" DEFERRED_IN_CONSULTATION = "deferred_in_consultation" _SHA256_NAME = re.compile(r"^[0-9a-f]{64}\.json$") _IDENTITY_FIELDS = ( diff --git a/scripts/vedastro_official_capability_runner.py b/scripts/vedastro_official_capability_runner.py index 47322fa85..725beb4ba 100644 --- a/scripts/vedastro_official_capability_runner.py +++ b/scripts/vedastro_official_capability_runner.py @@ -441,6 +441,10 @@ def _method_payload_for_instance(method: str, case: dict[str, Any], identity: st return payload +def _params_with_ayanamsa(payload: dict[str, Any], case: dict[str, Any]) -> dict[str, Any]: + return {**payload, "ayanamsa": case.get("ayanamsa_policy") or case.get("ayanamsa") or "lahiri"} + + def _call_bridge(method: str, payload: dict[str, Any]) -> dict[str, Any]: return call_bridge_method(method, payload) @@ -469,7 +473,7 @@ def run_selected_methods(methods: list[str], birth_payload: dict[str, Any]) -> d results[method] = {"available": False, "status": "unsupported_signature"} skipped_count += 1 continue - results[method] = _call_bridge(method, payload) + results[method] = _call_bridge(method, _params_with_ayanamsa(payload, birth_payload)) if results[method].get("status") == "ok": ok_count += 1 @@ -635,7 +639,7 @@ def run_full_capability_catalog(birth_payload: dict[str, Any]) -> dict[str, Any] if method in stub_map: report = stub_map[method] else: - report = _call_bridge(method, payload) + report = _call_bridge(method, _params_with_ayanamsa(payload, birth_payload)) status = str(report.get("status") or "blocked") executed_count += 1 bucket_row["executed"] += 1 @@ -713,6 +717,11 @@ def run_full_capability_catalog(birth_payload: dict[str, Any]) -> dict[str, Any] } +def _fanout_status(statuses: dict[str, str]) -> str: + distinct = set(statuses.values()) + return next(iter(distinct)) if len(distinct) == 1 else "partial" + + def run_snapshot_bundle(bundle: str, birth_payload: dict[str, Any]) -> dict[str, Any]: if bundle == "official_full_capability_catalog": return run_full_capability_catalog(birth_payload) @@ -745,7 +754,7 @@ def run_snapshot_bundle(bundle: str, birth_payload: dict[str, Any]) -> dict[str, report = {"available": False, "status": "stub_not_provided"} else: payload = _method_payload_for_instance("AllPlanetData", birth_payload, planet) - report = {"available": False, "status": "unsupported_signature"} if payload is None else _call_bridge("AllPlanetData", payload) + report = {"available": False, "status": "unsupported_signature"} if payload is None else _call_bridge("AllPlanetData", _params_with_ayanamsa(payload, birth_payload)) status = str(report.get("status") or "blocked") planet_statuses[planet] = "ok" if status == "ok" else status if status == "ok": @@ -758,7 +767,7 @@ def run_snapshot_bundle(bundle: str, birth_payload: dict[str, Any]) -> dict[str, } if chart_core: snapshot_sections["chart_core"] = chart_core - section_statuses["chart_core"] = "ok" if all(value == "ok" for value in planet_statuses.values()) else "partial" + section_statuses["chart_core"] = _fanout_status(planet_statuses) section_statuses["chart_core_fanout"] = planet_statuses if section_statuses["chart_core"] == "ok": coverage_sections.append("chart_core") @@ -773,7 +782,7 @@ def run_snapshot_bundle(bundle: str, birth_payload: dict[str, Any]) -> dict[str, report = {"available": False, "status": "stub_not_provided"} else: payload = _method_payload_for_instance("AllHouseData", birth_payload, house) - report = {"available": False, "status": "unsupported_signature"} if payload is None else _call_bridge("AllHouseData", payload) + report = {"available": False, "status": "unsupported_signature"} if payload is None else _call_bridge("AllHouseData", _params_with_ayanamsa(payload, birth_payload)) status = str(report.get("status") or "blocked") house_statuses[house] = "ok" if status == "ok" else status if status == "ok": @@ -786,7 +795,7 @@ def run_snapshot_bundle(bundle: str, birth_payload: dict[str, Any]) -> dict[str, } if house_core: snapshot_sections["house_core"] = house_core - section_statuses["house_core"] = "ok" if all(value == "ok" for value in house_statuses.values()) else "partial" + section_statuses["house_core"] = _fanout_status(house_statuses) section_statuses["house_core_fanout"] = house_statuses if section_statuses["house_core"] == "ok": coverage_sections.append("house_core") @@ -805,7 +814,7 @@ def run_snapshot_bundle(bundle: str, birth_payload: dict[str, Any]) -> dict[str, report = {"available": False, "status": "stub_not_provided"} else: payload = _method_payload_for_instance(method, birth_payload) - report = {"available": False, "status": "unsupported_signature"} if payload is None else _call_bridge(method, payload) + report = {"available": False, "status": "unsupported_signature"} if payload is None else _call_bridge(method, _params_with_ayanamsa(payload, birth_payload)) status = str(report.get("status") or "blocked") section_statuses[section_name] = "ok" if status == "ok" else status if status == "ok": diff --git a/scripts/vedastro_python_bridge.py b/scripts/vedastro_python_bridge.py index 0d9910196..094315d5b 100644 --- a/scripts/vedastro_python_bridge.py +++ b/scripts/vedastro_python_bridge.py @@ -16,7 +16,6 @@ from __future__ import annotations import argparse import contextlib import enum -import inspect import importlib import importlib.util import io @@ -27,6 +26,23 @@ import sys from pathlib import Path from typing import Any +try: + from scripts.vedastro_response_contract import ( + KEY_MISSING, + api_key, + ayanamsa_name, + response_failure, + verified_response, + ) +except ModuleNotFoundError: # pragma: no cover - direct CLI execution + from vedastro_response_contract import ( + KEY_MISSING, + api_key, + ayanamsa_name, + response_failure, + verified_response, + ) + ROOT = Path(__file__).resolve().parents[1] PACKAGE_NAME = "VedAstro" @@ -40,199 +56,6 @@ DEFAULT_VENV_PYTHONS = ( ROOT / "venv_vedastro" / "bin" / "python", ) -CHILD_RUNNER = r""" -import contextlib -import enum -import importlib -import io -import json -import sys - -MODULE_CANDIDATES = ("vedastro", "VedAstro") - - -def _offset_to_string(offset): - if isinstance(offset, str): - raw = offset.strip() - if not raw: - return "+00:00" - if raw[0] in "+-" and ":" in raw: - return raw - try: - offset = float(raw) - except ValueError: - return raw - - if isinstance(offset, (int, float)): - sign = "+" if offset >= 0 else "-" - absolute = abs(float(offset)) - hours = int(absolute) - minutes = int(round((absolute - hours) * 60)) - if minutes == 60: - hours += 1 - minutes = 0 - return f"{sign}{hours:02d}:{minutes:02d}" - - return "+00:00" - - -def _import_module(): - for name in MODULE_CANDIDATES: - with contextlib.redirect_stdout(io.StringIO()): - try: - return name, importlib.import_module(name) - except ModuleNotFoundError: - continue - return None, None - - -def _coerce(module, value): - if isinstance(value, list): - return [_coerce(module, item) for item in value] - if isinstance(value, dict): - enum_name = value.get("__vedastro_enum__") - if enum_name: - enum_type = getattr(module, enum_name) - return getattr(enum_type, value["value"]) - - type_name = value.get("__vedastro_type__") - if type_name == "GeoLocation": - return module.GeoLocation( - value["location_name"], - value["longitude"], - value["latitude"], - ) - if type_name == "Time": - geolocation = _coerce(module, value["geolocation"]) if value.get("geolocation") else None - if value.get("time_string") is not None: - return module.Time(value["time_string"], geolocation) - time_string = ( - f"{int(value['hour']):02d}:{int(value['minute']):02d} " - f"{int(value['day']):02d}/{int(value['month']):02d}/{int(value['year'])} " - f"{_offset_to_string(value.get('offset', '+00:00'))}" - ) - return module.Time(time_string, geolocation) - - if type_name: - target = getattr(module, type_name) - args = [_coerce(module, item) for item in value.get("args", [])] - kwargs = { - key: _coerce(module, item) - for key, item in value.get("kwargs", {}).items() - } - if args or kwargs: - return target(*args, **kwargs) - payload = { - key: _coerce(module, item) - for key, item in value.items() - if not key.startswith("__") - } - return target(**payload) - - return { - key: _coerce(module, item) - for key, item in value.items() - } - return value - - -def _serialize(value): - if value is None or isinstance(value, (str, int, float, bool)): - return value - if isinstance(value, enum.Enum): - return { - "type": type(value).__name__, - "name": value.name, - "value": value.value, - } - if isinstance(value, (list, tuple, set)): - return [_serialize(item) for item in value] - if isinstance(value, dict): - return {str(key): _serialize(item) for key, item in value.items()} - if hasattr(value, "to_json"): - try: - payload = value.to_json() - if isinstance(payload, str): - try: - return json.loads(payload) - except json.JSONDecodeError: - return payload - return _serialize(payload) - except Exception: - pass - if hasattr(value, "__dict__"): - return { - key: _serialize(item) - for key, item in vars(value).items() - if not key.startswith("_") - } - return str(value) - - -def _resolve_callable(module, method_name): - parts = [part for part in method_name.split(".") if part] - if not parts: - raise AttributeError("empty_method_name") - if len(parts) == 1: - return getattr(module.Calculate, parts[0]) - - current = module - for part in parts: - current = getattr(current, part) - return current - - -def main(): - method = sys.argv[1] - params = json.loads(sys.argv[2]) - module_name, module = _import_module() - if module is None: - print(json.dumps({ - "available": False, - "status": "python_package_not_installed", - "method": method, - "source": "vedastro_python_bridge_child", - })) - return - - call_target = _resolve_callable(module, method) - - args = [] - kwargs = {} - if isinstance(params, dict) and ("args" in params or "kwargs" in params): - args = [_coerce(module, item) for item in params.get("args", [])] - kwargs = { - key: _coerce(module, item) - for key, item in params.get("kwargs", {}).items() - } - elif isinstance(params, dict): - kwargs = { - key: _coerce(module, item) - for key, item in params.items() - } - elif isinstance(params, list): - args = [_coerce(module, item) for item in params] - elif params is not None: - args = [_coerce(module, params)] - - with contextlib.redirect_stdout(io.StringIO()): - result = call_target(*args, **kwargs) - - print(json.dumps({ - "available": True, - "status": "ok", - "method": method, - "module_name": module_name, - "result": _serialize(result), - "source": "vedastro_python_bridge", - })) - - -if __name__ == "__main__": - main() -""" - - CAPABILITY_RUNNER = r""" import contextlib import importlib @@ -433,24 +256,56 @@ def _serialize_runtime_value(value: Any) -> Any: return str(value) -def _resolve_runtime_callable(module: Any, method_name: str) -> Any: - parts = [part for part in method_name.split(".") if part] - if not parts: - raise AttributeError("empty_method_name") - if len(parts) == 1: - return getattr(module.Calculate, parts[0]) - current = module - for part in parts: - current = getattr(current, part) - return current +def _resolve_runtime_callable(calculate: Any, method_name: str) -> Any: + name = method_name.removeprefix("Calculate.") + if not name or name.startswith("_") or name == "SetAPIKey" or "." in name: + raise AttributeError("unsupported_calculator_method") + return getattr(calculate, name) + + +class _ProviderRejected(RuntimeError): + pass + + +def _verified_calculator(module: Any, key: str, ayanamsa: str) -> Any: + # Reuse the pinned SDK's argument serializers. Its normal transport unwraps + # Payload before callers can check Input, so validate at its request boundary. + import requests + + class VerifiedCalculate(module.Calculate): + @classmethod + def _make_request(cls, endpoint, params): + body = {**params, "Ayanamsa": ayanamsa, "APIKey": cls.api_key} + response = requests.post( + f"{cls.base_url}/{endpoint}", json=body, timeout=120, allow_redirects=False, + ) + response.raise_for_status() + envelope = verified_response(endpoint, body, response.json(), key) + if envelope["Status"] != "Pass": + raise _ProviderRejected(response_failure(envelope)) + payload = envelope["Payload"] + if isinstance(payload, dict) and len(payload) == 1: + return next(iter(payload.values())) + return payload + + VerifiedCalculate.SetAPIKey(key) + return VerifiedCalculate def _call_in_current_python(method: str, params: dict[str, Any]) -> dict[str, Any]: + key = api_key() + if not key: + return _provider_blocked(method, KEY_MISSING) module_name, module = _import_runtime_module() if module is None: return _missing_package_result(method) try: - target = _resolve_runtime_callable(module, method) + settings = dict(params) if isinstance(params, dict) else {} + ayanamsa = ayanamsa_name(settings.pop("ayanamsa", "lahiri")) + if isinstance(params, dict): + params = settings + calculate = _verified_calculator(module, key, ayanamsa) + target = _resolve_runtime_callable(calculate, method) args: list[Any] = [] kwargs: dict[str, Any] = {} if isinstance(params, dict) and ("args" in params or "kwargs" in params): @@ -473,6 +328,8 @@ def _call_in_current_python(method: str, params: dict[str, Any]) -> dict[str, An "python_bin": sys.executable, "source": "vedastro_python_bridge", } + except _ProviderRejected as exc: + return _provider_blocked(method, str(exc)) except Exception as exc: return { "available": False, @@ -480,7 +337,7 @@ def _call_in_current_python(method: str, params: dict[str, Any]) -> dict[str, An "method": method, "module_name": module_name, "python_bin": sys.executable, - "error": {"type": type(exc).__name__, "message": str(exc)}, + "error": {"type": type(exc).__name__}, "source": "vedastro_python_bridge", } @@ -549,7 +406,8 @@ def _select_python_bin() -> str | None: def _call_via_child_python(python_bin: str, method: str, params: dict[str, Any]) -> dict[str, Any]: child_env = os.environ.copy() completed = subprocess.run( - [python_bin, "-c", CHILD_RUNNER, method, json.dumps(params, ensure_ascii=False)], + [python_bin, str(Path(__file__).resolve()), "--sdk-child", "--method", method, + "--params-json", json.dumps(params, ensure_ascii=False)], check=False, capture_output=True, text=True, @@ -562,8 +420,6 @@ def _call_via_child_python(python_bin: str, method: str, params: dict[str, Any]) "status": "bridge_runtime_error", "method": method, "python_bin": python_bin, - "stderr": (completed.stderr or "").strip(), - "stdout_excerpt": (completed.stdout or "").strip()[:500], "source": "vedastro_python_bridge", } @@ -575,8 +431,6 @@ def _call_via_child_python(python_bin: str, method: str, params: dict[str, Any]) "status": "bridge_invalid_json", "method": method, "python_bin": python_bin, - "stdout_excerpt": (completed.stdout or "").strip()[:500], - "stderr": (completed.stderr or "").strip()[:500], "source": "vedastro_python_bridge", } @@ -668,6 +522,15 @@ def _missing_package_result(method: str) -> dict[str, Any]: } +def _provider_blocked(method: str, status: str) -> dict[str, Any]: + return { + "available": False, + "status": status, + "method": method, + "source": "vedastro_python_bridge", + } + + def call_method(method: str, params: dict[str, Any]) -> dict[str, Any]: stub = os.environ.get(STUB_RESULT_ENV, "").strip() if stub: @@ -683,6 +546,9 @@ def call_method(method: str, params: dict[str, Any]) -> dict[str, Any]: if os.environ.get(FORCE_UNAVAILABLE_ENV, "").strip().lower() in {"1", "true", "yes"}: return _missing_package_result(method) + if not api_key(): + return _provider_blocked(method, KEY_MISSING) + if _package_available(): return _call_in_current_python(method, params) @@ -701,14 +567,26 @@ def list_capabilities() -> dict[str, Any]: return _list_capabilities_via_child_python(python_bin) +def _fanout_status(rows: dict[str, Any]) -> str: + statuses = ["ok" if row["Status"] == "Pass" else row["Payload"]["status"] for row in rows.values()] + if all(status == "ok" for status in statuses): + return "ok" + if all(status == statuses[0] for status in statuses): + return statuses[0] + return "partial" + + def call_high_value(method_key: str, payload: dict[str, Any]) -> dict[str, Any]: + def call(method: str, params: dict[str, Any]) -> dict[str, Any]: + return call_method(method, {**params, "ayanamsa": payload.get("ayanamsa") or "lahiri"}) + if method_key == "event_tag_catalog": - return call_method("GetAllEventDataGroupedByTag", {}) + return call("GetAllEventDataGroupedByTag", {}) if method_key == "planet_longitude": planet = payload["planet"] time = payload["time"] - return call_method( + return call( "PlanetNirayanaLongitude", { "args": [ @@ -722,12 +600,12 @@ def call_high_value(method_key: str, payload: dict[str, Any]) -> dict[str, Any]: birth_time = payload["birth_time"] check_time = payload["check_time"] levels = int(payload.get("levels", 3)) - return call_method("DasaAtTime", {"args": [birth_time, check_time, levels]}) + return call("DasaAtTime", {"args": [birth_time, check_time, levels]}) if method_key == "chara_dasha_snapshot": birth_time = payload["birth_time"] check_time = payload["check_time"] - return call_method("GetCharaDasaAtTime", {"args": [birth_time, check_time]}) + return call("GetCharaDasaAtTime", {"args": [birth_time, check_time]}) if method_key == "official_full_snapshot_bundle": birth_time = payload["birth_time"] @@ -744,7 +622,7 @@ def call_high_value(method_key: str, payload: dict[str, Any]) -> dict[str, Any]: section_statuses: dict[str, str] = {} for planet in planets: - report = call_method( + report = call( "AllPlanetData", { "args": [ @@ -758,10 +636,10 @@ def call_high_value(method_key: str, payload: dict[str, Any]) -> dict[str, Any]: "Payload": {"AllPlanetData": report.get("result")} if report.get("status") == "ok" else report, } if chart_core: - section_statuses["chart_core"] = "ok" + section_statuses["chart_core"] = _fanout_status(chart_core) for house in houses: - report = call_method( + report = call( "AllHouseData", { "args": [ @@ -775,22 +653,22 @@ def call_high_value(method_key: str, payload: dict[str, Any]) -> dict[str, Any]: "Payload": {"AllHouseData": report.get("result")} if report.get("status") == "ok" else report, } if house_core: - section_statuses["house_core"] = "ok" + section_statuses["house_core"] = _fanout_status(house_core) - dasha_report = call_method( + dasha_report = call( "DasaAtRange", {"args": [birth_time, start_time, end_time, levels, precision_hours]}, ) - vimshottari_report = call_method( + vimshottari_report = call( "DasaAtTime", {"args": [birth_time, check_time, levels]}, ) - chara_report = call_method( + chara_report = call( "GetCharaDasaAtTime", {"args": [birth_time, check_time]}, ) - strength_report = call_method("AllPlanetStrength", {"args": [birth_time]}) - ashtakavarga_report = call_method("AshtakvargaLifeMap", {"args": [birth_time]}) + strength_report = call("AllPlanetStrength", {"args": [birth_time]}) + ashtakavarga_report = call("AshtakvargaLifeMap", {"args": [birth_time]}) snapshot_sections = { "chart_core": chart_core, @@ -818,7 +696,8 @@ def call_high_value(method_key: str, payload: dict[str, Any]) -> dict[str, Any]: } for section_name in ("dasha_all", "vimshottari_now", "chara_dasha_now", "shadbala", "ashtakavarga"): - section_statuses[section_name] = "ok" if snapshot_sections[section_name]["Status"] == "Pass" else "fail" + row = snapshot_sections[section_name] + section_statuses[section_name] = "ok" if row["Status"] == "Pass" else row["Payload"]["status"] filled_sections = [name for name, status in section_statuses.items() if status == "ok"] overall_status = "ok" if filled_sections else "blocked" @@ -853,6 +732,7 @@ def call_high_value(method_key: str, payload: dict[str, Any]) -> dict[str, Any]: def main() -> int: parser = argparse.ArgumentParser(description="VedAstro Python bridge") parser.add_argument("--print-schema", action="store_true") + parser.add_argument("--sdk-child", action="store_true", help=argparse.SUPPRESS) parser.add_argument("--method", default="") parser.add_argument("--params-json", default="{}") parser.add_argument("--high-value", default="") @@ -895,6 +775,8 @@ def main() -> int: ], }, } + elif args.sdk_child: + result = _call_in_current_python(args.method, json.loads(args.params_json)) elif args.list_capabilities: result = list_capabilities() elif args.high_value: diff --git a/scripts/vedastro_response_contract.py b/scripts/vedastro_response_contract.py new file mode 100644 index 000000000..65335e156 --- /dev/null +++ b/scripts/vedastro_response_contract.py @@ -0,0 +1,139 @@ +"""Validate the input VedAstro reports having actually calculated.""" + +from __future__ import annotations + +import math +import os +from datetime import datetime +from typing import Any + +# Swiss Ephemeris mode numbers in the VedAstro 1.23.25 enum and response echo. +_AYANAMSAS = { + "FAGAN_BRADLEY": 0, + "LAHIRI": 1, + "RAMAN": 3, + "KRISHNAMURTI": 5, + "DJWHAL_KHUL": 6, + "YUKTESHWAR": 7, + "SASSANIAN": 16, + "TRUE_CITRA": 27, + "TRUE_REVATI": 28, + "TRUE_PUSHYA": 29, +} +_AYANAMSA_ALIASES = { + "FAGAN": "FAGAN_BRADLEY", + "KP": "KRISHNAMURTI", + "KRISHNAMURTI/KP": "KRISHNAMURTI", + "KRISHNAMURTI_PADDHATI": "KRISHNAMURTI", + "TRUE_CHITRA": "TRUE_CITRA", +} +INPUT_ECHO_MISMATCH = "input_echo_mismatch" +KEY_MISSING = "vedastro_api_key_missing" + + +def api_key() -> str: + return os.environ.get("VEDASTRO_API_KEY", "").strip() + + +def ayanamsa_name(value: Any) -> str: + name = str(value).strip().upper().replace("-", "_").replace(" ", "_") + return _AYANAMSA_ALIASES.get(name, name) + + +def _ayanamsa_code(value: Any) -> int | None: + if isinstance(value, bool): + return None + if isinstance(value, int) or isinstance(value, str) and value.isdecimal(): + return int(value) + return _AYANAMSAS.get(ayanamsa_name(value)) + + +def _same_time(expected: dict[str, Any], actual: Any) -> bool: + if not isinstance(actual, dict): + return False + try: + requested = datetime.strptime(expected["StdTime"], "%H:%M %d/%m/%Y %z") + calculated = datetime.strptime(actual["StdTime"], "%H:%M %d/%m/%Y %z") + return ( + requested == calculated + and requested.utcoffset() == calculated.utcoffset() + and all( + math.isclose( + float(expected["Location"][coordinate]), float(actual["Location"][coordinate]), + rel_tol=0, abs_tol=1e-6, + ) + for coordinate in ("Latitude", "Longitude") + ) + ) + except (KeyError, TypeError, ValueError, OverflowError): + return False + + +def _input_matches(method: str, submitted: dict[str, Any], echo: Any) -> bool: + if not isinstance(echo, dict) or echo.get("CalculatorName") != method: + return False + expected_code = _ayanamsa_code(submitted.get("Ayanamsa")) + if expected_code is None or _ayanamsa_code(echo.get("Ayanamsa")) != expected_code: + return False + parameters = echo.get("Parameters") + if not isinstance(parameters, list): + return False + echoed: dict[str, Any] = {} + for parameter in parameters: + if not isinstance(parameter, dict) or not isinstance(parameter.get("Name"), str): + return False + name = parameter["Name"].casefold() + if name in echoed: + return False + echoed[name] = parameter.get("Value") + for name, expected in submitted.items(): + actual = echoed.get(name.casefold()) + if isinstance(expected, dict) and "StdTime" in expected and not _same_time(expected, actual): + return False + if name in {"planetName", "houseName"}: + if isinstance(actual, dict): + actual = actual.get("Name") + if expected != actual: + return False + return True + + +def blocked_response(reason: str) -> dict[str, Any]: + return {"Status": "Fail", "Payload": {"reason": reason}} + + +def response_failure(payload: dict[str, Any]) -> str | None: + if not isinstance(payload, dict) or payload.get("Status") != "Fail": + return None + body = payload.get("Payload") + reason = body.get("reason") if isinstance(body, dict) else None + return reason if isinstance(reason, str) else None + + +def verified_response(method: str, submitted: dict[str, Any], response: Any, key: str) -> dict[str, Any]: + if not isinstance(response, dict): + return blocked_response("invalid_response") + if response.get("Status") != "Pass": + error_text = str(response.get("Payload") or "").lower() + if any(text in error_text for text in ("rate limit", "calls/minute", "too many requests")): + return blocked_response("rate_limited") + return blocked_response("vedastro_provider_rejected") + if not _input_matches(method, submitted, response.get("Input")): + return blocked_response(INPUT_ECHO_MISMATCH) + if "Payload" not in response or response["Payload"] is None: + return blocked_response("invalid_response") + # Persist only calculation data. The provider can echo credentials in Input + # or in diagnostics, and neither is needed after validating the request. + return {"Status": "Pass", "Payload": redact_key(response["Payload"], key)} + + +def redact_key(value: Any, key: str) -> Any: + if not key: + return value + if isinstance(value, str): + return value.replace(key, "[redacted]") + if isinstance(value, list): + return [redact_key(item, key) for item in value] + if isinstance(value, dict): + return {redact_key(name, key): redact_key(item, key) for name, item in value.items()} + return value diff --git a/scripts/vedastro_rest_bridge.py b/scripts/vedastro_rest_bridge.py index c4cdf5eb9..aadc5a304 100644 --- a/scripts/vedastro_rest_bridge.py +++ b/scripts/vedastro_rest_bridge.py @@ -24,6 +24,25 @@ import urllib.request from pathlib import Path from typing import Any +try: + from scripts.vedastro_response_contract import ( + KEY_MISSING, + api_key, + ayanamsa_name, + blocked_response, + response_failure, + verified_response, + ) +except ModuleNotFoundError: # pragma: no cover - direct CLI execution + from vedastro_response_contract import ( + KEY_MISSING, + api_key, + ayanamsa_name, + blocked_response, + response_failure, + verified_response, + ) + API = "https://api.vedastro.org/api/Calculate" RATE_LIMIT_PER_MINUTE = 5 # Fictional smoke only. Do not replace with a real birth record. @@ -78,20 +97,20 @@ def reset_rate_limiter() -> None: def build_horoscope_payload(args: argparse.Namespace) -> dict[str, Any]: return { - "Ayanamsa": args.ayanamsa, - "BirthTime": _time(args.birth, args.name, args.lat, args.lon), - "SortByWeight": False, + "Ayanamsa": ayanamsa_name(args.ayanamsa), + "birthTime": _time(args.birth, args.name, args.lat, args.lon), + "sortByWeight": False, } def build_dasa_payload(args: argparse.Namespace) -> dict[str, Any]: return { - "Ayanamsa": args.ayanamsa, - "BirthTime": _time(args.birth, args.name, args.lat, args.lon), - "StartTime": _time(_date_to_vedastro_std(args.start), args.name, args.lat, args.lon), - "EndTime": _time(_date_to_vedastro_std(args.end), args.name, args.lat, args.lon), - "Levels": 3, - "PrecisionHours": 100, + "Ayanamsa": ayanamsa_name(args.ayanamsa), + "birthTime": _time(args.birth, args.name, args.lat, args.lon), + "startTime": _time(_date_to_vedastro_std(args.start), args.name, args.lat, args.lon), + "endTime": _time(_date_to_vedastro_std(args.end), args.name, args.lat, args.lon), + "levels": 3, + "precisionHours": 100, } @@ -113,6 +132,9 @@ def call( timeout: float = 90, skip_rate_limit: bool = False, ) -> dict[str, Any]: + key = api_key() + if not key: + return blocked_response(KEY_MISSING) if not skip_rate_limit: consume_rate_token() req = urllib.request.Request( @@ -121,6 +143,7 @@ def call( headers={"Content-Type": "application/json"}, method="POST", ) + req.add_unredirected_header("X-api-key", key) try: if opener is None: with urllib.request.urlopen(req, timeout=timeout) as response: @@ -137,6 +160,7 @@ def call( "http_status": 429, } raise + data = verified_response(method, payload, data, key) if out: Path(out).write_text(json.dumps(data, ensure_ascii=False, indent=1) + "\n", encoding="utf-8") print(f"[已落盘] {out}") @@ -144,7 +168,7 @@ def call( def probe_calculate_health(*, opener: Any | None = None, timeout: float = 8) -> dict[str, Any]: - """POST a fictional smoke horoscope and report whether Status is Pass.""" + """POST a fictional smoke horoscope and report whether its input is verified.""" args = argparse.Namespace(**SMOKE_DEFAULT) try: payload = build_horoscope_payload(args) @@ -164,14 +188,11 @@ def probe_calculate_health(*, opener: Any | None = None, timeout: float = 8) -> "endpoint": API, "transport": "rest", } - status = str(data.get("Status") or "") - if status.lower() == "pass": + if data.get("Status") == "Pass": return {"status": "official_verified", "reason": "status_pass", "endpoint": API, "transport": "rest"} - if str(data.get("official_closure_reason") or "") == "rate_limited": - return {"status": "official_blocked", "reason": "rate_limited", "endpoint": API, "transport": "rest"} return { "status": "official_blocked", - "reason": f"status_{status or 'missing'}", + "reason": data.get("official_closure_reason") or response_failure(data) or "invalid_response", "endpoint": API, "transport": "rest", } diff --git a/scripts/vedastro_service_adapter.py b/scripts/vedastro_service_adapter.py index 71b055b9e..6dc59eb23 100644 --- a/scripts/vedastro_service_adapter.py +++ b/scripts/vedastro_service_adapter.py @@ -9,8 +9,8 @@ workspace can evolve from research notes to an executable adapter contract. from __future__ import annotations import argparse -import http.client import hashlib +import http.client import json import os import socket @@ -22,14 +22,34 @@ import time from datetime import datetime from pathlib import Path from typing import Any -from urllib import request, error +from urllib import error, request from urllib.parse import urlparse try: from scripts.local_env import load_local_env + from scripts.vedastro_response_contract import ( + INPUT_ECHO_MISMATCH, + KEY_MISSING, + api_key, + ayanamsa_name, + blocked_response, + redact_key, + response_failure, + verified_response, + ) from scripts.vedastro_runtime_context import timeout_override_seconds except ModuleNotFoundError: # pragma: no cover - script execution path from local_env import load_local_env + from vedastro_response_contract import ( + INPUT_ECHO_MISMATCH, + KEY_MISSING, + api_key, + ayanamsa_name, + blocked_response, + redact_key, + response_failure, + verified_response, + ) from vedastro_runtime_context import timeout_override_seconds @@ -104,8 +124,8 @@ SUPPORTED_RANGE_SCAN_DOMAINS = {"marriage", "wealth", "career"} SUPPORTED_EXTERNAL_TECHNIQUE_DOMAINS = {"marriage", "wealth", "career", "general"} OFFICIAL_SEARCH_EVENTS_ENDPOINT_PATH = "/Calculate/SearchEvents" OFFICIAL_SEARCH_EVENTS_METHOD = "POST" -OFFICIAL_SEARCH_EVENTS_PROFILE_VERSION = "official_builder_search_events_v1" -OFFICIAL_FULL_SNAPSHOT_PROFILE_VERSION = "official_full_snapshot_v1" +OFFICIAL_SEARCH_EVENTS_PROFILE_VERSION = "official_builder_search_events_v2" +OFFICIAL_FULL_SNAPSHOT_PROFILE_VERSION = "official_full_snapshot_v2" OFFICIAL_METHOD_CATALOG_URL = "https://vedastro.org/Complete-List-VedAstro-API-Methods-Calculators.html" OFFICIAL_FULL_SNAPSHOT_METHODS = [ { @@ -563,7 +583,7 @@ def schema() -> dict[str, Any]: "retry_policy": RETRY_POLICY, "required_env": { "endpoint": "VEDASTRO_API_ENDPOINT", - "api_key_optional": "VEDASTRO_API_KEY", + "api_key_required": "VEDASTRO_API_KEY", }, "request_contract": [ "year", @@ -621,15 +641,14 @@ def schema() -> dict[str, Any]: "route_template": OFFICIAL_SEARCH_EVENTS_ENDPOINT_PATH, "method": OFFICIAL_SEARCH_EVENTS_METHOD, "content_type": "application/json", - "optional_auth_header": "x-api-key", + "required_auth_header": "x-api-key", "body_fields": [ - "BirthTime", + "birthTime", + "atTime", "Ayanamsa", - "EventTagList", - ], - "range_mode_fields": [ - "AtTime | StartTime + EndTime + PrecisionHours", + "eventTagList", ], + "range_mode_fields": ["atTime"], }, "official_full_snapshot_request_contract": { "profile_version": OFFICIAL_FULL_SNAPSHOT_PROFILE_VERSION, @@ -637,10 +656,8 @@ def schema() -> dict[str, Any]: "method_catalog_url": OFFICIAL_METHOD_CATALOG_URL, "strategy": "fetch_official_raw_sections_first_then_local_crosscheck", "common_body_fields": [ - "BirthTime", + "time", "Ayanamsa", - "NodeMode", - "CalculationPreferences", ], "request_sections": [ { @@ -841,18 +858,11 @@ def _build_official_search_events_profile(request_preview: dict[str, Any]) -> di case = dict(request_preview) case["tz"] = _normalize_tz(case) body = { - "BirthTime": _time_json_from_case(case, f"{case['year']:04d}-{case['month']:02d}-{case['day']:02d}"), - "Ayanamsa": str(case.get("ayanamsa_policy") or "lahiri"), - "EventTagList": OFFICIAL_RANGE_SCAN_EVENT_TAGS.get(str(request_preview.get("domain") or ""), ["General"]), + "birthTime": _time_json_from_case(case, f"{case['year']:04d}-{case['month']:02d}-{case['day']:02d}"), + "Ayanamsa": ayanamsa_name(case.get("ayanamsa_policy") or "lahiri"), + "eventTagList": OFFICIAL_RANGE_SCAN_EVENT_TAGS.get(str(request_preview.get("domain") or ""), ["General"]), + "atTime": _time_json_from_case(case, str(request_preview["start_date"])), } - start_time = _time_json_from_case(case, str(request_preview["start_date"])) - end_time = _time_json_from_case(case, str(request_preview["end_date"])) - if str(request_preview["start_date"]) == str(request_preview["end_date"]): - body["AtTime"] = start_time - else: - body["StartTime"] = start_time - body["EndTime"] = end_time - body["PrecisionHours"] = 100 headers: dict[str, str] = {"Content-Type": "application/json"} return { "profile_version": OFFICIAL_SEARCH_EVENTS_PROFILE_VERSION, @@ -864,22 +874,9 @@ def _build_official_search_events_profile(request_preview: dict[str, Any]) -> di def _build_live_sampling_search_events_profile(request_preview: dict[str, Any]) -> dict[str, Any]: - case = dict(request_preview) - case["tz"] = _normalize_tz(case) - body = { - "BirthTime": _time_json_from_case(case, f"{case['year']:04d}-{case['month']:02d}-{case['day']:02d}"), - "Ayanamsa": str(case.get("ayanamsa_policy") or "lahiri"), - "EventTagList": OFFICIAL_RANGE_SCAN_EVENT_TAGS.get(str(request_preview.get("domain") or ""), ["General"]), - "AtTime": _time_json_from_case(case, str(request_preview["start_date"])), - } - headers: dict[str, str] = {"Content-Type": "application/json"} - return { - "profile_version": f"{OFFICIAL_SEARCH_EVENTS_PROFILE_VERSION}_live_sampling", - "endpoint_path": OFFICIAL_SEARCH_EVENTS_ENDPOINT_PATH, - "method": OFFICIAL_SEARCH_EVENTS_METHOD, - "headers": headers, - "body": body, - } + profile = _build_official_search_events_profile(request_preview) + profile["profile_version"] += "_live_sampling" + return profile def _official_common_body(case: dict[str, Any]) -> dict[str, Any]: @@ -890,12 +887,7 @@ def _official_common_body(case: dict[str, Any]) -> dict[str, Any]: normalized, f"{int(normalized['year']):04d}-{int(normalized['month']):02d}-{int(normalized['day']):02d}", ), - "Ayanamsa": str(normalized.get("ayanamsa_policy") or "lahiri"), - "NodeMode": str(normalized.get("node_policy") or "mean"), - "CalculationPreferences": { - "scope": "all_supported_official_calculations", - "user_visibility": "backend_raw_evidence_not_direct_user_report", - }, + "Ayanamsa": ayanamsa_name(normalized.get("ayanamsa_policy") or "lahiri"), } @@ -946,10 +938,10 @@ def _official_full_snapshot_manifest(case: dict[str, Any], case_id: str = "user_ body = dict(common_body) if item["section"] == "events_overview": body = { - "BirthTime": common_body["time"], + "birthTime": common_body["time"], "Ayanamsa": common_body["Ayanamsa"], - "EventTagList": sorted({tag for tags in OFFICIAL_RANGE_SCAN_EVENT_TAGS.values() for tag in tags}), - "AtTime": common_body["time"], + "eventTagList": sorted({tag for tags in OFFICIAL_RANGE_SCAN_EVENT_TAGS.values() for tag in tags}), + "atTime": common_body["time"], } if item["section"] == "dasha_all": body = _official_dasha_range_body(case, common_body) @@ -979,6 +971,9 @@ def _official_full_snapshot_manifest(case: dict[str, Any], case_id: str = "user_ "primary_source": "vedastro_official", "case_id": case_id, "reference_date": reference_date, + "chart_input_supported": ( + str(case.get("node_policy") or "mean") == "mean" and not case.get("second") + ), "method_catalog": { "url": OFFICIAL_METHOD_CATALOG_URL, "declared_coverage": VEDASTRO_CALCULATION_COVERAGE, @@ -1059,6 +1054,7 @@ def _try_official_python_bridge_snapshot_bundle(case: dict[str, Any]) -> dict[st "precision_hours": int(normalized.get("dasha_precision_hours") or 100), "planets": OFFICIAL_SNAPSHOT_PLANETS, "houses": OFFICIAL_SNAPSHOT_HOUSES, + "ayanamsa": normalized.get("ayanamsa_policy") or "lahiri", } report = _call_vedastro_python_bridge_high_value("official_full_snapshot_bundle", payload) if report.get("status") != "ok": @@ -1676,9 +1672,9 @@ def _build_live_request( request_url = f"{endpoint.rstrip('/')}{official_request_profile.get('endpoint_path', '')}" headers = dict(official_request_profile.get("headers") or headers) vedastro_payload = dict(official_request_profile.get("body") or {}) - api_key = os.environ.get("VEDASTRO_API_KEY", "").strip() - if api_key: - headers["x-api-key"] = api_key + key = api_key() + if key: + headers["x-api-key"] = key return request_url, headers, vedastro_payload @@ -1693,6 +1689,7 @@ def _cache_key_for_request( return _hash_payload( { "request_url": request_url, + "response_contract": "verified_input_echo_v1", "headers": normalized_headers, "body": vedastro_payload, } @@ -2023,14 +2020,25 @@ def _acquire_free_tier_slot(request_url: str) -> dict[str, Any]: _TRANSPORT_READ_ERRORS = (http.client.HTTPException, ConnectionError, ssl.SSLError) +def _requires_vedastro_key(request_url: str, request_preview: dict[str, Any]) -> bool: + return _is_official_public_endpoint(request_url) or request_preview.get("operation") in { + "range_scan", "official_full_snapshot", + } + + def _post_json(endpoint: str, request_preview: dict[str, Any]) -> dict[str, Any] | str: request_url, headers, vedastro_payload = _build_live_request(endpoint, request_preview) + key = headers.pop("x-api-key", "") + if not key and _requires_vedastro_key(request_url, request_preview): + return blocked_response(KEY_MISSING) req = request.Request( request_url, data=json.dumps(vedastro_payload).encode("utf-8"), headers=headers, method="POST", ) + if key: + req.add_unredirected_header("X-api-key", key) try: with request.urlopen(req, timeout=_timeout_seconds()) as resp: raw = resp.read().decode("utf-8") @@ -2039,7 +2047,22 @@ def _post_json(endpoint: str, request_preview: dict[str, Any]) -> dict[str, Any] except _TRANSPORT_READ_ERRORS as exc: # Every caller already turns URLError into network_error. raise error.URLError(f"response_read_failed:{type(exc).__name__}") from exc - return json.loads(raw) + payload = json.loads(raw) + request_path = urlparse(request_url).path + if "/Calculate/" in request_path: + if ( + request_path.endswith("/Calculate/SearchEvents") + and urlparse(endpoint).path.rstrip("/") != "/api" + and not _is_official_public_endpoint(request_url) + and isinstance(payload, dict) + and isinstance(payload.get("events"), list) + and "Status" not in payload + ): + return redact_key(payload, key) # Private candidate adapter's legacy event replay contract. + return verified_response(request_path.rsplit("/", 1)[-1], vedastro_payload, payload, key) + if isinstance(payload, dict) and "Status" in payload: + return blocked_response("unexpected_provider_envelope") + return redact_key(payload, key) def _retry_status_codes() -> set[int]: @@ -2054,6 +2077,8 @@ def _retry_status_codes() -> set[int]: def _post_json_with_retry(endpoint: str, request_preview: dict[str, Any]) -> tuple[dict[str, Any], int, list[int]]: request_url, headers, vedastro_payload = _build_live_request(endpoint, request_preview) + if not headers.get("x-api-key") and _requires_vedastro_key(request_url, request_preview): + return blocked_response(KEY_MISSING), 0, [] cache_key = _cache_key_for_request(request_url, headers, vedastro_payload) cached_payload, _ = _load_cached_payload(cache_key) if isinstance(cached_payload, dict): @@ -2248,7 +2273,10 @@ def run_case(case_id: str) -> dict[str, Any]: "source_metadata": _source_metadata(endpoint), } - return _normalize_success(payload, endpoint, request_preview) + failure = response_failure(payload) + if failure: + return {"status": failure, "available": False, "reason": failure} + return _normalize_success(payload, endpoint, request_preview, attempt_count, retry_error_codes) def _official_full_snapshot_metadata(endpoint: str | None, manifest: dict[str, Any]) -> dict[str, Any]: @@ -2287,6 +2315,11 @@ def _official_snapshot_budget_exhausted_bundle(reason: str) -> dict[str, Any]: def _payload_status(payload: dict[str, Any]) -> str: if not isinstance(payload, dict): return "invalid" + if "Status" not in payload and isinstance(payload.get("events"), list): + return "ok" + failure = response_failure(payload) + if failure: + return failure metadata = payload.get("source_metadata") if isinstance(payload.get("source_metadata"), dict) else {} if metadata.get("degraded_reason") == "free_tier_rate_limited": return "rate_limited" @@ -2300,7 +2333,11 @@ def _payload_status(payload: dict[str, Any]) -> str: def _aggregate_section_status(statuses: list[str]) -> str: if statuses and all(status == "ok" for status in statuses): return "ok" - if any(status == "rate_limited" for status in statuses): + if INPUT_ECHO_MISMATCH in statuses: + return INPUT_ECHO_MISMATCH + if KEY_MISSING in statuses: + return KEY_MISSING + if "rate_limited" in statuses: return "rate_limited" return "partial" @@ -2330,7 +2367,7 @@ def _sign_position(value: Any) -> dict[str, Any] | None: def _extract_all_planet_data(payload: dict[str, Any]) -> dict[str, Any]: - if not isinstance(payload, dict): + if not isinstance(payload, dict) or payload.get("Status") != "Pass": return {} body = payload.get("Payload") if isinstance(payload.get("Payload"), dict) else {} data = body.get("AllPlanetData") if isinstance(body.get("AllPlanetData"), dict) else {} @@ -2338,7 +2375,7 @@ def _extract_all_planet_data(payload: dict[str, Any]) -> dict[str, Any]: def _extract_all_house_data(payload: dict[str, Any]) -> dict[str, Any]: - if not isinstance(payload, dict): + if not isinstance(payload, dict) or payload.get("Status") != "Pass": return {} body = payload.get("Payload") if isinstance(payload.get("Payload"), dict) else {} data = body.get("AllHouseData") if isinstance(body.get("AllHouseData"), dict) else {} @@ -2455,10 +2492,7 @@ def _post_official_snapshot_section(endpoint: str, request_item: dict[str, Any]) fanout_parameter = request_item.get("fanout_parameter") fanout_value = request_item.get("fanout_value") if fanout_parameter and fanout_value is not None: - if fanout_parameter == "planetName": - body[fanout_parameter] = {"Name": str(fanout_value)} - else: - body[fanout_parameter] = str(fanout_value) + body[fanout_parameter] = str(fanout_value) section_preview = { "operation": "official_full_snapshot", "section": request_item["section"], @@ -2490,6 +2524,8 @@ def _normalize_official_full_snapshot_success( section_statuses.get(section) == "ok" for section in fast_primary_present ) status = "ok" if ok_count == len(primary_sections) else "partial" + if not ok_count: + status = INPUT_ECHO_MISMATCH if INPUT_ECHO_MISMATCH in section_statuses.values() else "blocked" if fast_primary_ok and len(fast_primary_present) >= 4: status = "ok" rate_limited_sections = [ @@ -2534,6 +2570,9 @@ def _normalize_official_full_snapshot_success( } if rate_limited_sections: metadata["production_hint"] = "configure_vedastro_api_key_or_self_host_official_api" + chart_sections_verified = manifest["chart_input_supported"] and all( + section_statuses.get(section) == "ok" for section in ("chart_core", "house_core") + ) result = { "backend": "vedastro_service_adapter_candidate", "available": ok_count > 0, @@ -2547,8 +2586,8 @@ def _normalize_official_full_snapshot_success( "section_statuses": section_statuses, "request_manifest": manifest, "response_hash": metadata["response_hash"], - }, - "official_chart": _build_official_chart_from_snapshot(sections), + } if ok_count else {}, + "official_chart": _build_official_chart_from_snapshot(sections) if chart_sections_verified else {}, "official_full_capability_catalog": official_full_capability_catalog or {}, "section_statuses": section_statuses, "request_manifest": manifest, @@ -2579,6 +2618,26 @@ def _run_official_full_snapshot_case(case: dict[str, Any], case_id: str = "user_ "themes": case.get("themes") or case.get("theme"), } manifest = _official_full_snapshot_manifest(user_case, case_id) + endpoint = os.environ.get("VEDASTRO_API_ENDPOINT", "").strip() + network_enabled = os.environ.get(ALLOW_NETWORK_ENV, "").strip().lower() in {"1", "true", "yes"} + blocked = None + if endpoint and not network_enabled: + blocked = "network_execution_disabled" + elif network_enabled and _is_official_public_endpoint(endpoint) and not api_key(): + blocked = KEY_MISSING + if blocked: + return { + "backend": "vedastro_service_adapter_candidate", + "available": False, + "status": blocked, + "reason": blocked, + "operation": "official_full_snapshot", + "primary_source": "vedastro_official", + "snapshot_sections": {}, + "request_manifest": manifest, + "user_visibility": "backend_raw_evidence_not_direct_user_report", + "source_metadata": _official_full_snapshot_metadata(endpoint, manifest), + } budget_started_at = time.monotonic() official_full_capability_catalog: dict[str, Any] = {} elapsed_seconds = time.monotonic() - budget_started_at @@ -2621,7 +2680,7 @@ def _run_official_full_snapshot_case(case: dict[str, Any], case_id: str = "user_ } bridge_sections = ( official_python_bundle.get("snapshot_sections") - if isinstance(official_python_bundle.get("snapshot_sections"), dict) + if official_python_bundle.get("available") and isinstance(official_python_bundle.get("snapshot_sections"), dict) else {} ) bridge_section_statuses = ( @@ -2629,8 +2688,6 @@ def _run_official_full_snapshot_case(case: dict[str, Any], case_id: str = "user_ if isinstance(official_python_bundle.get("section_statuses"), dict) else {} ) - endpoint = os.environ.get("VEDASTRO_API_ENDPOINT", "").strip() - network_enabled = os.environ.get(ALLOW_NETWORK_ENV, "").strip().lower() in {"1", "true", "yes"} fanout_enabled = os.environ.get("VEDASTRO_FULL_SNAPSHOT_FANOUT_ENABLED", "1").strip().lower() in {"1", "true", "yes", "on"} if bridge_sections and not fanout_enabled: return _normalize_official_full_snapshot_success( @@ -2725,53 +2782,6 @@ def _run_official_full_snapshot_case(case: dict[str, Any], case_id: str = "user_ result["source_metadata"]["python_bridge"] = result["source_metadata"]["official_python_bundle"] return result - if not network_enabled: - if bridge_sections: - return _normalize_official_full_snapshot_success( - endpoint, - manifest, - bridge_sections, - bridge_section_statuses, - 1, - [], - official_python_bundle=official_python_bundle, - official_full_capability_catalog=official_full_capability_catalog, - ) - result = { - "backend": "vedastro_service_adapter_candidate", - "available": False, - "status": "network_execution_disabled", - "operation": "official_full_snapshot", - "primary_source": "vedastro_official", - "reason": f"{ALLOW_NETWORK_ENV} is not enabled; official full snapshot stops after building request manifest.", - "snapshot_sections": {}, - "official_full_capability_catalog": official_full_capability_catalog, - "request_manifest": manifest, - "user_visibility": "backend_raw_evidence_not_direct_user_report", - "source_metadata": _official_full_snapshot_metadata(endpoint, manifest), - } - result["source_metadata"]["official_full_capability_catalog"] = { - "source": official_full_capability_catalog.get("source"), - "status": official_full_capability_catalog.get("status"), - "bundle": official_full_capability_catalog.get("bundle"), - "summary": official_full_capability_catalog.get("summary"), - "coverage": official_full_capability_catalog.get("coverage"), - "domain_routing": official_full_capability_catalog.get("domain_routing") or {}, - "dynamic_selection": official_full_capability_catalog.get("dynamic_selection") or {}, - } - result["source_metadata"]["official_python_bundle"] = { - "source": official_python_bundle.get("source"), - "status": official_python_bundle.get("status"), - "coverage": official_python_bundle.get("coverage"), - "bundle": official_python_bundle.get("bundle"), - "summary": official_python_bundle.get("summary"), - "python_bin": official_python_bundle.get("python_bin"), - "module_name": official_python_bundle.get("module_name"), - } - result["source_metadata"]["official_python_path"] = str(official_python_bundle.get("source") or "vedastro_python_bridge") - result["source_metadata"]["python_bridge"] = result["source_metadata"]["official_python_bundle"] - return result - sections: dict[str, Any] = dict(bridge_sections) section_statuses: dict[str, str] = dict(bridge_section_statuses) attempt_count = 0 @@ -2859,6 +2869,16 @@ def run_official_full_snapshot_for_case( result = _run_official_full_snapshot_case(case, case_id=case_id) if not isinstance(result, dict): return result + statuses = result.get("section_statuses") or {} + uncached_statuses = (INPUT_ECHO_MISMATCH, KEY_MISSING) + if result.get("status") in uncached_statuses or any(status in uncached_statuses for status in statuses.values()): + return result + if any( + status in uncached_statuses + for name in ("chart_core_fanout", "house_core_fanout") + for status in (statuses.get(name) or {}).values() + ): + return result return _store_official_full_snapshot_semantic_cache(case, case_id, result) @@ -3056,6 +3076,18 @@ def _run_range_scan_case(case: dict[str, Any], domain: str, start_date: str, end "request_preview": sample_preview, "source_metadata": _source_metadata(endpoint), } + status = _payload_status(payload) + if status != "ok": + return { + "backend": "vedastro_service_adapter_candidate", + "available": False, + "status": status, + "reason": status, + "operation": "range_scan", + "domain": domain, + "request_preview": sample_preview, + "source_metadata": _source_metadata(endpoint), + } reports.append(_normalize_range_scan_success(payload, endpoint, sample_preview, attempt_count, retry_error_codes)) return _merge_range_scan_reports(reports, endpoint, request_preview) @@ -3191,6 +3223,11 @@ def run_external_technique(case_id: str, domain: str, method: str, api_endpoint: "source_metadata": _source_metadata(endpoint), } + if not isinstance(payload, dict): + return {"status": "invalid_response", "available": False} + failure = response_failure(payload) + if failure: + return {"status": failure, "available": False, "reason": failure} return _normalize_external_technique_success(payload, endpoint, request_preview) diff --git a/scripts/vedastro_snapshot_cache.py b/scripts/vedastro_snapshot_cache.py index 1a7eaa976..89742c2fb 100644 --- a/scripts/vedastro_snapshot_cache.py +++ b/scripts/vedastro_snapshot_cache.py @@ -21,7 +21,7 @@ from pathlib import Path from typing import Any ROOT = Path(__file__).resolve().parents[1] -CACHE_SCHEMA = "vedastro_snapshot_cache.v1" +CACHE_SCHEMA = "vedastro_snapshot_cache.v2" MAX_STALE_DAYS = 7 _SHA256_NAME = re.compile(r"^[0-9a-f]{64}\.json$") _IDENTITY_KEYS = { diff --git a/tests/test_explicit_calculation_modes_bug1828.py b/tests/test_explicit_calculation_modes_bug1828.py index 5dd010842..e767d29c5 100644 --- a/tests/test_explicit_calculation_modes_bug1828.py +++ b/tests/test_explicit_calculation_modes_bug1828.py @@ -57,7 +57,7 @@ def test_unknown_position_mode_is_a_bad_request() -> None: def test_cache_payload_records_both_modes_and_bumps_the_schema() -> None: payload = server._build_api_chart_cache_payload(dict(BIRTH)) - assert payload['cache_schema_version'] == 9 + assert payload['cache_schema_version'] == 10 assert payload['calculation']['node_mode'] == 'mean' assert payload['calculation']['position_mode'] == 'apparent' diff --git a/tests/test_vedastro_gateway.py b/tests/test_vedastro_gateway.py index 8b2f10f0c..b27390941 100644 --- a/tests/test_vedastro_gateway.py +++ b/tests/test_vedastro_gateway.py @@ -10,6 +10,7 @@ def test_gateway_status_defaults_to_official_first_cn_safe(monkeypatch): monkeypatch.setenv("JYOTISH_SKIP_LOCAL_ENV", "1") monkeypatch.delenv("VEDASTRO_SELF_HOST_ENDPOINT", raising=False) monkeypatch.delenv("VEDASTRO_API_ENDPOINT", raising=False) + monkeypatch.setenv("VEDASTRO_API_KEY", "test-only-credential") monkeypatch.delenv("VEDASTRO_CACHE_TTL_SECONDS", raising=False) monkeypatch.delenv("VEDASTRO_GATEWAY_QUEUE_ENABLED", raising=False) monkeypatch.delenv("VEDASTRO_QUEUE_ENABLED", raising=False) @@ -56,13 +57,14 @@ def test_gateway_status_exposes_official_readiness_gate(monkeypatch): monkeypatch.setenv("JYOTISH_SKIP_LOCAL_ENV", "1") monkeypatch.setenv("VEDASTRO_ENABLE_NETWORK", "1") monkeypatch.setenv("VEDASTRO_TIMEOUT_SECONDS", "20") + monkeypatch.delenv("VEDASTRO_API_KEY", raising=False) monkeypatch.setenv("VEDASTRO_FREE_TIER_QUEUE", "1") status = vedastro_gateway.gateway_status() assert status["official_configured"] is True - assert status["official_readiness"]["official_ready"] is True - assert status["official_readiness"]["free_tier_possible_with_cache_queue"] is True + assert status["official_readiness"]["official_ready"] is False + assert status["official_readiness"]["free_tier_possible_with_cache_queue"] is False def test_gateway_status_never_exposes_vedastro_secret(monkeypatch): diff --git a/tests/test_vedastro_official_full_snapshot.py b/tests/test_vedastro_official_full_snapshot.py index 921579b8d..44cd2c5d1 100644 --- a/tests/test_vedastro_official_full_snapshot.py +++ b/tests/test_vedastro_official_full_snapshot.py @@ -37,7 +37,7 @@ def test_schema_declares_official_full_snapshot_contract() -> None: report = _run_adapter("--print-schema") assert "official_full_snapshot_request_contract" in report - assert "BirthTime" in report["official_full_snapshot_request_contract"]["common_body_fields"] + assert report["official_full_snapshot_request_contract"]["common_body_fields"] == ["time", "Ayanamsa"] assert report["official_full_snapshot_request_contract"]["primary_source"] == "vedastro_official" assert "official_full_snapshot_response_contract" in report assert "snapshot_sections" in report["official_full_snapshot_response_contract"] @@ -132,7 +132,7 @@ def test_official_full_snapshot_dasha_request_uses_official_range_contract(monke assert body["endTime"]["StdTime"] == "23:59 31/12/2026 +08:00" assert body["levels"] == 3 assert body["precisionHours"] == 100 - assert body["Ayanamsa"] == "lahiri" + assert body["Ayanamsa"] == "LAHIRI" assert "StartTime" not in body assert "EndTime" not in body assert "time" not in body @@ -240,46 +240,24 @@ def test_official_full_snapshot_marks_semantic_rate_limit_payloads(monkeypatch) assert result["source_metadata"]["production_hint"] == "configure_vedastro_api_key_or_self_host_official_api" -def test_post_json_with_retry_waits_for_free_tier_slot(monkeypatch) -> None: +def test_post_json_with_retry_blocks_before_using_free_tier_without_key(monkeypatch) -> None: from scripts import vedastro_service_adapter as adapter - monotonic_values = iter([0.0, 0.1, 0.2, 0.9, 1.2, 1.3]) - sleep_calls: list[float] = [] - - def fake_monotonic() -> float: - return next(monotonic_values) - - def fake_sleep(seconds: float) -> None: - sleep_calls.append(seconds) - - def fake_post(endpoint: str, request_preview: dict[str, object]) -> dict[str, object]: - return {"Status": "Pass", "Payload": {"echo": request_preview}} + def unexpected(*args, **kwargs): + raise AssertionError("Missing credentials must short-circuit cache, rate queue and network") monkeypatch.delenv("VEDASTRO_API_KEY", raising=False) - monkeypatch.setenv("VEDASTRO_FREE_TIER_MAX_REQUESTS", "1") - monkeypatch.setenv("VEDASTRO_FREE_TIER_WINDOW_SECONDS", "1") - monkeypatch.setenv("VEDASTRO_CACHE_TTL_SECONDS", "0") - monkeypatch.setattr(adapter.time, "monotonic", fake_monotonic) - monkeypatch.setattr(adapter.time, "sleep", fake_sleep) - monkeypatch.setattr(adapter, "_post_json", fake_post) - monkeypatch.setattr(adapter, "_FREE_TIER_REQUEST_TIMESTAMPS", []) - - first, first_attempts, first_retries = adapter._post_json_with_retry( + monkeypatch.setattr(adapter, "_post_json", unexpected) + monkeypatch.setattr(adapter, "_acquire_free_tier_slot", unexpected) + monkeypatch.setattr(adapter, "_load_cached_payload", unexpected) + payload, attempts, retries = adapter._post_json_with_retry( "https://api.vedastro.org/api", - {"operation": "range_scan", "official_request_profile": {"endpoint_path": "/Calculate/SearchEvents", "body": {"foo": "bar"}}}, - ) - second, second_attempts, second_retries = adapter._post_json_with_retry( - "https://api.vedastro.org/api", - {"operation": "range_scan", "official_request_profile": {"endpoint_path": "/Calculate/SearchEvents", "body": {"foo": "baz"}}}, + {"operation": "range_scan", "official_request_profile": {"endpoint_path": "/Calculate/SearchEvents"}}, ) - assert first_attempts == 1 - assert second_attempts == 1 - assert first_retries == [] - assert second_retries == [] - assert sleep_calls and sleep_calls[0] > 0 - assert first["source_metadata"]["free_tier_rate_limit"]["waited_seconds"] == 0 - assert second["source_metadata"]["free_tier_rate_limit"]["waited_seconds"] > 0 + assert payload == {"Status": "Fail", "Payload": {"reason": "vedastro_api_key_missing"}} + assert attempts == 0 + assert retries == [] def test_orchestrator_attaches_official_full_snapshot_before_range_scan(monkeypatch) -> None: @@ -617,6 +595,7 @@ def test_official_full_snapshot_can_use_python_bridge_bundle_without_rest_endpoi "snapshot_sections": { "chart_core": { "Sun": { + "Status": "Pass", "Payload": { "AllPlanetData": { "PlanetRasiD1Sign": {"Name": "Aries", "DegreesIn": {"TotalDegrees": "3.5"}}, @@ -630,6 +609,7 @@ def test_official_full_snapshot_can_use_python_bridge_bundle_without_rest_endpoi }, "house_core": { "House1": { + "Status": "Pass", "Payload": { "AllHouseData": { "HouseBhavaChalitSign": {"Name": "Leo", "DegreesIn": {"TotalDegrees": "13.0"}}, @@ -785,6 +765,7 @@ def test_official_full_snapshot_prefers_official_capability_runner_bundle(monkey "snapshot_sections": { "chart_core": { "Sun": { + "Status": "Pass", "Payload": { "AllPlanetData": { "PlanetRasiD1Sign": {"Name": "Aries", "DegreesIn": {"TotalDegrees": "3.5"}}, @@ -795,6 +776,7 @@ def test_official_full_snapshot_prefers_official_capability_runner_bundle(monkey }, "house_core": { "House1": { + "Status": "Pass", "Payload": { "AllHouseData": { "HouseBhavaChalitSign": {"Name": "Leo", "DegreesIn": {"TotalDegrees": "13.0"}}, @@ -879,6 +861,7 @@ def test_official_full_snapshot_attaches_full_capability_catalog_summary(monkeyp "snapshot_sections": { "chart_core": { "Sun": { + "Status": "Pass", "Payload": { "AllPlanetData": { "PlanetRasiD1Sign": {"Name": "Aries", "DegreesIn": {"TotalDegrees": "3.5"}}, @@ -888,6 +871,7 @@ def test_official_full_snapshot_attaches_full_capability_catalog_summary(monkeyp }, "house_core": { "House1": { + "Status": "Pass", "Payload": { "AllHouseData": { "HouseBhavaChalitSign": {"Name": "Leo", "DegreesIn": {"TotalDegrees": "13.0"}}, @@ -1084,6 +1068,7 @@ def test_official_full_snapshot_skips_rest_sections_already_filled_by_python_bun "snapshot_sections": { "chart_core": { "Sun": { + "Status": "Pass", "Payload": { "AllPlanetData": { "PlanetRasiD1Sign": {"Name": "Aries", "DegreesIn": {"TotalDegrees": "3.5"}}, @@ -1094,6 +1079,7 @@ def test_official_full_snapshot_skips_rest_sections_already_filled_by_python_bun }, "house_core": { "House1": { + "Status": "Pass", "Payload": { "AllHouseData": { "HouseBhavaChalitSign": {"Name": "Leo", "DegreesIn": {"TotalDegrees": "13.0"}} diff --git a/tests/test_vedastro_range_scan_replay.py b/tests/test_vedastro_range_scan_replay.py index ad616c2d4..e25500747 100644 --- a/tests/test_vedastro_range_scan_replay.py +++ b/tests/test_vedastro_range_scan_replay.py @@ -113,7 +113,7 @@ def test_run_range_scan_case_refreshes_live_sampling_request_profile_for_each_sa def fake_post_json_with_retry(endpoint: str, request_preview: dict[str, object]): live_profile = request_preview.get("live_sampling_request_profile") or {} body = live_profile.get("body") if isinstance(live_profile, dict) else {} - at_time = body.get("AtTime") if isinstance(body, dict) else {} + at_time = body.get("atTime") if isinstance(body, dict) else {} std_time = at_time.get("StdTime") if isinstance(at_time, dict) else None captured_at_times.append(std_time) return {"Status": "Pass", "Payload": {"SearchEvents": []}}, 1, [] @@ -148,6 +148,7 @@ def test_run_range_scan_case_refreshes_live_sampling_request_profile_for_each_sa def test_run_range_scan_case_reuses_request_cache_across_case_ids(monkeypatch, tmp_path) -> None: + monkeypatch.setenv("VEDASTRO_API_KEY", "test-only-credential") case = vedastro_service_adapter.PARITY_CASES["beijing_first_use_demo"] calls = {"count": 0} @@ -155,8 +156,8 @@ def test_run_range_scan_case_reuses_request_cache_across_case_ids(monkeypatch, t calls["count"] += 1 live_profile = request_preview.get("live_sampling_request_profile") or {} body = live_profile.get("body") if isinstance(live_profile, dict) else {} - birth_time = body.get("BirthTime") if isinstance(body, dict) else {} - at_time = body.get("AtTime") if isinstance(body, dict) else {} + birth_time = body.get("birthTime") if isinstance(body, dict) else {} + at_time = body.get("atTime") if isinstance(body, dict) else {} birth_location = birth_time.get("Location") if isinstance(birth_time, dict) else {} at_location = at_time.get("Location") if isinstance(at_time, dict) else {} assert birth_location.get("Name") == "UserLocation" diff --git a/tests/test_vedastro_report_deadline_20261102.py b/tests/test_vedastro_report_deadline_20261102.py index 3e4febb9a..3f87c3113 100644 --- a/tests/test_vedastro_report_deadline_20261102.py +++ b/tests/test_vedastro_report_deadline_20261102.py @@ -256,6 +256,7 @@ READ_ERRORS = [ @pytest.fixture def stub_network(monkeypatch): monkeypatch.setenv("VEDASTRO_API_ENDPOINT", "https://oracle.stub.invalid/api") + monkeypatch.setenv("VEDASTRO_API_KEY", "test-only-credential") monkeypatch.setenv("VEDASTRO_ENABLE_NETWORK", "1") monkeypatch.setenv("VEDASTRO_CACHE_TTL_SECONDS", "0") monkeypatch.setenv("VEDASTRO_RETRY_BACKOFF_SECONDS", "0") @@ -336,7 +337,8 @@ def test_api_chart_overview_attach_fails_soft_on_any_error(monkeypatch): assert overview["error_type"] == "IncompleteRead" -def test_the_rest_health_probe_blocks_on_a_cut_body(): +def test_the_rest_health_probe_blocks_on_a_cut_body(monkeypatch): + monkeypatch.setenv("VEDASTRO_API_KEY", "test-only-credential") def opener(req, timeout=None): return _CutResponse(http.client.IncompleteRead(b"{", 9)) diff --git a/tests/test_vedastro_request_verification_2171.py b/tests/test_vedastro_request_verification_2171.py new file mode 100644 index 000000000..56ed75c1d --- /dev/null +++ b/tests/test_vedastro_request_verification_2171.py @@ -0,0 +1,193 @@ +from __future__ import annotations + +import json +from copy import deepcopy +from io import BytesIO +from pathlib import Path +from types import SimpleNamespace + +import pytest +import requests + +from scripts import vedastro_python_bridge as sdk +from scripts import vedastro_rest_bridge as rest +from scripts import vedastro_service_adapter as adapter +from scripts.vedastro_priority import apply_vedastro_source_priority +from scripts.vedastro_response_contract import verified_response +from tests.vedastro_http_fixture import pass_response + +ENDPOINT = "https://api.vedastro.org/api" +TEST_KEY = "test-only-credential" +ROOT = Path(__file__).resolve().parents[1] + + +def _recorded_sun(): + path = ROOT / "references/oracle/artifacts/vedastro_official_parity_raw_keyed_2026_07_23.json" + return json.loads(path.read_text(encoding="utf-8"))["raw_responses"]["Sun"] + + +def test_accepts_the_recorded_provider_envelope_without_persisting_input(): + response = _recorded_sun() + body = { + "planetName": "Sun", + "time": next(row["Value"] for row in response["Input"]["Parameters"] if row["Name"] == "time"), + "Ayanamsa": "LAHIRI", + } + + verified = verified_response("AllPlanetData", body, response, TEST_KEY) + + assert verified == {"Status": "Pass", "Payload": response["Payload"]} + + +@pytest.mark.parametrize("mismatch", ["time", "timezone", "latitude", "longitude", "ayanamsa", "method", "planet", "missing"]) +def test_rejects_pass_with_wrong_or_missing_input(mismatch): + response = _recorded_sun() + time = next(row["Value"] for row in response["Input"]["Parameters"] if row["Name"] == "time") + body = {"planetName": "Sun", "time": deepcopy(time), "Ayanamsa": "LAHIRI"} + + if mismatch == "time": + body["time"]["StdTime"] = body["time"]["StdTime"].replace("12:00", "12:01") + elif mismatch == "timezone": + body["time"]["StdTime"] = body["time"]["StdTime"].replace("12:00", "11:00").replace("+08:00", "+07:00") + elif mismatch in {"latitude", "longitude"}: + body["time"]["Location"][mismatch.title()] += 0.01 + elif mismatch == "ayanamsa": + body["Ayanamsa"] = "RAMAN" + elif mismatch == "method": + response["Input"]["CalculatorName"] = "AllHouseData" + elif mismatch == "planet": + body["planetName"] = "Moon" + else: + del response["Input"] + + assert verified_response("AllPlanetData", body, response, TEST_KEY) == { + "Status": "Fail", + "Payload": {"reason": "input_echo_mismatch"}, + } + + +@pytest.fixture +def case(): + return { + "year": 1990, "month": 1, "day": 1, "hour": 12, "minute": 0, + "lat": 39.9042, "lon": 116.4074, "tz": "+08:00", "ayanamsa_policy": "lahiri", + "reference_date": "2026-11-22", + } + + +def _unexpected(*_args, **_kwargs): + pytest.fail("The missing-key path must stop before cache, SDK import and HTTP") + + +def test_missing_key_blocks_all_official_transports(monkeypatch, tmp_path, case): + monkeypatch.delenv("VEDASTRO_API_KEY", raising=False) + monkeypatch.setenv("VEDASTRO_API_ENDPOINT", ENDPOINT) + monkeypatch.setenv("VEDASTRO_ENABLE_NETWORK", "1") + monkeypatch.setenv("VEDASTRO_OFFICIAL_FULL_SNAPSHOT_CACHE_DIR", str(tmp_path)) + monkeypatch.setattr(adapter.request, "urlopen", _unexpected) + monkeypatch.setattr(adapter, "_try_official_capability_runner_snapshot_bundle", _unexpected) + monkeypatch.setattr(sdk, "_package_available", _unexpected) + + assert rest.probe_calculate_health(opener=_unexpected)["reason"] == "vedastro_api_key_missing" + assert sdk.call_method("AllPlanetStrength", {})["status"] == "vedastro_api_key_missing" + assert adapter.run_official_full_snapshot_for_case(case)["status"] == "vedastro_api_key_missing" + scan = adapter.run_range_scan_for_case(case, "career", "2026-11-22", "2026-11-22") + assert scan["status"] == "vedastro_api_key_missing" + assert not list(tmp_path.iterdir()) + + +def test_network_disabled_keeps_the_configured_snapshot_offline(monkeypatch, case): + monkeypatch.setenv("VEDASTRO_API_KEY", TEST_KEY) + monkeypatch.setenv("VEDASTRO_API_ENDPOINT", ENDPOINT) + monkeypatch.setenv("VEDASTRO_ENABLE_NETWORK", "0") + monkeypatch.setattr(adapter, "_try_official_capability_runner_snapshot_bundle", _unexpected) + monkeypatch.setattr(adapter, "_try_official_python_bridge_snapshot_bundle", _unexpected) + monkeypatch.setattr(adapter, "_try_official_full_capability_catalog_bundle", _unexpected) + monkeypatch.setattr(adapter.request, "urlopen", _unexpected) + + snapshot = adapter._run_official_full_snapshot_case(case) + assert snapshot["status"] == "network_execution_disabled" + assert snapshot["request_manifest"]["requests"] + + +def test_chart_and_range_requests_reject_example_chart_before_the_cache(monkeypatch, tmp_path, case): + calls = [] + + def provider(req, **_kwargs): + assert req.get_header("X-api-key") == TEST_KEY + body = json.loads(req.data) + assert body["Ayanamsa"] == "LAHIRI" + assert not {"NodeMode", "CalculationPreferences", "APIKey"}.intersection(body) + method = req.full_url.rsplit("/", 1)[-1] + calls.append((method, body)) + if method == "AllPlanetData": + assert isinstance(body["planetName"], str) + if method == "AllHouseData": + assert isinstance(body["houseName"], str) + if method == "SearchEvents": + assert set(body) == {"Ayanamsa", "birthTime", "eventTagList", "atTime"} + wrong = deepcopy(body) + natal = wrong.get("birthTime") or wrong["time"] + natal["StdTime"] = "14:30 25/10/1992 +05:30" # Provider example. + return BytesIO(json.dumps(pass_response(method, wrong, {method: {"mock": True}})).encode()) + + monkeypatch.setenv("VEDASTRO_API_ENDPOINT", ENDPOINT) + monkeypatch.setenv("VEDASTRO_ENABLE_NETWORK", "1") + monkeypatch.setenv("VEDASTRO_API_KEY", TEST_KEY) + monkeypatch.setenv("VEDASTRO_CACHE_DIR", str(tmp_path / "requests")) + monkeypatch.setenv("VEDASTRO_OFFICIAL_FULL_SNAPSHOT_CACHE_DIR", str(tmp_path / "snapshots")) + monkeypatch.setattr(adapter.request, "urlopen", provider) + monkeypatch.setattr(adapter, "OFFICIAL_SNAPSHOT_PLANETS", ["Sun"]) + monkeypatch.setattr(adapter, "OFFICIAL_SNAPSHOT_HOUSES", ["House1"]) + monkeypatch.setattr(adapter, "_try_official_capability_runner_snapshot_bundle", lambda _: {}) + monkeypatch.setattr(adapter, "_try_official_python_bridge_snapshot_bundle", lambda _: {}) + monkeypatch.setattr(adapter, "_try_official_full_capability_catalog_bundle", lambda _: {}) + + snapshot = adapter.run_official_full_snapshot_for_case(case) + assert snapshot["available"] is False + assert snapshot["status"] == "input_echo_mismatch" + assert snapshot["raw_response"] == {} + assert snapshot["section_statuses"]["chart_core_fanout"] == {"Sun": "input_echo_mismatch"} + assert snapshot["section_statuses"]["house_core_fanout"] == {"House1": "input_echo_mismatch"} + assert snapshot["official_chart"] == {} + local = {"chart": {"planets": {"Sun": {"sign": "Pisces"}}}} + assert apply_vedastro_source_priority(local, official_snapshot=snapshot)["chart"]["primary_source"] == "local_engine" + scan = adapter.run_range_scan_for_case(case, "career", "2026-11-22", "2026-11-22") + assert scan["status"] == "input_echo_mismatch" + assert not list(tmp_path.rglob("*.json")) + assert {method for method, _ in calls} == {"SearchEvents", "DasaAtRange", "AllPlanetData", "AllHouseData"} + + +def test_sdk_auth_and_echo_verification_are_per_call(monkeypatch): + received = [] + time = {"StdTime": "12:00 01/01/1990 +08:00", "Location": {"Latitude": 39.9042, "Longitude": 116.4074}} + + class Calculate: + base_url = f"{ENDPOINT}/Calculate" + + @classmethod + def SetAPIKey(cls, value): + cls.api_key = value + + @classmethod + def AllPlanetStrength(cls): + return cls._make_request("AllPlanetStrength", {"time": time}) + + def provider(url, *, json, **kwargs): + assert url.endswith("/Calculate/AllPlanetStrength") + assert kwargs["allow_redirects"] is False + received.append(json) + payload = pass_response("AllPlanetStrength", json, {"AllPlanetStrength": {TEST_KEY: "echo"}}) + return SimpleNamespace(raise_for_status=lambda: None, json=lambda: payload) + + monkeypatch.setenv("VEDASTRO_API_KEY", TEST_KEY) + monkeypatch.setattr(sdk, "_import_runtime_module", lambda: ("vedastro", SimpleNamespace(Calculate=Calculate))) + monkeypatch.setattr(requests, "post", provider) + good = sdk._call_in_current_python("AllPlanetStrength", {"ayanamsa": "lahiri"}) + wrong = sdk._call_in_current_python("AllPlanetStrength", {"ayanamsa": "raman"}) + + assert good["status"] == "ok" and good["result"] == {"[redacted]": "echo"} + assert wrong["status"] == "input_echo_mismatch" and "result" not in wrong + assert [call["Ayanamsa"] for call in received] == ["LAHIRI", "RAMAN"] + assert all(call["APIKey"] == TEST_KEY for call in received) + assert not hasattr(Calculate, "api_key") diff --git a/tests/test_vedastro_rest_bridge.py b/tests/test_vedastro_rest_bridge.py index af8071228..9be08ea34 100644 --- a/tests/test_vedastro_rest_bridge.py +++ b/tests/test_vedastro_rest_bridge.py @@ -1,12 +1,11 @@ import argparse import http.client +import json import urllib.error from io import BytesIO import pytest -from tests.test_consultation_contract_golden import FORBIDDEN_PRIVACY_MARKERS - from scripts.vedastro_rest_bridge import ( SMOKE_DEFAULT, _date_to_vedastro_std, @@ -18,6 +17,8 @@ from scripts.vedastro_rest_bridge import ( probe_calculate_health, reset_rate_limiter, ) +from tests.test_consultation_contract_golden import FORBIDDEN_PRIVACY_MARKERS +from tests.vedastro_http_fixture import pass_response def _args(**overrides): @@ -39,24 +40,24 @@ def test_default_horoscope_payload_uses_fictional_smoke_without_network(): assert payload == { "Ayanamsa": "LAHIRI", - "BirthTime": { + "birthTime": { "StdTime": "12:00 01/01/1990 +08:00", "Location": {"Name": "Beijing, China", "Longitude": 116.4074, "Latitude": 39.9042}, }, - "SortByWeight": False, + "sortByWeight": False, } - assert "1993" not in payload["BirthTime"]["StdTime"] - assert all(marker not in payload["BirthTime"]["StdTime"] for marker in FORBIDDEN_PRIVACY_MARKERS) + assert "1993" not in payload["birthTime"]["StdTime"] + assert all(marker not in payload["birthTime"]["StdTime"] for marker in FORBIDDEN_PRIVACY_MARKERS) def test_dasa_payload_formats_vedastro_range_times_without_network(): payload = build_dasa_payload(_args()) assert payload["Ayanamsa"] == "LAHIRI" - assert payload["StartTime"]["StdTime"] == "00:00 01/01/2026 +08:00" - assert payload["EndTime"]["StdTime"] == "00:00 31/03/2026 +08:00" - assert payload["Levels"] == 3 - assert payload["PrecisionHours"] == 100 + assert payload["startTime"]["StdTime"] == "00:00 01/01/2026 +08:00" + assert payload["endTime"]["StdTime"] == "00:00 31/03/2026 +08:00" + assert payload["levels"] == 3 + assert payload["precisionHours"] == 100 def test_date_parser_rejects_ambiguous_times(): @@ -81,20 +82,30 @@ class _Handle(BytesIO): return False -def test_recorded_horoscope_status_pass_does_not_hit_network(): +def test_recorded_horoscope_status_pass_does_not_hit_network(monkeypatch): + monkeypatch.setenv("VEDASTRO_API_KEY", "test-only-credential") reset_rate_limiter() recorded = {"Status": "Pass", "Payload": {"source": "recorded_smoke"}} - def fake_opener(_req, timeout=90): - return _Handle(b'{"Status": "Pass", "Payload": {"source": "recorded_smoke"}}') + def fake_opener(req, timeout=90): + assert req.get_header("X-api-key") == "test-only-credential" + body = json.loads(req.data) + assert "test-only-credential" not in str(body) + raw = pass_response("HoroscopePredictions", body, recorded["Payload"]) + return _Handle(json.dumps(raw).encode()) result = call("HoroscopePredictions", build_horoscope_payload(_args()), opener=fake_opener) assert result == recorded -def test_probe_maps_recorded_pass_and_rate_limit_without_network(): +def test_probe_maps_recorded_pass_and_rate_limit_without_network(monkeypatch): + monkeypatch.setenv("VEDASTRO_API_KEY", "test-only-credential") reset_rate_limiter() - health = probe_calculate_health(opener=lambda _req, timeout=8: _Handle(b'{"Status": "Pass"}')) + def passed(req, timeout=8): + raw = pass_response("HoroscopePredictions", json.loads(req.data), []) + return _Handle(json.dumps(raw).encode()) + + health = probe_calculate_health(opener=passed) assert health["status"] == "official_verified" assert health["transport"] == "rest" diff --git a/tests/test_vedastro_runtime_mode_diagnostics.py b/tests/test_vedastro_runtime_mode_diagnostics.py index 7dff6b02a..2736ac0bc 100644 --- a/tests/test_vedastro_runtime_mode_diagnostics.py +++ b/tests/test_vedastro_runtime_mode_diagnostics.py @@ -60,7 +60,7 @@ def test_vedastro_diagnostics_reports_official_mode_when_configured() -> None: assert report["official_closure_plan"]["required_env"]["VEDASTRO_TIMEOUT_SECONDS"] == "20" -def test_vedastro_diagnostics_labels_premium_key_missing_but_free_tier_possible() -> None: +def test_vedastro_diagnostics_blocks_official_mode_without_key() -> None: report = _run_diag({ "VEDASTRO_API_ENDPOINT": "https://api.vedastro.org/api", "VEDASTRO_ENABLE_NETWORK": "1", @@ -68,9 +68,9 @@ def test_vedastro_diagnostics_labels_premium_key_missing_but_free_tier_possible( "VEDASTRO_API_KEY": "", "VEDASTRO_FREE_TIER_QUEUE": "1", }) - assert report["mode"] == "official_extended" - assert report["official_ready"] is True - assert "missing_api_key" not in report["readiness_blockers"] + assert report["mode"] == "fast_local_fallback" + assert report["official_ready"] is False + assert "VEDASTRO_API_KEY" in report["missing"] assert "premium_key_missing" in report["readiness_blockers"] - assert report["free_tier_possible_with_cache_queue"] is True - assert report["official_closure_plan"]["premium_key_policy"] == "API key recommended for stable official full snapshot; free tier may still block or throttle." + assert report["free_tier_possible_with_cache_queue"] is False + assert report["official_closure_plan"]["premium_key_policy"] == "A missing API key blocks official calculation requests." diff --git a/tests/test_vedastro_service_adapter_executor.py b/tests/test_vedastro_service_adapter_executor.py index fd4e869ce..9f2574142 100644 --- a/tests/test_vedastro_service_adapter_executor.py +++ b/tests/test_vedastro_service_adapter_executor.py @@ -5,10 +5,12 @@ import os import subprocess import sys import threading +import time import types -from pathlib import Path from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path +from tests.vedastro_http_fixture import pass_response ROOT = Path(__file__).resolve().parents[1] @@ -133,6 +135,7 @@ def test_vedastro_official_snapshot_stops_when_foreground_budget_is_exhausted(mo monkeypatch.setenv("VEDASTRO_API_ENDPOINT", "https://api.vedastro.org/api") monkeypatch.setenv("VEDASTRO_ENABLE_NETWORK", "1") + monkeypatch.setenv("VEDASTRO_API_KEY", "test-only-credential") monkeypatch.setenv("VEDASTRO_TIMEOUT_SECONDS", "4") monkeypatch.setattr( adapter, @@ -163,7 +166,7 @@ def test_vedastro_official_snapshot_stops_when_foreground_budget_is_exhausted(mo monkeypatch.setattr(adapter, "_try_official_python_bridge_snapshot_bundle", fail_bridge) ticks = iter([100.0, 104.1]) - monkeypatch.setattr(adapter.time, "monotonic", lambda: next(ticks)) + monkeypatch.setattr(adapter, "time", types.SimpleNamespace(monotonic=lambda: next(ticks), time=time.time, strftime=time.strftime, gmtime=time.gmtime)) result = adapter._run_official_full_snapshot_case({ "year": 1990, "month": 4, @@ -188,6 +191,7 @@ def test_vedastro_official_snapshot_skips_bridge_after_runner_consumes_budget(mo monkeypatch.setenv("VEDASTRO_API_ENDPOINT", "https://api.vedastro.org/api") monkeypatch.setenv("VEDASTRO_ENABLE_NETWORK", "1") + monkeypatch.setenv("VEDASTRO_API_KEY", "test-only-credential") monkeypatch.setenv("VEDASTRO_TIMEOUT_SECONDS", "4") monkeypatch.setattr( adapter, @@ -225,7 +229,7 @@ def test_vedastro_official_snapshot_skips_bridge_after_runner_consumes_budget(mo monkeypatch.setattr(adapter, "_try_official_python_bridge_snapshot_bundle", fail_bridge) ticks = iter([100.0, 100.1, 104.2]) - monkeypatch.setattr(adapter.time, "monotonic", lambda: next(ticks)) + monkeypatch.setattr(adapter, "time", types.SimpleNamespace(monotonic=lambda: next(ticks), time=time.time, strftime=time.strftime, gmtime=time.gmtime)) result = adapter._run_official_full_snapshot_case({ "year": 1990, "month": 4, @@ -286,7 +290,7 @@ def test_vedastro_official_snapshot_budget_does_not_mask_mock_rest_endpoint(monk monkeypatch.setattr(adapter, "_try_official_python_bridge_snapshot_bundle", lambda case: {"available": False, "status": "blocked", "snapshot_sections": {}, "section_statuses": {}, "coverage": {"source_mode": "official_python_bridge_bundle", "filled_sections": []}}) monkeypatch.setattr(adapter, "_post_official_snapshot_section", fake_post) ticks = iter([100.0, 100.1, 104.2]) - monkeypatch.setattr(adapter.time, "monotonic", lambda: next(ticks)) + monkeypatch.setattr(adapter, "time", types.SimpleNamespace(monotonic=lambda: next(ticks), time=time.time, strftime=time.strftime, gmtime=time.gmtime)) result = adapter._run_official_full_snapshot_case({ "year": 1990, @@ -459,13 +463,11 @@ def test_vedastro_range_scan_unconfigured_still_returns_official_search_events_p assert report["request_preview"]["official_request_profile"]["endpoint_path"] == "/Calculate/SearchEvents" assert report["request_preview"]["official_request_profile"]["method"] == "POST" assert report["request_preview"]["official_request_profile"]["headers"] == {"Content-Type": "application/json"} - assert report["request_preview"]["official_request_profile"]["body"]["Ayanamsa"] == "lahiri" - assert report["request_preview"]["official_request_profile"]["body"]["EventTagList"] == ["LendingMoney", "BorrowingMoney", "BuyingSelling", "General"] - assert "AtTime" not in report["request_preview"]["official_request_profile"]["body"] - assert report["request_preview"]["official_request_profile"]["body"]["StartTime"]["StdTime"] == "12:00 01/01/2026 +08:00" - assert report["request_preview"]["official_request_profile"]["body"]["EndTime"]["StdTime"] == "12:00 01/01/2031 +08:00" - assert report["request_preview"]["official_request_profile"]["body"]["PrecisionHours"] == 100 - assert report["request_preview"]["live_sampling_request_profile"]["body"]["AtTime"]["StdTime"] == "12:00 01/01/2026 +08:00" + assert report["request_preview"]["official_request_profile"]["body"]["Ayanamsa"] == "LAHIRI" + assert report["request_preview"]["official_request_profile"]["body"]["eventTagList"] == ["LendingMoney", "BorrowingMoney", "BuyingSelling", "General"] + assert report["request_preview"]["official_request_profile"]["body"]["atTime"]["StdTime"] == "12:00 01/01/2026 +08:00" + assert set(report["request_preview"]["official_request_profile"]["body"]) == {"birthTime", "atTime", "eventTagList", "Ayanamsa"} + assert report["request_preview"]["live_sampling_request_profile"]["body"]["atTime"]["StdTime"] == "12:00 01/01/2026 +08:00" def test_vedastro_schema_declares_official_search_events_live_contract() -> None: @@ -483,10 +485,10 @@ def test_vedastro_schema_declares_official_search_events_live_contract() -> None contract = report["official_search_events_profile_contract"] assert contract["route_template"] == "/Calculate/SearchEvents" assert contract["method"] == "POST" - assert contract["optional_auth_header"] == "x-api-key" - assert "BirthTime" in contract["body_fields"] - assert "EventTagList" in contract["body_fields"] - assert "AtTime | StartTime + EndTime + PrecisionHours" in contract["range_mode_fields"] + assert contract["required_auth_header"] == "x-api-key" + assert "birthTime" in contract["body_fields"] + assert "eventTagList" in contract["body_fields"] + assert "atTime" in contract["range_mode_fields"] def test_vedastro_service_adapter_posts_official_search_events_contract() -> None: @@ -497,10 +499,10 @@ def test_vedastro_service_adapter_posts_official_search_events_contract() -> Non assert self.headers.get("x-api-key") == "sk_live_test" length = int(self.headers.get("Content-Length", "0")) payload = json.loads(self.rfile.read(length).decode("utf-8")) - assert payload["Ayanamsa"] == "lahiri" - assert payload["EventTagList"] == ["Marriage", "Personal", "General"] - assert payload["BirthTime"]["StdTime"] == "12:00 01/01/1990 +08:00" - assert payload["AtTime"]["StdTime"] == "12:00 01/01/2026 +08:00" + assert payload["Ayanamsa"] == "LAHIRI" + assert payload["eventTagList"] == ["Marriage", "Personal", "General"] + assert payload["birthTime"]["StdTime"] == "12:00 01/01/1990 +08:00" + assert payload["atTime"]["StdTime"] == "12:00 01/01/2026 +08:00" assert "StartTime" not in payload response = { "Status": "Pass", @@ -514,7 +516,7 @@ def test_vedastro_service_adapter_posts_official_search_events_contract() -> Non } ], } - body = json.dumps(response).encode("utf-8") + body = json.dumps(pass_response("SearchEvents", payload, response["Payload"])).encode("utf-8") self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) @@ -608,6 +610,7 @@ def test_vedastro_service_adapter_can_normalize_mock_http_response() -> None: env = os.environ.copy() env["VEDASTRO_API_ENDPOINT"] = f"http://127.0.0.1:{server.server_port}/vedastro" env["VEDASTRO_ENABLE_NETWORK"] = "1" + env["VEDASTRO_API_KEY"] = "test-only-credential" completed = subprocess.run( [sys.executable, "scripts/vedastro_service_adapter.py", "--case", "beijing_first_use_demo"], cwd=ROOT, @@ -639,10 +642,10 @@ def test_vedastro_service_adapter_can_normalize_mock_range_scan_response() -> No def do_POST(self) -> None: # noqa: N802 length = int(self.headers.get("Content-Length", "0")) payload = json.loads(self.rfile.read(length).decode("utf-8")) - assert payload["Ayanamsa"] == "lahiri" - assert payload["EventTagList"] == ["Marriage", "Personal", "General"] - assert payload["BirthTime"]["StdTime"] == "12:00 01/01/1990 +08:00" - seen_at_times.append(payload["AtTime"]["StdTime"]) + assert payload["Ayanamsa"] == "LAHIRI" + assert payload["eventTagList"] == ["Marriage", "Personal", "General"] + assert payload["birthTime"]["StdTime"] == "12:00 01/01/1990 +08:00" + seen_at_times.append(payload["atTime"]["StdTime"]) response = { "events": [ { @@ -676,6 +679,7 @@ def test_vedastro_service_adapter_can_normalize_mock_range_scan_response() -> No env = os.environ.copy() env["VEDASTRO_API_ENDPOINT"] = f"http://127.0.0.1:{server.server_port}/vedastro" env["VEDASTRO_ENABLE_NETWORK"] = "1" + env["VEDASTRO_API_KEY"] = "test-only-credential" completed = subprocess.run( [ sys.executable, @@ -769,6 +773,7 @@ def test_vedastro_range_scan_records_hashes_and_artifact_path() -> None: env = os.environ.copy() env["VEDASTRO_API_ENDPOINT"] = f"http://127.0.0.1:{server.server_port}/vedastro" env["VEDASTRO_ENABLE_NETWORK"] = "1" + env["VEDASTRO_API_KEY"] = "test-only-credential" # 原值:沿用进程环境,没有 VEDASTRO_WRITE_AUDIT_ARTIFACTS。 # 新值:显式设为 1。 # 原因:审计落盘默认关闭后,这条测试仍要断言文件存在,所以打开开关。这是测试前置,不是放宽断言。 @@ -808,7 +813,7 @@ def test_vedastro_range_scan_records_hashes_and_artifact_path() -> None: assert metadata["vedastro_event_method"] == "SearchEvents" assert metadata["official_endpoint_path"] == "/Calculate/SearchEvents" assert metadata["official_request_profile"]["method"] == "POST" - assert metadata["official_request_profile"]["body"]["EventTagList"] == ["Marriage", "Personal", "General"] + assert metadata["official_request_profile"]["body"]["eventTagList"] == ["Marriage", "Personal", "General"] assert metadata["official_request_profile_hash"] assert metadata["allowlist_domain"] == "marriage" assert metadata["allowlist_event_count"] == 1 @@ -864,6 +869,7 @@ def test_vedastro_range_scan_retries_transient_http_error() -> None: env = os.environ.copy() env["VEDASTRO_API_ENDPOINT"] = f"http://127.0.0.1:{server.server_port}/vedastro" env["VEDASTRO_ENABLE_NETWORK"] = "1" + env["VEDASTRO_API_KEY"] = "test-only-credential" env["VEDASTRO_RETRY_BACKOFF_SECONDS"] = "0" completed = subprocess.run( [ @@ -934,6 +940,7 @@ def test_vedastro_range_scan_reuses_cached_live_response() -> None: env = os.environ.copy() env["VEDASTRO_API_ENDPOINT"] = f"http://127.0.0.1:{server.server_port}/vedastro" env["VEDASTRO_ENABLE_NETWORK"] = "1" + env["VEDASTRO_API_KEY"] = "test-only-credential" env["VEDASTRO_CACHE_TTL_SECONDS"] = "600" env["JYOTISH_SKIP_LOCAL_ENV"] = "1" @@ -1033,6 +1040,7 @@ def test_vedastro_service_adapter_applies_domain_allowlist_to_range_scan_noise() env = os.environ.copy() env["VEDASTRO_API_ENDPOINT"] = f"http://127.0.0.1:{server.server_port}/vedastro" env["VEDASTRO_ENABLE_NETWORK"] = "1" + env["VEDASTRO_API_KEY"] = "test-only-credential" completed = subprocess.run( [ sys.executable, @@ -1068,6 +1076,8 @@ def test_vedastro_service_adapter_applies_domain_allowlist_to_range_scan_noise() def test_vedastro_service_adapter_preserves_match_metadata_for_official_tag_and_alias_hits() -> None: class Handler(BaseHTTPRequestHandler): def do_POST(self) -> None: # noqa: N802 + length = int(self.headers.get("Content-Length", "0")) + payload = json.loads(self.rfile.read(length).decode("utf-8")) response = { "Status": "Pass", "Payload": [ @@ -1089,7 +1099,7 @@ def test_vedastro_service_adapter_preserves_match_metadata_for_official_tag_and_ }, ], } - body = json.dumps(response).encode("utf-8") + body = json.dumps(pass_response("SearchEvents", payload, response["Payload"])).encode("utf-8") self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) @@ -1106,6 +1116,7 @@ def test_vedastro_service_adapter_preserves_match_metadata_for_official_tag_and_ env = os.environ.copy() env["VEDASTRO_API_ENDPOINT"] = f"http://127.0.0.1:{server.server_port}/api" env["VEDASTRO_ENABLE_NETWORK"] = "1" + env["VEDASTRO_API_KEY"] = "test-only-credential" completed = subprocess.run( [ sys.executable, @@ -1160,6 +1171,7 @@ def test_vedastro_service_adapter_classifies_http_error() -> None: env = os.environ.copy() env["VEDASTRO_API_ENDPOINT"] = f"http://127.0.0.1:{server.server_port}/vedastro" env["VEDASTRO_ENABLE_NETWORK"] = "1" + env["VEDASTRO_API_KEY"] = "test-only-credential" completed = subprocess.run( [sys.executable, "scripts/vedastro_service_adapter.py", "--case", "beijing_first_use_demo"], cwd=ROOT, @@ -1199,6 +1211,7 @@ def test_vedastro_service_adapter_classifies_invalid_json_response() -> None: env = os.environ.copy() env["VEDASTRO_API_ENDPOINT"] = f"http://127.0.0.1:{server.server_port}/vedastro" env["VEDASTRO_ENABLE_NETWORK"] = "1" + env["VEDASTRO_API_KEY"] = "test-only-credential" completed = subprocess.run( [sys.executable, "scripts/vedastro_service_adapter.py", "--case", "beijing_first_use_demo"], cwd=ROOT, diff --git a/tests/test_vedastro_user_entrypoint.py b/tests/test_vedastro_user_entrypoint.py index 8f908d23e..773eeec3c 100644 --- a/tests/test_vedastro_user_entrypoint.py +++ b/tests/test_vedastro_user_entrypoint.py @@ -129,7 +129,7 @@ def test_user_entrypoint_runs_catalog_and_strict_workflow_contract() -> None: report = json.loads(completed.stdout) assert report["scope"] == "vedastro_user_entrypoint" - assert report["runtime_mode"]["mode"] == "official_extended" + assert report["runtime_mode"]["mode"] == "fast_local_fallback" assert report["input"]["themes"] == ["career", "health"] assert report["official_capability_catalog"]["summary"]["catalog_method_count"] == 4 assert report["official_capability_catalog"]["summary"]["sample_limit"] == 8 @@ -141,7 +141,7 @@ def test_user_entrypoint_runs_catalog_and_strict_workflow_contract() -> None: # 新值:True # 原因:该字段跟随真实限流。本用例没有 API key、端点是官方地址、配额用默认正数,所以仍然开启。废弃开关不再决定它。 assert report["cache_and_queue"]["free_tier_queue_enabled"] is True - assert report["runtime_mode"]["free_tier_possible_with_cache_queue"] is True + assert report["runtime_mode"]["free_tier_possible_with_cache_queue"] is False assert report["runtime_mode"]["readiness_blockers"] == ["premium_key_missing"] assert report["cache_and_queue"]["free_tier_strategy"]["using_free_tier"] is True # 原值:True(因为设置了 VEDASTRO_FREE_TIER_QUEUE=1) diff --git a/tests/vedastro_http_fixture.py b/tests/vedastro_http_fixture.py new file mode 100644 index 000000000..4e146d105 --- /dev/null +++ b/tests/vedastro_http_fixture.py @@ -0,0 +1,18 @@ +"""HTTP response double using the provider's captured Input envelope shape.""" + + +def pass_response(method, body, payload, *, ayanamsa=1): + return { + "Status": "Pass", + "Input": { + "CalculatorName": method, + "Ayanamsa": ayanamsa, + "Type": "SingleCall", + "Parameters": [ + {"Name": name, "Value": value} + for name, value in body.items() + if name not in {"Ayanamsa", "APIKey"} + ], + }, + "Payload": payload, + }