From f58cd93ee41f3dfb4d0cf05b04c3dbccc4d13a81 Mon Sep 17 00:00:00 2001 From: jesse-ux Date: Mon, 9 Nov 2026 15:17:39 +0800 Subject: [PATCH] =?UTF-8?q?feat(api):=20native=20calculation=20takes=20exp?= =?UTF-8?q?licit=20node/position=20modes=20=E2=80=94=20backend=20half=20(#?= =?UTF-8?q?185,=20BUG-1828)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增模块级 _request_calculation_modes(body):常量从 ondemand_calc.contract 取, 缺省 mean / apparent 并标 product_default_explicit;非法值 400; position_mode=mean 400 且消息含 position_mode_unsupported - 5 处隐式 body.get(..., 'mean') 改为显式口径(缓存键、高严谨 birth payload、 主题报告、_compute_chart_sync 三处);主题报告不再把非法值静默改成 mean - 缓存键加 calculation.position_mode,cache_schema_version 8 → 9(三栏注释) - execute_consultation_workflow 的两条返回路径都带 calculation_profile 未动:declared_window_chart 与其余不在本单范围的入口(保持原隐式默认); domain_calculation_service.py 等冻结文件未改。 Tests: tests/test_explicit_calculation_modes_bug1828.py(11 条);连同 api_server_growth_contract 与 ondemand contract 共 27 条全过。 前端部分(schema / toolInput / 预热 / 回执)下一轮继续。 Co-Authored-By: Grok (agent loop) --- scripts/jyotish_api_server.py | 52 ++++++++++--- ...test_explicit_calculation_modes_bug1828.py | 77 +++++++++++++++++++ 2 files changed, 120 insertions(+), 9 deletions(-) create mode 100644 tests/test_explicit_calculation_modes_bug1828.py diff --git a/scripts/jyotish_api_server.py b/scripts/jyotish_api_server.py index da30183e9..0f68b9610 100644 --- a/scripts/jyotish_api_server.py +++ b/scripts/jyotish_api_server.py @@ -698,6 +698,29 @@ def _request_ayanamsa(*sources) -> str: return DEFAULT_AYANAMSA_NAME +def _request_calculation_modes(body: dict) -> dict: + """本命计算的口径:node_mode 与 position_mode 一律显式,缺省用产品默认值并标记来源(BUG-1828)。 + + 常量只从 ``ondemand_calc.contract`` 取(#173 拍板:mean / apparent),这里不另写一份。 + ``position_mode = mean`` 目前引擎做不到,返回 400 而不是偷偷按 apparent 算。 + """ + contract = _load_local_module('ondemand_calc.contract') + node_modes = tuple(contract.NODE_MODES) + position_modes = tuple(contract.POSITION_MODES) + raw_node = body.get('node_mode', body.get('nodeMode')) if isinstance(body, dict) else None + raw_position = body.get('position_mode', body.get('positionMode')) if isinstance(body, dict) else None + source = 'caller_supplied' if raw_node not in (None, '') and raw_position not in (None, '') else 'product_default_explicit' + node_mode = str(raw_node).strip().lower() if raw_node not in (None, '') else contract.PRODUCT_DEFAULT_NODE_MODE + position_mode = str(raw_position).strip().lower() if raw_position not in (None, '') else contract.PRODUCT_DEFAULT_POSITION_MODE + if node_mode not in node_modes: + raise BadRequest('node_mode must be mean or true') + if position_mode not in position_modes: + raise BadRequest('position_mode must be apparent or mean') + if position_mode not in tuple(contract.SUPPORTED_POSITION_MODES): + raise BadRequest('position_mode_unsupported: this engine can only compute apparent positions') + return {'node_mode': node_mode, 'position_mode': position_mode, 'profile_source': source} + + def _request_node_mode(*sources) -> str: for source in sources: if isinstance(source, dict): @@ -2196,6 +2219,11 @@ def execute_consultation_workflow( from scripts.reference_transparency_contract import build_reference_transparency_contract birth_payload = handler._high_rigor_birth_payload(body) + # BUG-1828:回执里带上实际生效的交点与位置口径(显式传入或产品默认值)。 + calculation_profile = { + **_request_calculation_modes(body), + 'ayanamsa': birth_payload.get('ayanamsa'), + } sensitivity_args = type('BirthTimeSensitivityArgs', (), birth_payload)() try: birth_time_sensitivity = _load_local_module('jyotish_engine')._build_birth_time_sensitivity(sensitivity_args) @@ -2276,6 +2304,7 @@ def execute_consultation_workflow( result = handler._high_rigor_workflow_plan_only(birth_payload, themes, events) result['birth_time_sensitivity'] = birth_time_sensitivity result['endpoint'] = 'consultation_workflow' + result['calculation_profile'] = calculation_profile result['entry_mode'] = entry_mode result['routing'] = route_packet result['unified_orchestrator'] = unified_contract @@ -2508,6 +2537,7 @@ def execute_consultation_workflow( result = { 'success': True, 'endpoint': 'consultation_workflow', + 'calculation_profile': calculation_profile, 'mode': 'vedastro_official_first_existing_modules_reused', 'entry_mode': entry_mode, 'question': question, @@ -2759,12 +2789,15 @@ def _build_api_chart_cache_payload(body: dict) -> dict: return { # 原值 7;新值 8:缓存键加 analysis_profiles(功能吉凶 profile + Narayana 各步 profile),旧缓存全部失效。 # 原因:占星师 2026-11-08 第五轮逐项答复 K3:缓存须按 profile 键控并随 profile 变化失效。 - 'cache_schema_version': 8, + # 原值 8;新值 9:缓存键再加 position_mode(交点口径本来就在 calculation.node_mode 里),旧缓存全部失效。 + # 原因:BUG-1828:缓存键显式记录交点与位置口径 + 'cache_schema_version': 9, 'analysis_profiles': {key: profiles[key] for key in ('functional_profile', 'narayana_step_profiles')}, 'birth': retention.normalize_chart_cache_birth(body), 'calculation': { 'ayanamsa': _request_ayanamsa(body), - 'node_mode': body.get('node_mode', body.get('nodeMode', 'mean')), + 'node_mode': _request_calculation_modes(body)['node_mode'], + 'position_mode': _request_calculation_modes(body)['position_mode'], 'today': retention.normalize_chart_cache_day(today), 'transit_date': retention.normalize_chart_cache_day(body.get('transit_date')), 'skip_vedastro_main_entry_overview': bool(body.get('skip_vedastro_main_entry_overview')), @@ -4363,7 +4396,7 @@ class JyotishComputeService(VedastroEvidenceMixin, SynastryMixin): 'lon': lon, 'tz': tz, 'ayanamsa': _request_ayanamsa(body), - 'node_mode': body.get('node_mode', body.get('nodeMode', 'mean')), + 'node_mode': _request_calculation_modes(body)['node_mode'], 'today': today, 'transit_date': body.get('transit_date') or body.get('reference_date'), 'target_year': target_year, @@ -5920,9 +5953,9 @@ class JyotishComputeService(VedastroEvidenceMixin, SynastryMixin): except ValueError as e: raise BadRequest('Invalid birth date') from e - node_mode = body.get('node_mode', body.get('nodeMode', 'mean')) - if not isinstance(node_mode, str) or node_mode not in {'mean', 'true'}: - node_mode = 'mean' + # 原值:非法值静默改成 mean / 新值:非法值报 400,缺省用产品默认值并标记来源 + # 原因:BUG-1828:本命计算显式传交点与位置口径 + node_mode = _request_calculation_modes(body)['node_mode'] today = body.get('today') or body.get('current_date') if not isinstance(today, str) or not today.strip(): @@ -6137,7 +6170,7 @@ class JyotishComputeService(VedastroEvidenceMixin, SynastryMixin): 'lon': lon, 'tz': tz, 'ayanamsa': _request_ayanamsa(body), - 'node_mode': body.get('node_mode', body.get('nodeMode', 'mean')), + 'node_mode': _request_calculation_modes(body)['node_mode'], }) canonical_birth = canonical_chart['birth_info'] planets_data = canonical_chart['planets'] @@ -6274,7 +6307,7 @@ class JyotishComputeService(VedastroEvidenceMixin, SynastryMixin): 'lon': lon, 'tz': tz, 'ayanamsa': _request_ayanamsa(body), - 'node_mode': body.get('node_mode', body.get('nodeMode', 'mean')), + 'node_mode': _request_calculation_modes(body)['node_mode'], }) canonical_dasha = _birth_moment_vimshottari( birth_dt=birth_dt, @@ -6390,7 +6423,7 @@ class JyotishComputeService(VedastroEvidenceMixin, SynastryMixin): 'lon': lon, 'tz': tz, 'ayanamsa': ayanamsa_name, - 'node_mode': body.get('node_mode', body.get('nodeMode', 'mean')), + 'node_mode': _request_calculation_modes(body)['node_mode'], 'today': body.get('today') or body.get('current_date'), 'transit_date': body.get('transit_date'), }) @@ -8005,6 +8038,7 @@ class JyotishComputeService(VedastroEvidenceMixin, SynastryMixin): 'range_end': body.get('range_end', body.get('rangeEnd')), 'timezone_id': body.get('timezone_id', body.get('timezoneId')), 'ayanamsa': _request_ayanamsa(body), + # 不在本单范围(declared window chart 归其他入口):保持原有隐式默认。 'node_mode': body.get('node_mode', body.get('nodeMode', 'mean')), }) except calculation_service.CalculationError as exc: diff --git a/tests/test_explicit_calculation_modes_bug1828.py b/tests/test_explicit_calculation_modes_bug1828.py new file mode 100644 index 000000000..5dd010842 --- /dev/null +++ b/tests/test_explicit_calculation_modes_bug1828.py @@ -0,0 +1,77 @@ +"""本命计算显式传入交点口径与位置口径(#185,BUG-1828)。 + +口径只认 `scripts/ondemand_calc/contract.py` 的一份定义(产品 2026-11-09 #173 拍板:mean / apparent); +缺省用默认值并标 `product_default_explicit`,`position_mode = mean` 返回 400。 +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +for path in (str(ROOT), str(ROOT / 'scripts')): + if path not in sys.path: + sys.path.insert(0, path) + +import jyotish_api_server as server # noqa: E402 + +BIRTH = {'year': 1990, 'month': 6, 'day': 15, 'hour': 10, 'minute': 20, 'lat': 31.2, 'lon': 121.5, 'tz': 8} + + +def test_defaults_come_from_the_shared_contract_and_are_marked() -> None: + modes = server._request_calculation_modes(dict(BIRTH)) + assert modes['node_mode'] == 'mean' + assert modes['position_mode'] == 'apparent' + assert modes['profile_source'] == 'product_default_explicit' + + +def test_explicit_values_are_marked_as_caller_supplied() -> None: + modes = server._request_calculation_modes({**BIRTH, 'node_mode': 'true', 'position_mode': 'apparent'}) + assert modes['node_mode'] == 'true' + assert modes['position_mode'] == 'apparent' + assert modes['profile_source'] == 'caller_supplied' + + +# 空串按「没传」处理(沿用 _request_node_mode 的旧语义),所以列在无效值里的只有真非法值。 +@pytest.mark.parametrize('value', ['vn', 'fixed', 1]) +def test_invalid_node_mode_is_a_bad_request(value) -> None: + with pytest.raises(server.BadRequest) as excinfo: + server._request_calculation_modes({**BIRTH, 'node_mode': value}) + assert 'node_mode' in str(excinfo.value) + + +def test_mean_position_mode_is_refused_with_the_named_reason() -> None: + with pytest.raises(server.BadRequest) as excinfo: + server._request_calculation_modes({**BIRTH, 'position_mode': 'mean'}) + assert 'position_mode_unsupported' in str(excinfo.value) + + +def test_unknown_position_mode_is_a_bad_request() -> None: + with pytest.raises(server.BadRequest) as excinfo: + server._request_calculation_modes({**BIRTH, 'position_mode': 'topocentric'}) + assert 'position_mode' in str(excinfo.value) + + +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['calculation']['node_mode'] == 'mean' + assert payload['calculation']['position_mode'] == 'apparent' + + +def test_cache_payload_changes_when_the_profile_changes() -> None: + default = server._build_api_chart_cache_payload(dict(BIRTH)) + node_true = server._build_api_chart_cache_payload({**BIRTH, 'node_mode': 'true'}) + assert node_true['calculation'] != default['calculation'] + assert node_true['calculation']['node_mode'] == 'true' + + +def test_defaults_are_the_single_definition_from_ondemand_calc() -> None: + from scripts.ondemand_calc import contract + + modes = server._request_calculation_modes(dict(BIRTH)) + assert modes['node_mode'] == contract.PRODUCT_DEFAULT_NODE_MODE + assert modes['position_mode'] == contract.PRODUCT_DEFAULT_POSITION_MODE