Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
27dcbd889e |
@@ -0,0 +1,117 @@
|
||||
# 生时纠正:按用途判断时间范围够不够用——绑定与扫描(后端,2026-11-16,Claude)
|
||||
|
||||
Bug 编号:BUG-1932。
|
||||
|
||||
## 背景
|
||||
|
||||
产品负责人 11-16 确认了新方向:生时纠正不再帮用户「找出准确分钟」,而是判断「用户给的时间范围够不够回答他现在问的事」。够就直接用整个范围;不够就指出范围内哪里会变、影响哪条结论。占星师 11-16 的回信确认这部分可以先上线,并指明沿用她 11-09 的用途区间方案。
|
||||
|
||||
那份方案已经在仓内,**先完整读完再动手**:
|
||||
|
||||
- 规范:`docs/tasks/assets/purpose-gate-20261109/README.md`
|
||||
- 分步计划:`docs/tasks/assets/purpose-gate-20261109/PLAN.md`
|
||||
- 状态合同参考实现与示例:同目录 `reference_gate.py`、`examples.json`
|
||||
|
||||
其中 Task 1(用途决策合同)已由 #186 完成,在 `scripts/rectification_purpose_gate/__init__.py`,目前没有任何生产入口读它。**本单做 PLAN 的 Task 2 和 Task 3:从真实计算结果构造评估事实,并扫描范围内的敏感界限。只做后端,不接任何入口。** Task 4、5(接口、页面、模型、持久化)是后面的单子。
|
||||
|
||||
## 不做的事
|
||||
|
||||
- 不接任何生产入口:不改 `frontend/`,不改 `scripts/chart_choice/service.py` 的对外行为,不改报告、年运、聊天。新模块只被新测试调用。
|
||||
- 不改评分:不动 `scripts/chart_choice/astrologer.py` 的 `score_minute`、`scan`,不动 `active_rectification_events.py::adjudicate_candidate_rows` 的阈值和 `can_apply` 语义。不要把 `score_minute` 当稳定性检测器。
|
||||
- 不重写大运:周期顺序和日期一律调用现有引擎函数(`active_rectification_event_engine.py` 里的 `_vimshottari_timeline`、`_narayana_periods`、`_narayana_antardasha_table` 或它们的公开入口)。需要对外可调用的入口就加薄包装,不复制算法。
|
||||
- 不改 `references/real_case_calibration/` 下的归档与冻结复跑脚本;`tests/test_rectification_reseal_round7_bug1809.py` 必须照旧通过。
|
||||
- 不改 `scripts/rectification_purpose_gate/__init__.py` 里已有的状态枚举和 `assess_use` 行为;只允许新增。
|
||||
- 不产生任何「校时准确率」「已找到出生时间」之类的输出字段。
|
||||
- 不查询含真实用户资料的数据库;测试只用合成输入或 `references/real_case_calibration/` 里已公开的人物。
|
||||
|
||||
## 一、移植候选差异合同
|
||||
|
||||
把占星师仓的 `scripts/active_rectification_candidates.py`(`build_candidate_difference_contract`,输出 groups、discriminators、dimension_sensitivity)移植为 `scripts/active_rectification_candidates.py`,连同她的测试 `tests/test_active_rectification_candidates.py`。源文件由 Claude 随本单放在分支的 `docs/tasks/assets/purpose-scan-20261116/` 下,文件头写明来源提交。
|
||||
|
||||
移植时只允许这几处改动,并在 PROGRESS 逐条列出:
|
||||
|
||||
1. **参数必须显式传入。** 她的默认是 `ayanamsa=raman`、`node_mode=true`,本站是 `raman`/`mean`。去掉 `request.get(..., 默认值)`,缺 `ayanamsa` 或 `node_mode` 直接报错,不沿用任何一方的默认。
|
||||
2. `boundary_time` 改名或加注:它是「新一组的首个采样点」,不是求解出的精确边界。精确边界由第三节的边界提供器给。
|
||||
3. 240 分钟上限保留为这个模块自己的限制;全天未知的范围由第三节分段调用,不在这里放宽。
|
||||
|
||||
其余算法不改。她的测试原样通过。
|
||||
|
||||
## 二、用途绑定(PLAN Task 2)
|
||||
|
||||
新建 `scripts/rectification_purpose_gate/scope.py`:
|
||||
|
||||
```python
|
||||
def build_scope_request(question: dict, original_input: dict, remaining_ranges: list,
|
||||
profiles: dict, evaluated_at: str) -> dict: ...
|
||||
def collect_scope_outputs(scope_request: dict, native_results: list) -> dict: ...
|
||||
```
|
||||
|
||||
字段按规范第三节和第六节。要点:
|
||||
|
||||
- `build_scope_request` 规范化用途并算出七个绑定指纹(`BINDING_KEYS`,已在合同模块里)。同输入指纹相同;问题主题、预测窗、输入修订号、参数、引擎版本、精度政策、候选集合任一项变化,对应指纹必须变。
|
||||
- `remaining_ranges` 是一组范围,可以不连续,可以跨午夜。不填补中间空隙,不取外包络,不取中点。端点一律转成带时区的时刻;时区或地点有歧义时返回多个明确分支或报错,不在循环里猜。
|
||||
- `collect_scope_outputs` 只消费已经算好的原生结果,自己不算任何大运。每条记录保留候选时刻、分支、参数、方法、状态、原始结果引用和依赖。缺的层写 `blocked`,不补 0;不适用的层不进 `required_layers`。
|
||||
- **用途精度政策 `purpose_policy_v1`**:一张冻结的表,把(主题,时间粒度)映射到所需的层和判定条件。先查仓内现有的问题路由有没有机器可读的层清单,有就引用它;没有就按下表建,并在文件里写明「产品约定,待占星师审核」:
|
||||
|
||||
| 主题 | 所需层(最少) |
|
||||
|---|---|
|
||||
| 事业 | D1、D10、A10、Vimshottari、Narayana |
|
||||
| 财富 | D1、D2、D11、Vimshottari、Narayana |
|
||||
| 婚恋 | D1、D9、UL、A7、Vimshottari、Narayana |
|
||||
| 整体结构(只问性格、格局) | D1、D9、月亮星宿 |
|
||||
|
||||
时间粒度取 `structure`(不问时间)、`year`、`month`、`day`。粒度决定应期边界偏移到什么程度算实质变化(见第三节)。政策版本号进绑定指纹。表里没有的主题返回 `insufficient_evidence` 所需的事实(政策缺失),不要自造宽松规则。
|
||||
|
||||
测试 `tests/test_rectification_purpose_binding.py`:PLAN Task 2 列的各条(指纹变化、缺层保留 blocked、只扫了一部分范围时 `domain_complete=false`、没有事件也能评估用途稳定性且历史证据为 `not_evaluated`、不连续范围不被合并)。
|
||||
|
||||
## 三、敏感界限扫描(PLAN Task 3)
|
||||
|
||||
新建 `scripts/rectification_purpose_gate/scan.py`:
|
||||
|
||||
```python
|
||||
def scan_scope(scope_request: dict, compute_at, boundary_providers: dict) -> dict: ...
|
||||
```
|
||||
|
||||
输出 `scan_state`(`policy_covered` / `sampled_only` / `incomplete`)、`per_layer_scan_receipts`、`output_envelopes`、`material_differences`、`stable_claim_ids`、`conditional_claim_ids`,能直接组装成 `assess_use` 的输入。
|
||||
|
||||
边界提供器,本单要给出的真实实现:
|
||||
|
||||
1. **分盘上升换座**:复用 `scripts/chart_choice/boundaries.py::find_lines`(它已按度数求解精确时刻)。所需分盘不在 `TRACKED_DIVISIONS` 里的(如 D3、D7、D11),用同一求解方法扩展,可以给 `find_lines` 传 `divisions` 参数,不要改它的默认值。
|
||||
2. **D1 上升、上升星宿、月亮星座与星宿**:同样按度数求解,不靠分钟网格。
|
||||
3. **Arudha(A1、A7、A10、UL)**:没有解析边界,用分钟网格发现变化后在相邻两点间二分到秒级,回执里写明「网格发现 + 二分」,最大未检查间隔写实际值。
|
||||
4. **大运边界**:对用途的预测窗,取范围内各候选时刻下相关 Vimshottari(到政策要求的层级)和 Narayana 周期的起止日期,给出每条边界的最早、最晚、并集、交集。提醒:出生时间差 1 分钟,Vimshottari 边界约移动 3.8 天,范围越宽包络越宽,这是预期结果,不是错误。
|
||||
|
||||
判定规则:
|
||||
|
||||
- 首尾相同但中间变过(A→B→A)必须检出;只有首尾样本、没有边界依据时只能给 `sampled_only`。
|
||||
- 应期比较不只比主星名:同名周期,边界跨过用户问的日期、月末或年末(按粒度)就是实质变化。并集只能叫「各候选的可能范围」;交集为空不生成共同窗口。
|
||||
- 相同的分数、相同的空值、相同的 `blocked` 都不产生稳定事实。
|
||||
- 与本次用途无关的层发生变化(例如问事业时 D60 变了)只记录,不影响本次结论。
|
||||
- 区分原因:`birth_time_sensitive` / `method_unresolved` / `missing_input` / `calculation_failure` / `scan_incomplete`。
|
||||
- 计算预算:`scan_scope` 接受一个预算参数(候选计算次数上限)。用完返回 `incomplete` 并写明未覆盖的区段,不得因为超时或用完预算而判稳定。
|
||||
- 引擎只接受到秒时,不声称排除了秒内变化;回执写明分辨率。
|
||||
|
||||
测试 `tests/test_rectification_purpose_scan.py`:
|
||||
|
||||
- 用确定性假函数验证扫描器本身:A→B→A;无边界提供器只有首尾样本得 `sampled_only`;给出界限后得到三段。
|
||||
- 规范第八节的 U01、U02、U03、U05、U07、U08、U09、U11、U12、U16,各一条,场景名写进用例名。
|
||||
- 真实引擎三例(用 `references/real_case_calibration/` 里的公开人物或合成出生输入):一个范围较宽但对所选用途稳定的例子;一个范围内跨已知分盘边界的例子;一个应期日期敏感的例子。每例把原始结果存成夹具,PROGRESS 里用人话写清「为什么这例是稳定/不稳定」,供人工核对。
|
||||
- 扫描结果经 `assess_use` 得到的状态与预期一致:稳定例 `scope_ready`,跨界例 `needs_refinement` 或 `conditional`。
|
||||
|
||||
## 四、命令行入口(只供人工核对)
|
||||
|
||||
`python -m scripts.rectification_purpose_gate --input <json>`:读一份合成或公开人物的输入(出生日期、范围、地点、时区、岁差、交点模式、主题、粒度、预测窗),输出完整评估对象的 JSON。不接 API。README 写在 `docs/research/rect-purpose-scan-20261116.md`,附三例真实引擎的输出摘要。
|
||||
|
||||
## 五、文档
|
||||
|
||||
- `docs/BUG_HISTORY.md` 新增 BUG-1932(只在自己那一节内编辑;不写姓名、出生资料、邮箱、ID)。
|
||||
- `CHANGELOG.md` 加一行。
|
||||
- `docs/tasks/PROGRESS-rect-purpose-scan-20261116.md`:逐节写做了什么、命令和结果、与她原模块的差异清单、没做到的。有哪条 U 场景没能在真实引擎上验证,写「未验证」,不要写成通过。
|
||||
|
||||
## 验收
|
||||
|
||||
- `PATH=<venv>/bin:$PATH python scripts/run_quality_gate.py --profile quick --skip-frontend-runtime` 通过;
|
||||
- 新增三个测试文件全部通过;`tests/test_rectification_purpose_gate.py`、`test_rectification_comparability_bug1801.py`、`test_rectification_api_can_apply_guard_bug1802.py`、`test_active_rectification_api.py`、`test_rectification_reseal_round7_bug1809.py` 照旧通过,没有删改旧断言;
|
||||
- `cd frontend && npx eslint .` 0 错误(本单不应有前端改动);
|
||||
- diff 不含 `frontend/`、`scripts/report_render/`、`references/real_case_calibration/` 的改动;`scripts/chart_choice/` 只允许 `boundaries.py` 的新增参数,默认行为不变;
|
||||
- 没有任何生产入口导入新模块(验收时会 grep)。
|
||||
@@ -0,0 +1,8 @@
|
||||
# 来源
|
||||
|
||||
两份文件原样取自占星师资料仓 `ea2a9d657451cd04615a3a7108dc92666dc8340c`:
|
||||
|
||||
- `scripts/active_rectification_candidates.py`
|
||||
- `tests/test_active_rectification_candidates.py`
|
||||
|
||||
文件名加了 `.upstream` 后缀,避免被测试收集。移植要求见 `docs/tasks/TASK-rect-purpose-scan-20261116.md` 第一节。
|
||||
@@ -0,0 +1,322 @@
|
||||
# /// script
|
||||
# requires-python = ">=3.11"
|
||||
# dependencies = []
|
||||
# ///
|
||||
# ─── How to run ───
|
||||
# .venv/bin/python -m pytest -q tests/test_active_rectification_candidates.py
|
||||
"""Sample candidate birth times and group them by material chart differences.
|
||||
|
||||
This module implements the "Candidate Difference Contract" (candidate-driven
|
||||
rectification plan Task 2). It never approves a birth time. It answers one
|
||||
question only: inside the user's uncertain interval, which minutes are
|
||||
materially the same chart, where do the material boundaries fall, and which
|
||||
technique dimensions actually discriminate between adjacent candidate groups.
|
||||
|
||||
Design rules:
|
||||
- Every sampled candidate stays inside the user interval (reversed or
|
||||
out-of-bounds intervals are rejected).
|
||||
- Adjacent samples with an identical material signature merge into one group.
|
||||
- Group boundaries are reported as discriminators with from/to values, so a
|
||||
reader can say "08:03 and 08:12 differ because D9 ascendant moves X -> Y".
|
||||
- All results are plain JSON-compatible dictionaries; no prose conclusions.
|
||||
- The shared native calculation path is reused (same as the event engine):
|
||||
domain_calculation_service.compute_chart + varga.calc_all_vargas +
|
||||
jaimini.calc_arudha_padas + dasha_analyzer.lon_to_nakshatra.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from collections.abc import Sequence
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Final, TypedDict
|
||||
from uuid import NAMESPACE_URL, uuid5
|
||||
|
||||
SCRIPTS = Path(__file__).resolve().parent
|
||||
if str(SCRIPTS) not in sys.path:
|
||||
sys.path.insert(0, str(SCRIPTS))
|
||||
|
||||
import domain_calculation_service # noqa: E402
|
||||
import dasha_analyzer # noqa: E402
|
||||
import jaimini # noqa: E402
|
||||
import narayana_dasha # noqa: E402
|
||||
import varga # noqa: E402
|
||||
|
||||
SCHEMA_VERSION: Final = "jyotish.active_rectification_candidates.v1"
|
||||
# Divisions whose ascendant sign we fingerprint. Classical local path is the
|
||||
# same production line the event engine uses for its evidence rows.
|
||||
RELEVANT_DIVISIONS: Final[tuple[int, ...]] = (2, 3, 4, 7, 9, 10, 11, 12, 24, 30, 60)
|
||||
# Arudha padas tracked as derived points: A1 = arudha lagna (self), A7 = spouse,
|
||||
# A10 = career visibility, UL = upapada (marriage visibility).
|
||||
TRACKED_ARUDHAS: Final[tuple[str, ...]] = ("A1", "A7", "A10", "UL")
|
||||
MAX_WINDOW_MINUTES: Final = 240
|
||||
MAX_SAMPLE_STEP: Final = 15
|
||||
SIGNS: Final = narayana_dasha.SIGNS
|
||||
|
||||
FINGERPRINT_DIMENSION_ORDER: Final = (
|
||||
"lagna_sign",
|
||||
"lagna_nakshatra",
|
||||
"moon_sign",
|
||||
"moon_nakshatra",
|
||||
"vimshottari_md_lord",
|
||||
*(f"varga_asc.D{division}" for division in RELEVANT_DIVISIONS),
|
||||
"arudha.A1",
|
||||
"arudha.A7",
|
||||
"arudha.A10",
|
||||
"arudha.UL",
|
||||
)
|
||||
|
||||
|
||||
def _sign_name(sign_index: int) -> str:
|
||||
return str(SIGNS[sign_index % 12])
|
||||
|
||||
|
||||
class CandidateDifferenceRequest(TypedDict):
|
||||
birth_date: str
|
||||
start_time: str
|
||||
end_time: str
|
||||
lat: float
|
||||
lon: float
|
||||
tz: float
|
||||
ayanamsa: str
|
||||
node_mode: str
|
||||
sample_step_minutes: int
|
||||
|
||||
|
||||
def _candidate_times(request: CandidateDifferenceRequest) -> list[datetime]:
|
||||
"""Return sampled candidate datetimes strictly inside the user interval."""
|
||||
birth_date = date.fromisoformat(request["birth_date"])
|
||||
try:
|
||||
start_time = time.fromisoformat(request["start_time"])
|
||||
end_time = time.fromisoformat(request["end_time"])
|
||||
except ValueError as exc:
|
||||
raise ValueError("candidate_times_invalid_format") from exc
|
||||
step = int(request.get("sample_step_minutes", 1))
|
||||
if step < 1 or step > MAX_SAMPLE_STEP:
|
||||
raise ValueError("candidate_sample_step_out_of_bounds")
|
||||
start = datetime.combine(birth_date, start_time)
|
||||
end = datetime.combine(birth_date, end_time)
|
||||
if end < start:
|
||||
raise ValueError("candidate_interval_reversed")
|
||||
total_minutes = int((end - start).total_seconds() // 60) + 1
|
||||
if total_minutes < 2:
|
||||
raise ValueError("candidate_interval_too_short")
|
||||
if total_minutes > MAX_WINDOW_MINUTES:
|
||||
raise ValueError("candidate_interval_out_of_bounds")
|
||||
sampled = [start + timedelta(minutes=offset) for offset in range(0, total_minutes, step)]
|
||||
if len(sampled) < 2:
|
||||
raise ValueError("candidate_sample_step_too_coarse")
|
||||
if sampled[-1] != end and (end - sampled[-1]).total_seconds() // 60 >= 1:
|
||||
# Keep the user-visible end minute as the final sample so the reported
|
||||
# contract always covers the declared interval edge.
|
||||
sampled.append(end)
|
||||
return sampled
|
||||
|
||||
|
||||
def _varga_chart(varga_results: dict, division: int) -> dict | None:
|
||||
return next(
|
||||
(chart for name, chart in varga_results.items() if name.startswith(f"D{division}_")),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def _material_signature(chart: dict, planet_longitudes: dict[str, float]) -> dict[str, str]:
|
||||
"""Compute the material chart fingerprint for one sampled candidate."""
|
||||
ascendant_longitude = float(chart["ascendant"]["lon"])
|
||||
ascendant_index = int(ascendant_longitude // 30)
|
||||
moon_longitude = float(planet_longitudes["Moon"])
|
||||
asc_nak = dasha_analyzer.lon_to_nakshatra(ascendant_longitude)
|
||||
moon_nak = dasha_analyzer.lon_to_nakshatra(moon_longitude)
|
||||
signature: dict[str, str] = {
|
||||
"lagna_sign": _sign_name(ascendant_index),
|
||||
"lagna_nakshatra": f"{asc_nak[0][0]} p{asc_nak[2]}",
|
||||
"moon_sign": _sign_name(int(moon_longitude // 30)),
|
||||
"moon_nakshatra": f"{moon_nak[0][0]} p{moon_nak[2]}",
|
||||
# Vimshottari Mahadasha lord is the Moon nakshatra lord.
|
||||
"vimshottari_md_lord": str(moon_nak[0][1]),
|
||||
}
|
||||
|
||||
varga_results = varga.calc_all_vargas(
|
||||
planet_longitudes,
|
||||
ascendant_longitude,
|
||||
divisions=list(RELEVANT_DIVISIONS),
|
||||
)
|
||||
for division in RELEVANT_DIVISIONS:
|
||||
dimension = f"varga_asc.D{division}"
|
||||
varga_chart = _varga_chart(varga_results, division)
|
||||
ascendant = varga_chart.get("Ascendant") if isinstance(varga_chart, dict) else None
|
||||
sign_index = ascendant.get("sign_idx") if isinstance(ascendant, dict) else None
|
||||
signature[dimension] = _sign_name(sign_index) if isinstance(sign_index, int) else "blocked"
|
||||
|
||||
arudha_result = jaimini.calc_arudha_padas(ascendant_index, planet_longitudes)
|
||||
padas = arudha_result.get("padas") if isinstance(arudha_result, dict) else None
|
||||
for key in TRACKED_ARUDHAS:
|
||||
pada = (padas or {}).get(key) if isinstance(padas, dict) else None
|
||||
sign_index = pada.get("sign_idx") if isinstance(pada, dict) else None
|
||||
signature[f"arudha.{key}"] = _sign_name(sign_index) if isinstance(sign_index, int) else "unavailable"
|
||||
|
||||
return signature
|
||||
|
||||
|
||||
def _compute_chart_for_candidate(request: CandidateDifferenceRequest, candidate_at: datetime) -> tuple[dict, dict[str, float]]:
|
||||
chart = domain_calculation_service.compute_chart({
|
||||
"year": candidate_at.year,
|
||||
"month": candidate_at.month,
|
||||
"day": candidate_at.day,
|
||||
"hour": candidate_at.hour,
|
||||
"minute": candidate_at.minute,
|
||||
"lat": request["lat"],
|
||||
"lon": request["lon"],
|
||||
"tz": request["tz"],
|
||||
"ayanamsa": request.get("ayanamsa", "raman"),
|
||||
"node_mode": request.get("node_mode", "true"),
|
||||
})
|
||||
planet_longitudes = {
|
||||
name: float(data["lon"])
|
||||
for name, data in chart.get("planets", {}).items()
|
||||
if isinstance(data, dict) and isinstance(data.get("lon"), int | float)
|
||||
}
|
||||
if "Moon" not in planet_longitudes:
|
||||
raise ValueError("candidate_chart_missing_moon")
|
||||
return chart, planet_longitudes
|
||||
|
||||
|
||||
def _merge_signature_groups(rows: Sequence[tuple[datetime, dict[str, str]]]) -> list[dict]:
|
||||
groups: list[dict] = []
|
||||
for candidate_at, signature in rows:
|
||||
if groups and groups[-1]["signature"] == signature:
|
||||
group = groups[-1]
|
||||
group["end_time"] = candidate_at.strftime("%H:%M")
|
||||
group["width_minutes"] = _width_minutes(group["start_time"], group["end_time"])
|
||||
group["sample_count"] += 1
|
||||
continue
|
||||
groups.append({
|
||||
"group_id": f"g{len(groups) + 1}",
|
||||
"start_time": candidate_at.strftime("%H:%M"),
|
||||
"end_time": candidate_at.strftime("%H:%M"),
|
||||
"representative_time": candidate_at.strftime("%H:%M"),
|
||||
"width_minutes": 1,
|
||||
"sample_count": 1,
|
||||
"signature": dict(signature),
|
||||
})
|
||||
for group in groups:
|
||||
group["signature"] = {key: group["signature"][key] for key in FINGERPRINT_DIMENSION_ORDER if key in group["signature"]}
|
||||
return groups
|
||||
|
||||
|
||||
def _width_minutes(start_time: str, end_time: str) -> int:
|
||||
start = datetime.strptime(start_time, "%H:%M")
|
||||
end = datetime.strptime(end_time, "%H:%M")
|
||||
return int((end - start).total_seconds() // 60) + 1
|
||||
|
||||
|
||||
def _build_discriminators(groups: Sequence[dict]) -> list[dict]:
|
||||
discriminators: list[dict] = []
|
||||
for previous, current in zip(groups, groups[1:]):
|
||||
changed: list[dict[str, str]] = []
|
||||
stable_dimensions: list[str] = []
|
||||
for dimension, current_value in current["signature"].items():
|
||||
previous_value = previous["signature"].get(dimension)
|
||||
if previous_value == current_value:
|
||||
stable_dimensions.append(dimension)
|
||||
else:
|
||||
changed.append({
|
||||
"dimension": dimension,
|
||||
"from": previous_value,
|
||||
"to": current_value,
|
||||
})
|
||||
discriminators.append({
|
||||
"boundary_time": current["start_time"],
|
||||
"from_group": previous["group_id"],
|
||||
"to_group": current["group_id"],
|
||||
"changed_dimensions": changed,
|
||||
"stable_dimensions": sorted(stable_dimensions),
|
||||
})
|
||||
return discriminators
|
||||
|
||||
|
||||
def _build_dimension_sensitivity(groups: Sequence[dict]) -> dict:
|
||||
dimensions = FINGERPRINT_DIMENSION_ORDER if groups else ()
|
||||
rows: dict[str, dict] = {}
|
||||
for dimension in dimensions:
|
||||
values: list[str] = []
|
||||
for group in groups:
|
||||
value = group["signature"].get(dimension)
|
||||
if value is not None and value not in values:
|
||||
values.append(value)
|
||||
changed = len(values) > 1
|
||||
rows[dimension] = {
|
||||
"values": values,
|
||||
"distinct_value_count": len(values),
|
||||
"group_count": len(groups),
|
||||
"kind": "sensitive" if changed else "stable",
|
||||
"usable_discriminator": changed,
|
||||
}
|
||||
ranking = sorted(
|
||||
(dimension for dimension in dimensions if rows[dimension]["usable_discriminator"]),
|
||||
key=lambda dimension: (-rows[dimension]["distinct_value_count"], dimension),
|
||||
)
|
||||
return {"dimensions": rows, "ranking": ranking}
|
||||
|
||||
|
||||
def _adapter_status(groups: Sequence[dict]) -> dict:
|
||||
blocked_layers: list[str] = []
|
||||
for group in groups:
|
||||
for dimension, value in group["signature"].items():
|
||||
if value in {"blocked", "unavailable"} and dimension not in blocked_layers:
|
||||
blocked_layers.append(dimension)
|
||||
return {
|
||||
"native_calculation": "available",
|
||||
"blocked_layers": sorted(blocked_layers),
|
||||
"note": "Layers listed in blocked_layers could not be computed and never count as evidence.",
|
||||
}
|
||||
|
||||
|
||||
def build_candidate_difference_contract(request: CandidateDifferenceRequest) -> dict:
|
||||
"""Sample candidate times and return groups plus discriminators (no approval)."""
|
||||
sampled = _candidate_times(request)
|
||||
rows: list[tuple[datetime, dict[str, str]]] = []
|
||||
for candidate_at in sampled:
|
||||
chart, planet_longitudes = _compute_chart_for_candidate(request, candidate_at)
|
||||
rows.append((candidate_at, _material_signature(chart, planet_longitudes)))
|
||||
|
||||
groups = _merge_signature_groups(rows)
|
||||
discriminators = _build_discriminators(groups)
|
||||
sensitivity = _build_dimension_sensitivity(groups)
|
||||
fingerprint = (
|
||||
f"{request['birth_date']}|{request['start_time']}|{request['end_time']}|"
|
||||
f"{request['lat']}|{request['lon']}|{request['tz']}|"
|
||||
f"{request.get('ayanamsa', 'raman')}|{request.get('node_mode', 'true')}|"
|
||||
f"{request.get('sample_step_minutes', 1)}"
|
||||
)
|
||||
return {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"contract_id": str(uuid5(NAMESPACE_URL, f"{SCHEMA_VERSION}:{fingerprint}")),
|
||||
"request_profile": {
|
||||
"birth_date": request["birth_date"],
|
||||
"start_time": request["start_time"],
|
||||
"end_time": request["end_time"],
|
||||
"lat": request["lat"],
|
||||
"lon": request["lon"],
|
||||
"tz": request["tz"],
|
||||
"ayanamsa": request.get("ayanamsa", "raman"),
|
||||
"node_mode": request.get("node_mode", "true"),
|
||||
"sample_step_minutes": int(request.get("sample_step_minutes", 1)),
|
||||
},
|
||||
"sample": {
|
||||
"candidate_count": len(sampled),
|
||||
"first_candidate_time": sampled[0].strftime("%H:%M"),
|
||||
"last_candidate_time": sampled[-1].strftime("%H:%M"),
|
||||
"all_candidates_within_interval": True,
|
||||
},
|
||||
"groups": groups,
|
||||
"discriminators": discriminators,
|
||||
"dimension_sensitivity": sensitivity,
|
||||
"adapter_status": _adapter_status(groups),
|
||||
"status": "candidate_groups_only",
|
||||
"claim_boundary": (
|
||||
"Candidate difference contract only; it shows where material chart "
|
||||
"changes fall inside the uncertain interval and cannot approve a birth time."
|
||||
),
|
||||
}
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
SCRIPTS = Path(__file__).resolve().parents[1] / "scripts"
|
||||
if str(SCRIPTS) not in sys.path:
|
||||
sys.path.insert(0, str(SCRIPTS))
|
||||
|
||||
import active_rectification_candidates as candidates # noqa: E402
|
||||
from jyotish_api_server import BadRequest, JyotishAPIHandler # noqa: E402
|
||||
|
||||
|
||||
def _handler() -> JyotishAPIHandler:
|
||||
return JyotishAPIHandler.__new__(JyotishAPIHandler)
|
||||
|
||||
|
||||
def _base_request(**overrides) -> dict:
|
||||
request = {
|
||||
"birth_date": "2000-01-01",
|
||||
"start_time": "08:00",
|
||||
"end_time": "08:03",
|
||||
"lat": 31.2304,
|
||||
"lon": 121.4737,
|
||||
"tz": 8,
|
||||
"ayanamsa": "raman",
|
||||
"node_mode": "true",
|
||||
"sample_step_minutes": 1,
|
||||
}
|
||||
request.update(overrides)
|
||||
return request
|
||||
|
||||
|
||||
def test_rejects_reversed_interval() -> None:
|
||||
with pytest.raises(ValueError, match="candidate_interval_reversed"):
|
||||
candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="08:05", end_time="08:00")
|
||||
)
|
||||
|
||||
|
||||
def test_rejects_out_of_bounds_interval() -> None:
|
||||
with pytest.raises(ValueError, match="candidate_interval_out_of_bounds"):
|
||||
candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="08:00", end_time="12:00")
|
||||
)
|
||||
|
||||
|
||||
def test_rejects_single_minute_window() -> None:
|
||||
with pytest.raises(ValueError, match="candidate_interval_too_short"):
|
||||
candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="08:00", end_time="08:00")
|
||||
)
|
||||
|
||||
|
||||
def test_rejects_out_of_bounds_sample_step() -> None:
|
||||
with pytest.raises(ValueError, match="candidate_sample_step_out_of_bounds"):
|
||||
candidates.build_candidate_difference_contract(
|
||||
_base_request(sample_step_minutes=16)
|
||||
)
|
||||
|
||||
|
||||
def test_rejects_step_coarser_than_interval() -> None:
|
||||
with pytest.raises(ValueError, match="candidate_sample_step_too_coarse"):
|
||||
candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="08:00", end_time="08:02", sample_step_minutes=5)
|
||||
)
|
||||
|
||||
|
||||
def test_groups_are_contiguous_and_every_candidate_stays_inside_interval() -> None:
|
||||
result = candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="08:00", end_time="08:04")
|
||||
)
|
||||
groups = result["groups"]
|
||||
assert len(groups) >= 1
|
||||
assert result["sample"]["first_candidate_time"] == "08:00"
|
||||
assert result["sample"]["last_candidate_time"] == "08:04"
|
||||
assert result["sample"]["all_candidates_within_interval"] is True
|
||||
assert result["sample"]["candidate_count"] == 5
|
||||
# Groups must tile the sampled range without gaps or overlaps.
|
||||
total_samples = sum(int(group["sample_count"]) for group in groups)
|
||||
assert total_samples == result["sample"]["candidate_count"]
|
||||
for index, group in enumerate(groups):
|
||||
if index == 0:
|
||||
continue
|
||||
previous = groups[index - 1]
|
||||
assert group["start_time"] > previous["end_time"]
|
||||
assert group["group_id"].startswith("g")
|
||||
assert group["representative_time"]
|
||||
assert group["width_minutes"] >= 1
|
||||
assert int(group["sample_count"]) >= 1
|
||||
assert group["status"] if False else True
|
||||
|
||||
|
||||
def test_members_of_one_group_share_an_identical_material_signature() -> None:
|
||||
result = candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="08:00", end_time="08:04")
|
||||
)
|
||||
for group in result["groups"]:
|
||||
signature = group["signature"]
|
||||
for dimension in (
|
||||
"lagna_sign",
|
||||
"moon_nakshatra",
|
||||
"vimshottari_md_lord",
|
||||
"varga_asc.D9",
|
||||
"varga_asc.D60",
|
||||
"arudha.A1",
|
||||
"arudha.A10",
|
||||
"arudha.UL",
|
||||
):
|
||||
assert dimension in signature
|
||||
assert signature["varga_asc.D9"] not in {"blocked", "unavailable"}
|
||||
assert signature["vimshottari_md_lord"]
|
||||
|
||||
|
||||
def test_discriminators_report_material_boundaries_with_from_to_values() -> None:
|
||||
result = candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="08:00", end_time="08:04")
|
||||
)
|
||||
groups = result["groups"]
|
||||
discriminators = result["discriminators"]
|
||||
assert len(discriminators) == len(groups) - 1
|
||||
for discriminator in discriminators:
|
||||
to_group = next(group for group in groups if group["group_id"] == discriminator["to_group"])
|
||||
from_group = next(group for group in groups if group["group_id"] == discriminator["from_group"])
|
||||
assert discriminator["boundary_time"] == to_group["start_time"]
|
||||
assert from_group["end_time"] < to_group["start_time"]
|
||||
assert discriminator["changed_dimensions"], "adjacent groups must differ somewhere"
|
||||
for change in discriminator["changed_dimensions"]:
|
||||
assert change["from"] != change["to"]
|
||||
assert change["dimension"] in candidates.FINGERPRINT_DIMENSION_ORDER
|
||||
for dimension in discriminator["stable_dimensions"]:
|
||||
assert from_group["signature"][dimension] == to_group["signature"][dimension]
|
||||
|
||||
|
||||
def test_dimension_sensitivity_marks_usable_discriminators() -> None:
|
||||
result = candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="08:00", end_time="08:04")
|
||||
)
|
||||
sensitivity = result["dimension_sensitivity"]
|
||||
assert "dimensions" in sensitivity and "ranking" in sensitivity
|
||||
rows = sensitivity["dimensions"]
|
||||
for dimension, row in rows.items():
|
||||
assert row["kind"] in {"stable", "sensitive"}
|
||||
assert row["usable_discriminator"] == (row["distinct_value_count"] > 1)
|
||||
for dimension in sensitivity["ranking"]:
|
||||
assert rows[dimension]["usable_discriminator"] is True
|
||||
for dimension in candidates.FINGERPRINT_DIMENSION_ORDER:
|
||||
assert dimension in rows
|
||||
|
||||
|
||||
def test_contract_is_deterministic_for_identical_input() -> None:
|
||||
first = candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="08:00", end_time="08:01")
|
||||
)
|
||||
second = candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="08:00", end_time="08:01")
|
||||
)
|
||||
assert first["contract_id"] == second["contract_id"]
|
||||
assert first["groups"] == second["groups"]
|
||||
assert first["discriminators"] == second["discriminators"]
|
||||
|
||||
|
||||
def test_wide_window_finds_material_changes_and_keeps_boundary() -> None:
|
||||
result = candidates.build_candidate_difference_contract(
|
||||
_base_request(start_time="04:00", end_time="06:00", sample_step_minutes=10)
|
||||
)
|
||||
assert result["sample"]["candidate_count"] == 13
|
||||
assert len(result["groups"]) >= 2, "rising vargas must produce a boundary in two hours"
|
||||
assert result["dimension_sensitivity"]["ranking"], "at least one dimension must discriminate"
|
||||
assert result["adapter_status"]["native_calculation"] == "available"
|
||||
assert result["status"] == "candidate_groups_only"
|
||||
assert "cannot approve a birth time" in result["claim_boundary"]
|
||||
|
||||
|
||||
def test_api_handler_exposes_candidate_contract() -> None:
|
||||
result = _handler()._compute_active_rectification_candidates(
|
||||
{
|
||||
"birth_date": "2000-01-01",
|
||||
"start_time": "08:00",
|
||||
"end_time": "08:04",
|
||||
"lat": 31.2304,
|
||||
"lon": 121.4737,
|
||||
"tz": 8,
|
||||
"ayanamsa": "raman",
|
||||
}
|
||||
)
|
||||
assert result["success"] is True
|
||||
assert result["endpoint"] == "active_rectification_candidates"
|
||||
assert result["schema_version"] == candidates.SCHEMA_VERSION
|
||||
assert result["request_profile"]["ayanamsa"] == "raman"
|
||||
assert result["groups"]
|
||||
assert result["claim_boundary"]
|
||||
|
||||
|
||||
def test_api_handler_rejects_reversed_interval() -> None:
|
||||
with pytest.raises(BadRequest):
|
||||
_handler()._compute_active_rectification_candidates(
|
||||
{
|
||||
"birth_date": "2000-01-01",
|
||||
"start_time": "08:05",
|
||||
"end_time": "08:00",
|
||||
"lat": 31.2304,
|
||||
"lon": 121.4737,
|
||||
"tz": 8,
|
||||
"ayanamsa": "raman",
|
||||
}
|
||||
)
|
||||
Reference in New Issue
Block a user